Online coding is a crucial part of software developer job interviews. In this article, I will try to add several coding questions. These will be evaluation focused code snippets instead of task based coding questions. Additionally, I will share online code links at the end of every question.
Let’s start with one of the most well-known one:
-
In this question, closure and asynchronous code handling knowledge is assessed.
// What will be the console log of the code below? for (var i = 0; i < 4; i++) { setTimeout(() => console.log(i), 0); }It will write 4, 4, 4, 4 in console because
setTimeout()is a
asynchronous function and it will be executed afterforcycle is completed.iis defined outside scope offorloop and it will be equal to 4 whenconsole.log()starts to write.
How can you fix it to write 0, 1, 2, 3? Here is the possible solutions:
// Solution 1: for (let i = 0; i < 4; i++) { setTimeout(() => console.log(i), 0); } // Solution 2: for (var i = 0; i < 4; i++) { (function (i) { setTimeout(() => console.log(i), 0); })(i); }Solution 1: You can change declaration of
ifromvartolet
becauseletis block scoped variable butvaris function scoped variable.
Solution 2: You can wrapsetTimeout()with a function to limit
the scope ofivariable. But you should passias parameter to your IIFE (Immediately-invoked Function Expression).You can test it in below:
-
This one is about scope of this.
// What will be the logs in console? function nameLogger() { this.name = 'halil'; console.log('first:', this.name); } console.log('second:', this.name); nameLogger(); console.log('third:', this.name);Console output will be following:
second: undefined first: halil third: halilWhile “second” is executed
this.nameis undefined but afternameLogger()function is executed it will be defined. Because,thisrefers to the global object in a function. So the others log "halil" as expected.
!! It will not work with'use strict'because in a function, in strict mode,thisequalsundefinedinstead of global object.You can test it in below:
-
The last one is about
thisandbind
// What will be written? const module = { x: 55, getX: function () { console.log('x:', this.x); } }; const unboundX = module.getX; unboundX();Console output will be
x: undefinedbecausethisrefers to current owner object. So when you assign onlygetXmethod to a new objectunboundX,thiswill refers to it. And it has noxproperty, that’s whythis.xequals toundefined.
You can fix it by usingbind()as below:
const boundX = unboundX.bind(module); boundX();Now you bind module object to
unboundXfunction. Then it can reach thexproperty of module.You can test it in below:
You can read some of my other articles from the links below:
JavaScript Interview Coding Questions — 2
Halil Can Ozcelik ・ Jan 6 '20 ・ 2 min read
Top comments (0)