user777 user777 - 1 year ago 84
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
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

var x = (undefined = "whatever");

holds the value

This seems weird on the one hand, but worse, a source for bugs on the other hand because nobody should even attempt to redefine
, 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download