Answer
Global variables are declared outside of a function or declared with a window object for accessibility throughout the program (unless shadowed by locals). If you declare a variable without using var, even if it's inside a function, it will still be seen as global.
The var
statement declares a function-scoped or globally-scoped variable, optionally initializing it to 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 variable 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:
- In strict mode, if you attempt to use an undeclared variable, you'll get a reference error when you run your code.
- Outside of strict mode, however, if you assign a value to a name that has not been declared with
let
,const
, orvar
, you'll end up creating a new global variable. It will be global no matter how deeply nested within functions and blocks your code is, which is almost certainly not what you want, is bug-prone, and is one of the best reasons for using strict mode! - Global variables created in this accidental way are like global variables declared with
var
: they define properties of the global object. But unlike the properties defined by proper var declarations, these properties can be deleted with the delete operator.