Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning value to undefined in JavaScript

I was writing some code in JavaScript. When I accidentally came across this.

undefined = 'some value' //does not give any error

true = 'some value';   //gives error

null = 'some value';   //gives error

How is it that first statement is valid whereas the other two are invalid. From what I know both undefined, true, and null are values you can assign to some variable, so all these should be invalid statements.

like image 747
user_rj Avatar asked Jul 06 '17 07:07

user_rj


People also ask

Can you set a value to undefined in JavaScript?

Javascript has a delete operator that can be used to delete a member of an object. Depending on the scope of a variable (i.e. if it's global or not) you can delete it to make it undefined. There is no undefined keyword that you can use as an undefined literal.

What is the value of undefined in JavaScript?

The undefined property indicates that a variable has not been assigned a value, or not declared at all.

How do you assign an undefined string?

The typescript compiler performs strict null checks, which means you can't pass a string | undefined variable into a method that expects a string . To fix this you have to perform an explicit check for undefined before calling luminaireReplaceLuminaire() .


2 Answers

From MDN:

undefined is a property of the global object; i.e., it is a variable in global scope. The initial value of undefined is the primitive value undefined.

Hence, you can assign the value to undefined unlike true and null which are reserved keywords. Note that this is the same case with NaN as well which is again not a reserved keyword and hence, you can assign any value to it.


Just to add more to this, it doesn't matter even if you are assigning a value to undefined, it will not write to it as it is a readonly property.

Quoting from MDN again.

In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property per the ECMAScript 5 specification. Even when this is not the case, avoid overriding it.

enter image description here


Prefer using strict-mode in your JavaScript by declaring "use strict" at the very top of the file or inside a function to avoid such things. Using something like

"use strict";
undefined = 'test'; //will raise an error, refer to [1]

[1] VM1082:2 Uncaught TypeError: Cannot assign to read only property 'undefined' of object '#'

like image 138
Mr. Alien Avatar answered Sep 17 '22 18:09

Mr. Alien


This is because undefined is not a reserved word in JavaScript, even though it has a special meaning. So it can be assigned a value and the whole statement is valid. Whereas true and null are reserved words and can't be assigned values.

For reference: JavaScript Reserved Words

like image 21
Dij Avatar answered Sep 17 '22 18:09

Dij