Global variables are defined outside of functions or alongside window objects for use throughout the program (unless shadowed by locals). Even if you declare a variable without using var, it will still be interpreted as global.
The var statement declares a function-scoped or globally-scoped variable and optionally assigns it a value.
Example :
var x = 10;
if (x === 10) {
var x = 20;
console.log(x);
// expected output: 20
}
console.log(x);
// expected output: 20
Example: Declaring global variables within function
window.value = 90; // Declaring global variable by window object function setValue() { window.value = 100; } // Accessing global variable from other function function getValue() { setValue(); return window.value; } console.log(getValue()); // 100
Using Undeclared Variables:
- If you try to use an undeclared variable in strict mode, you’ll get a reference error when you run your code.
- If you assign a value to a name that hasn’t been declared with let, const, or var outside of strict mode, you’ll end up establishing a new global variable. It will be global regardless of how deeply nested your code is within functions and blocks, which is almost probably not what you want, is bug-prone, and is one of the strongest reasons to use strict mode!
- Global variables generated this way are similar to global variables declared using var in that they define properties of the global object. These properties, however, unlike those specified by conventional var declarations, can be erased using the delete operator.