skip to Main Content

Consider the following code snippets:

// Using var
var val = 20;
console.log(window.val); // Outputs: 20
// Using let
let val = 20;
console.log(window.val); // Outputs: undefined

In both cases, val is declared in the global scope, yet accessing window.val returns undefined when using let, while it correctly returns 20 when using var.

How var and let differ in their interaction with the global object (window in a browser environment).

3

Answers


  1. There are two points in here:

    1. variables declared with var in the global scope are added as a properties to the global object and making them accessible as properties of that object.
    2. variables declared with let and const in the global scope are not added as a properties to the global object. They exist in the scope but do not create properties on the global object
    Login or Signup to reply.
  2. From- JavaScript: The Definitive Guide

    Globals declared with var are implemented as properties of the global
    object. The global object can be referenced as globalThis. So if you
    write var x= 2 outside of a function, it is like you wrote
    globalThis.x = 2.

    Global variables and constants declared with let and const are not
    properties of the global object.

    In web browsers, the Window object serves as the global object for all JavaScript code
    contained in the browser window it represents. This global Window object has a self referential window property that can be used to refer to the global object.

    Login or Signup to reply.
  3. Yes, It is undefined Here it is why?

    • When you declare a variable with var, it is hoisted to the top of its scope (including the global scope) and becomes a property of the global object. Hence, when you access window.val after declaring var val = 20, you can retrieve its value, which is 20.

    • On the other hand, variables declared with let have block scope, meaning they are only accessible within the block in which they are defined. In this case, the block is the global scope. However, unlike var, let variables are not added as properties to the global object. Therefore, when you try to access window.val after declaring let val = 20, it returns undefined because val is not a property of the global object.

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