By: Colten Rouska
var something = {};
if(something){ ... }
var logger = require('logger');
function addTwo(num1, num2){
logger.log('adding some numbers');
return num1 + num2;
}
function addTen(num){
return num + 10;
}
var multiByThree = function(num){
return num * 3;
}
module.exports = {
addTwo: addTwo,
addTen: addTen,
multiBythree: multiByThree
};
import logger from 'logger';
let addTwo = (num1, num2) => {
logger.log('adding some numbers');
return num1 + num2;
};
function addTen (num) {
return num + 10;
};
let multiByThree = num => {
return num * 3;
}
export default {
addTwo,
addTen,
multiByThree
};
Variable hoisting
lexical scoping
undefined and NaN are not constants. They are global variables, and you can change their values. That should not be possible, and yet it is. Don’t do it.
function example(){
if(context){
var text = 'right';
// What is text?
} else {
// is text accessible here?
// if it is, what is it?
}
return text; // Is text out here?
}
function example(){
var text;
if(context){
text = 'right';
// text is 'right'
} else {
// text is defined but will return undefined
}
return text; // if context is true text = 'right' else undefined
}
function example(){
if(context){
let text = 'right';
// What is text?
} else {
// is text accessible here?
// if it is, what is it?
}
return text; // Is text out here?
}
Named Functions
Object Variables
Classes vs Closures
Objects are passed around by reference. They are never copied
let myFunctions = {
doThings: function(){
throw new Error('broken');
},
doStuff: function doStuff(){
throw new Error('broken');
}
};
What is the difference?
function MyClass() {}
MyClass.prototype.doThings = function(){
throw new Error('Broken');
};
MyClass.prototype.doStuff = function doOtherStuff() {
throw new Error('Broken');
};
var fruit = {
apple: {},
banana: {},
'orange': {} // does the string change anything?
};
// Does this get apple?
var apple = fruit.apple;
// Does this get banana?
var banana = fruit['banana'];
What is the difference?
function(logger) {
return {
logThings: function(text){
logger.log(text);
};
};
}
What is the difference? Is there a difference?
class MyClass {
constructor(logger){
this.logger = logger;
}
logStuff: function(text){
this.logger.log(text);
}
}
function MyClass(logger) {
this.logger = logger;
}
MyClass.prototype.logStuff = function (text) {
this.logger.log(text);
};
Few classical programmers found prototypal inheritance to be acceptable, and classically inspired syntax obscures the language’s true prototypal nature. It is the worst of both worlds.
Objects are passed around by reference. They are never copied
undefined and NaN are not constants. They are global variables, and you can change their values. That should not be possible, and yet it is. Don’t do it.
When used inside of a function, the var statement defines the function’s private variables.