Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
JavaScript always initializes, and then declares variables.
function hoist() {
a = 20;
var b = 100;
}
hoist();
console.log(a);
/*
Accessible as a global variable outside hoist() function
Output: 20
*/
console.log(b);
/*
Since it was declared, it is confined to the hoist() function scope.
We can't print it out outside the confines of the hoist() function.
Output: ReferenceError: b is not defined
*/
-
When a function is created, the JavaScript engine adds a prototype property to the function.
-
This prototype property is an object. It has a constructor property by default.
-
The constructor property points back to the function on which prototype object is a property
-
An object's prototype is a pointer to another object.
-
It will follow the prototype chain until it sees a null value, when it will return undefined.
const person = {
kind: "person"
}
const female = {
gender: "female"
}
const Mae = Object.assign({}, person, female)
return Mae.gender // female
return Mae.kind // person
- A closure gives you access to an outer function's scope from an inner function.
- To use a closure, simply define a function inside another function and expose it. To expose a function, return it or pass it to another function.
const getSecret = (secret) => {
return {
get: () => secret
}
}
const obj = getSecret("this is a secret")
-
A promise is an object which can be returned synchronously from an asynchronous function.
-
It will be in 1 of three possible states
- Fulfilled
- Rejected
- Pending
-
ES6 has a promise constructor
-
I've done this using axios and fetch
const wait = time => new Promise((resolve) => setTimeout(resolve, time));
wait(3000).then(() => console.log('Hello!')); // 'Hello!'