H S

Posted on

# f**ing quirk(s) in JS that show(s) up mostly in the interviews - I

It was a part of an interview under the pen-pressure of "do it under 15 minutes". The questions were eight MCQs. And then it started.

Q1. What will be output of this code?

function f(x){ x+=1 }
function g(x) { x.value *= 5 }
var a;
var b = 1;
var c = {value: 2};
var d = c;
console.log(a, b, c.value, d.value);

Choices -

1. NaN 2 2 10
2. 1 2 2 10
3. undefined 1 10 10
4. undefined 1 2 2

Submitted choice - (2)

Defence - a is undefined, so += will automatic typecast it to a number, which should be 0 and that makes resultant to be 1. So, (2). But, that's wrong;

Quirk (focus: console.log(a);) - While something undefined is operated on +=, the operand is automatically typecast-ed to a number resulting in NaN, but not a 0. Hence, wrong.

Another quirk - The answer is not just wrong. It is wrong * 2; How? (focus: console.log(b)). The value of b is globally defined to 1; so f(b) should just up it by 1 and b is primitive by design and as a resultant b should be 2. But, that's wrong. function(){} changes the play. That syntax creates a new scope. And the values passed to the function as arguments are copied into that scope. Now with that signature of function definition, in a newly created scope, the primitive nature of the argument passed, makes the operation limited in that scope. Though, that's how functions natively works, but, still, a quirk worth remembering.

So, nothing comes out of that scope?
Another another quirk - No. So, console.log(d.value), copies the reference into the scope and that's easy - changing references updates the values across the scopes. And this was missed while choosing the answer since I sort-of knew that there is no way c.value and d.value would differ in this context. And the choice(2) doesn't support that. Now, that's haste, I think.

Contd. in next part.