aka
for (var i = 1; i < 5; i += 1) {
var j = 1;
console.log(i);
}
console.log(i);
console.log(j);
Variable hoisting
for (let i = 1; i < 5; i += 1) {
let j = 1;
console.log(i);
}
console.log(i); // ERROR!
console.log(j); // ERROR!
const x = 5;
x = 10; // ERROR!
var divide = function(a, b) {
b = b || 2;
return a / b;
};
let divide = function(a, b = 2) {
return a / b;
};
divide(20, 4); // 5
divide(20); // 10
let fn = function(a, b = a+1) {
// ...
};
var print = function(prefix) {
var args = Array.prototype.slice.call(arguments).slice(1);
args.forEach(function(arg) {
console.log(prefix + ' : ' + arg);
});
};
print('LOG', 1, 2, 3);
let print = function(prefix, ...args) {
args.forEach(function(arg) {
console.log(prefix + ' : ' + arg);
});
};
print('LOG', 1, 2, 3);
let fn = function(a, b, c) {
...
};
let args = [1, 2, 3];
fn(...args);
let arr = [10, 20, 30];
for (let x of arr) {
// ...
}
let evenGenerator = function*() {
let i = 0;
while (true) {
i += 2;
yield i;
}
};
let g = evenGenerator();
g.next().value; // 2
g.next().value; // 4
g.next().value; // 6
[a, b] = [b, a];
let [a, b] = fnThatReturnsArray();
let [a, ...others] = fnThatReturnsArray();
let {name, age} = {name: 'tham', age: 20};
var square = function(x) {
return x * x;
};
let square = x => x * x;
let add = (x, y) => x + y;
cats.forEach(cat => {
if (cat.age < 1) {
kittens.push(cat);
}
});
var map = function(words) {
return words.map(function(word) {
return word.length;
});
};
let map = words => words.map(word => word.length);
var obj = {
eat: function(food) { },
feed: function(foodArray) {
var that = this;
foodArray.forEach(function(item) {
that.eat(item);
});
}
};
let obj = {
eat: function(food) { },
feed: function(foodArray) {
foodArray.forEach(item => this.eat(item));
}
};
return {
thisFunc: thisFunc,
thatFunc: thatFunc
};
return {
thisFunc,
thatFunc
};
var obj = {
doSomething: function(a, b) {
// ...
}
};
var obj = {
doSomething(a, b) {
// ...
}
};
doSomething(function(err, a) {
if (err) {
..
}
// ...
doAnotherThing(function(err) {
if (err) {
..
}
// ...
doYetAnotherThing(function(err, b) {
if (err) {
..
}
//...
});
});
});
doSomething()
.then(function() {
// ...
return doAnotherThing();
})
.then(function() {
// ...
return doYetAnotherThing();
})
.then(function() {
// ...
})
.catch(function(err) {
// ...
});
let timeConsumingFn = function() {
return new Promise(function(resolve, reject) {
setTimeout(resolve, 1000);
});
};
timeConsumingFn().then(function() {
console.log('Time consuming fn finished!');
});
class Cat extends Animal {
constructor(name, age) {
super(name);
this.age = age;
}
meow() {
console.log('meow!');
}
}
let cat = new Cat('kitty', 2);
cat.meow();
let add = (a, b) => a + b;
export default add;
import add from "add";
let val = add(2, 3);