Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is null a valid javascript property name?

Tags:

javascript

Javascript objects can be used as maps. The following all is valid code:

var x = {}; x.a = 1; x['b'] = 2; // the same as x.b = 2; x[3] = 3; // x.3 won't work, but this syntax works fine. Also, x[3] == x['3']. x['What, this works too?!?!?'] = 'Yup, it does!'; 

But today I tested another case which... seems to work, but raises some warning flags in my head because it looks... wrong:

x[null] = 42; 

Now, it would be extremely cool if this worked as expected (I won't have to rewrite a bunch of code then), but can I rely on it? Or maybe this is just some undocumented behavior which just happens to work in all modern browsers but might as well cease working on the next release of Google Chrome?

like image 683
Vilx- Avatar asked Mar 13 '12 16:03

Vilx-


People also ask

Is null valid in JavaScript?

Javascript null is a primitive type that has one value null. JavaScript uses the null value to represent a missing object. Use the strict equality operator ( === ) to check if a value is null . The typeof null returns 'object' , which is historical bug in JavaScript that may never be fixed.

Does null have properties in JavaScript?

The trap of null null might appear, often unexpectedly, in situations when you expect an object. Then if you try to extract a property from null , JavaScript throws an error. Because who variable is an empty string, the function returns null . When accessing message property from null , a TypeError error is thrown.

What is property of null?

null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.

Is null a object in JavaScript?

Null is not an object in JavaScript!


1 Answers

Anything between the property brackets is converted to a string. null becomes "null", which is a valid property.

like image 109
Rob W Avatar answered Sep 23 '22 02:09

Rob W