I have used two different Javascript code editor to try this. It gives two different outputs for the same code. Why it is like this ? One of them gives ‘null’ for the values, another one gives ‘undefined’.
Here the code I wrote.
let a ;
var b ;
console.log(a);
console.log(b);
CodePen
I have tried to check versions of javascript for code editors but there is no solution. thank you in advance.
2
Answers
In general, the expected value of an uninitialized variable is
undefined
:https://www.tutorialspoint.com/es6/es6_variables.htm
However, Javascript is being implemented into multiple projects and it is not surprising at all that those implementations may differ. In this case, having
null
for uninitialized variables seems to be a bug unless there is a very good reason for it, which I do not see at this point.A good approach to prevent such anomalies that come from the lack of initialization is to explicitly initialize tour variables, like
if the type of uncertainty (
null
and/orundefined
) may be meaningful in your context, you can also make a convention to initialize all variables, because it does not add much difficulty into your coding, but adds some predictability accross use-cases.This is a problem of the online editor. It seems that instead of recreating the JavaScript context each time the code is changed, it tries to reset everything the script might have set in the last run and then executes the new code.
In the case of the global variables
a
andb
, the following happens:The editor creates a list of all properties
window
has on the first run (before your code is executed), and then on each change of the code, the editor runs overall propertieswindow
has, and for those that are not in the initial list it does:While
delete
normally removes a set property and results in it beingundefined
this won’t happen in this case, soa
andb
arenull
after the second run.