JavaScript inquiries
I had some time ago one of the most, probably THE most exciting and nice job interview in my whole life!
Near the end of the interview I had to solve some interesting JS problems.
One of them was to write a function which validates both of these:
console.log(sum(2,3)); console.log(sum(2)(3));
The solution is this:
function sum(a,c) { if (c !== undefined) { return a + c; } return function(b) { return a + b; } }
If you ask me, this is a really nice little exercise!!
The second one was a for loop like this:
for (var i = 0; i < 5; i++) { setTimeout(function() {console.log(i);}, i * 1000); }
This exercise had to be implemented in order to print i like this:
0
1
2
3
4
The solution?
Using ES6 change var to let. Or, use a closure like this:
for (var i = 0; i < 5; i++) { (function(a){ setTimeout(function() {console.log(a);}, a * 1000); })(i); }
This had to implement block scope! Nice huh?
PS: Thank you Nicolas for the most interesting interview ever! He used a tool like this here: https://coderpad.io! Super cool stuff!
UPDATE: Of course, I did not pass to the next round, I blew it somehow! But, I earned an important insight out of this interview! I NEED TO STUDY JS MORE. Pure JS that is… no frameworks, no libraries! Yep! Lesson learnt!