Execution starts with global scope, so global() gets pushed to the callstack first and gets removed last.
Set Timeout flow:
Whenever the callstack encounters a setTimeout, the callback function and the timer is sent to the web API and setTimeout is removed from the callstack. Controls continues with the next lines of code.
The web API starts the timer for given time in the background.
Once the timer is up, the callback function gets sent to the callback queue.
Now the event loop checks callstack, checks callback queue, push the function from callback queue to the callstack if callstack is empty.
Promise flow:
Whenever the callstack encounters a promise, the fetch function and the url is sent to the web API.
This would create a promise object in the memory heap. This contains the promise value and onFulfilment and onRejected placeholders.
.then and .catch lines would send the callback functions to the placeholders created in previous step.
Once fetch returns the value, the promise value is set in the promise object. Now the callback functions and the value is sent to the microtask queue.
Now the event loop checks callstack, checks microtask queue, push the function from microtask queue to the callstack if callstack is empty.
Note:
If both the queues, callback queue and microtask queue contains functions to execute, JS/event loop prioritizes the microtask queue and pushes that function to the callstack.
To use a variable's value as the key name in an object, wrap that variable with [<variable_here>]. Usually used while dynamically updating a value in the object.
Useful while updating/creating an object in a loop.
It does not change any objects or variables that existed before it was called.
Same inputs, same output. Given the same inputs, a pure function should always return the same result.
function sum(a, b) {
return a + b;
}
Functional programming:
The function and the data must be totally separated. Function should not be dependant on external variables. All requirements should be passed in parameters.
Functions are treated as first class citizens, i.e., function can be assigned to a variable, passed as an argument and also can be returned from another function.