Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 24 Jan, 2021

JavaScript has two scopes which are the local scope and global scope and when we directly assign a variable without declaring, it become 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 in 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:

Javascript




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

Output:



1 -> false
2 -> true
3 ->true

assigning variable without declaring it 

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




function check(){
     y = "GeeksForGeeks";
}
check();
console.log(y);

Output:

GeeksForGeeks

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

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

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

Example 3:

Javascript




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

Output:

x is a Property of Window Object

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 Reference error : x is not defined, when we assign a value to a variable without declaring it.

Example 4:

Javascript




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

Output:

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

assigning variable in strict mode




My Personal Notes arrow_drop_up
Recommended Articles
Page :