Objects are key-value collections.
const user = {
name: "Sam",
age: 20,
};
console.log(user.name);
console.log(user["age"]);A method is a function stored on an object.
const counter = {
value: 0,
inc() {
this.value += 1;
},
};
counter.inc();
console.log(counter.value); // 1this depends on how a function is called.
const obj = {
x: 1,
show() {
return this.x;
},
};
const f = obj.show;
console.log(obj.show()); // 1
console.log(f()); // undefined in strict mode (or global object in sloppy mode)Arrow functions capture this from the surrounding scope.
const [a, b] = [1, 2];
const { name, age: years } = { name: "A", age: 10 };
console.log(a, b, name, years);Defaults:
const [x = 0] = [];
const { ok = false } = {};- Function declarations are hoisted (callable before definition).
vardeclarations are hoisted (initialized toundefined).let/constare hoisted but in the Temporal Dead Zone until initialized.
hoisted();
function hoisted() {
console.log("works");
}A closure is when a function retains access to variables from its outer scope.
function makeCounter() {
let n = 0;
return () => {
n += 1;
return n;
};
}
const c = makeCounter();
console.log(c()); // 1
console.log(c()); // 2HOFs take functions as arguments or return functions.
const once = (fn) => {
let used = false;
let value;
return (...args) => {
if (!used) {
used = true;
value = fn(...args);
}
return value;
};
};