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.
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.
The undefined property indicates that a variable has not been assigned a value, or not declared at all.
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() .
From MDN:
undefined
is a property of the global object; i.e., it is a variable in global scope. The initial value ofundefined
is the primitive valueundefined
.
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.
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 '#'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With