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.
Recommended Posts
View AllDifferences between JavaScript Map and Object
Discover the key dissimilarities between JavaScript Map and Object. Learn how they store data, handle key collisions, and their performance trade-offs...
Understanding Hoisting in JavaScript
Learn about hoisting in JavaScript: how variables and functions are moved to the top of their scope during compilation, affecting code behavior.
JavaScript's Lambda and Arrow Functions
Lambda and arrow functions in JavaScript allow for concise and elegant code. Learn how to use them to streamline your code and improve readability.
What is memoization?
Memoization is a programming technique that improves efficiency by caching results of expensive function calls. Learn more about it here.
Difference between Function, Method and Constructor calls in JavaScript
You are probably used to thinking about functions, methods, and class constructors as three distinct things if you are experienced with object-oriente...