user777 user777 - 2 months ago 8
Javascript Question

Why doesn't assigning a value to undefined produce an error in modern browsers?

For example imagine the following expression:

undefined = "whatever";


The value of
undefined
isn't change by this, but it doesn't produce any error or exception whatsoever either, neither in Firefox, Chrome, Edge nor IE11.

Actually the value of the expression is even the assigned value instead of
undefined
:

var x = (undefined = "whatever");


Now
x
holds the value
"whatever"
.

This seems weird on the one hand, but worse, a source for bugs on the other hand because nobody should even attempt to redefine
undefined
, and typos that result in doing so should be caught by the engine. Why would that fly?

Compare to the behavior when trying to redefine other keywords, for example:

for = 12345;


This yields
"Uncaught SyntaxError: Unexpected token ="
as it rightly should.

Answer

Because js has to be backwards compatible and at some time it was introduced that way. To tackle this problem strict mode was introduced. While using strict mode undefined = "whatever" will throw an error.

Comments