Skip to content

Instantly share code, notes, and snippets.

View singhArmani's full-sized avatar
🎯
Focusing

Amandeep Singh singhArmani

🎯
Focusing
View GitHub Profile
// After understanding static scoping and thus closures.
// Without static scoping, there's no concept of closures.
let array = [];
for (var i = 0; i < 3; i++) {
// invoking the function to capture (closure) the variable's current value in the loop.
array[i] = (function(x) {
return function() {
return x;
};
})(i);
// Using ES6 block-scoped binding
var array = [];
for (let i = 0; i < 3; i++) {
// This time, each 'i' refers to the binding of one specific iteration
// and preserves the value that was current at that time.
// Therefore, each arrow function returns a different value.
array.push(() => i);
}
var newArray = array.map(el => el());
console.log(newArray); // [0, 1, 2]
// Misunderstanding scope:thinking that block-level scope exist here
var array = [];
for (var i = 0; i < 3; i++) {
// Every 'i' in the bodies of the three arrow functions referes to the same binding,
// which is why they all return the same value of '3' at the end of the loop.
array.push(() => i);
}
var newArray = array.map(el => el());
console.log(newArray); // [3, 3, 3]
var a = 10; // global scope
function foo() { // enter new scope, TDZ starts
// Uninitialised binding for 'a' is created
console.log(a); // ReferenceError
// TDZ ends, 'a' is intialised with value of 20 here only
let a = 20;
}
var a = 10; // global scope
function foo() {
// Declaration of var a will be hoisted to the top of function.
// Something like: var a;
console.log(a); // prints undefined
// actual intialisation of value 20 only happens here
var a = 20; // local scope
}
var x = 10;
var foo = {
x: 90,
getX: function() {
return this.x;
}
};
foo.getX(); // prints 90
var xGetter = foo.getX;
xGetter(); // prints ??
var obj = { a: 1, b: 2 };
Object.setPrototypeOf(obj, {c: 3});
Object.defineProperty(obj, 'd', { value: 4, enumerable: false });
// what properties will be printed when we run the for-in loop?
for(let prop in obj) {
console.log(prop);
}
var obj = { x: 1, y: 2, z: 3 };
[...obj]; // TypeError
function foo() {
return Promise.resolve().then(foo);
};
function foo() {
setTimeout(foo, 0); // will there by any stack overflow error?
};