JavaScript Puzzlers: Dive into Intriguing Code Snippets

Vineet Mishra
2 min readJun 15, 2024

--

Closures and Loops:

Wait don’t jump into solutions think again……..

Solutions: This will output 6 five times after a delay of 1000ms. This happens because the setTimeout function creates closures over variables, and by the time the function inside setTimeout executes, the loop has already finished and i is 6.

To fix this using ES6 let declaration which has block scope and it will give each setTimeout a different copy of the i

NaN (Not a Number):

Wait don’t jump into solutions think again……..

NaN is a numeric data type that is produced when a mathematical operation has an undefined or unrepresentable result.

Scope and Variable Hoisting:

Wait don’t jump into solutions think again……..

JavaScript variables declared with var are hoisted to the top of their scope, but not their initialisations.

Implicit Type Conversion:

Wait don’t jump into solutions think again……..

JavaScript performs implicit type conversion (“type coercion”) when operands are of different types in an expression.

--

--

Vineet Mishra

SDE 2 at Accelya , I write about Mobile/Web Development and Deployment, and Interview Q & A