typeof Operator with Assignment in JavaScript – A Publicis Sapient Interview Question. Javascript interview prepratiron.


Understanding the Code Step by Step

The given JavaScript snippet involves variable assignment and the typeof operator. Let’s analyze how JavaScript processes it.


Javascript Code:

var z = 1, y = z = typeof y;
console.log(y);

Step 1: Breaking Down Variable Declarations

var z = 1;

  • Here, z is declared and assigned the value 1.

y = z = typeof y;

  • The key part here is right-to-left assignment (= assigns values from right to left).
  • We evaluate typeof y first and then assign the result to z, and then assign z to y.


Step 2: Evaluating typeof y

  • At this point in execution, y has not been explicitly assigned a value, so it is undefined.
  • The typeof operator returns a string representation of the data type.

typeof y; // "undefined"

Step 3: Assigning the Value

z = typeof y; // z = "undefined"
y = z; // y = "undefined"

Step 4: Logging the Output

console.log(y);

Since y is now "undefined" (a string), the output is:

"undefined"

Final Output

"undefined"

Remember key points:

  1. Assignment (=) in JavaScript happens from right to left.
  2. typeof always returns a string, even when checking undefined.
  3. Variables declared with var are hoisted, meaning y exists but is undefined before assignment.
  4. The final value of y is "undefined" (a string), not undefined (a primitive type).


✔ Final Answer:

B) undefined

This question appeared in the Publicis Sapient 2nd round of interview, testing the candidate’s knowledge of assignment operator (=) and typeof operator in JavaScript.

Post a Comment

Previous Post Next Post