javascriptvariablesglobal-variablesglobal-object

Is there any difference between var a = something and window.a = someting?


I'm new to the JavaScript World and I'm confused after I knew a lot about the global object (usually window) and knew it's just an object like any object I'd create and that var set properties in the global object unlike let

after that Is there any difference between window.a = something (like in any object) and var a = something?


Solution

  • In the global context, using var vs assigning to window are indeed quite similar. However, yes there are a number of differences. Here are a few I can think of:


    // This is okay. The variable declaration is hoisted, so you can use it before
    // it's been declared (although it won't be assigned its value until later).
    console.log(a);
    var a = "hello world";

    // On the other hand, without var, this creates an error.
    console.log(a);
    window.a = "hello world";


    var a = "hello world";
    
    console.log(a);
    delete window.a; // Does nothing for `var`.
    console.log(a);

    window.a = "hello world";
    
    console.log(a);
    delete window.a; // This will delete it, further access creates a ReferenceError.
    console.log(a);


    function foo() {
      var a = "hello world";
      console.log(a);
    }
    
    foo();
    console.log(a); // ReferenceError

    function foo() {
      window.a = "hello world";
      console.log(a);
    }
    
    foo();
    console.log(a); // still exists here