skip to Main Content

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
enter image description here

enter image description here

I have tried to check versions of javascript for code editors but there is no solution. thank you in advance.

2

Answers


  1. In general, the expected value of an uninitialized variable is undefined:

    Variable hoisting allows the use of a variable in a JavaScript program, even before it is declared. Such variables will be initialized to undefined by default. JavaScript runtime will scan for variable declarations and put them to the top of the function or script. Variables declared with var keyword get hoisted to the top.

    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

    let x = undefined;
    

    if the type of uncertainty (null and/or undefined) 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.

    Login or Signup to reply.
  2. 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 and b, 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 properties window has, and for those that are not in the initial list it does:

    window[key] = null;
    delete window[key];
    

    While delete normally removes a set property and results in it being undefined this won’t happen in this case, so a and b are null after the second run.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search