Interesting javascript hack, you should know
1. Javascript Closures
A closure is an inner function that accesses to the outer function’s variables.
It has three scopes (access variables)
- Own scope (variables defined between its curly brackets)
- Outer function’s variables
- Global variables
Note: will amaze with the output of this code, because most of the developer think its output is 0.
Example :
var a = [];
for(var i=0;i<3;i++) {
a[i] = function() {
return i;
}
}
console.log(a[0]());
Output:
3
Tried in console
2. Async Javascript -setTimeout function within closure
Example :
console.log(1);
setTimeout(function(){
console.log(2);
}, 0);
console.log(3);
Output:
1
3
undefined
2
These are some tricky javascript concept asked in google and amazon interview's
Amazon web developer interview question https://www.reddit.com/r/javascript/comments/7535tm/amazon_web_developer_loop_timeout_interview/