Open In App

What happen when we directly assign the variable without declaring it in JavaScript ?

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript has two scopes which are the local scope and global scope and when we directly assign a variable without declaring, it becomes a global property of the window object. The window is the object of the browser. It is not the object of JavaScript. It is automatically created by the browser and it can be accessed from anywhere on the web page.

Let us assign a value to a variable x without declaring it and check with the help of hasOwnProperty() method, whether variable x belongs to the window object or not.

Example 1: This example checks the above approach.

Javascript




<script>
    // Before x is not assigned
    console.log(`${window.hasOwnProperty('x')}`);
      
    x= 2; // Assigning x without declaring it
      
    console.log(`${window.hasOwnProperty('x')}`);
      
    // To show both value refers to same object
    console.log(`${window.x === x}`);
</script>


Output:

false
true
true

Example 2: In the below example, variable x is assigned value without declaring it, so it will become a global property and can be accessed from anywhere.

Javascript




<script>
    function check(){
     y = "GeeksForGeeks";
    }
    check();
    console.log(y);
</script>


Output:

GeeksForGeeks

We can also access this value as the window.x. So the function check() can also be written like the following-

function check(){
    window.x = "GeeksForGeeks";
}

Example 3: We can also show that the assigning value without declaring it became a property of the window object with the help of hasOwnProperty().

Javascript




<script>
    function check(){
    x = "GeeksForGeeks";
    }
    check();
    if(window.hasOwnProperty('x')){
    console.log(`x is a Property of Window Object`);
    }
</script>


Output:

x is a Property of Window Object

Example 4: We can use strict mode which is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. It will throw a Reference error: x is not defined when we assign a value to a variable without declaring it.

Javascript




<script>
    'use strict' // For strict mode
    try{
    function check(){
      
        x = "GeeksForGeeks";
    }
    check();
      
    } catch(err){
         
    console.log(err);
    }
</script>


Output:

ReferenceError: x is not defined
    at check (<anonymous>:5:11)
    at <anonymous>:7:5


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads