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 All

What's the difference between undefined and not defined in JavaScript


undefined?and?not defined?in JavaScript refer to memory space in JavaScript, but there is a very clear distinction between them

Difference between var and let in JavaScript


Learn the difference between var and let in JavaScript. Understand variable hoisting, scope, and how they affect your code's behavior. Get started now...

What is currying function in JavaScript ?


Currying function in JavaScript allows you to transform a function that takes multiple arguments into a series of functions that each take one arg.

What is prototype and prototype chaining in JavaScript


This article explains the concept of prototype and prototype chaining in JavaScript. Learn how prototypes work, how they are used to create inheritanc...

What is memoization?


Memoization is a programming technique that improves efficiency by caching results of expensive function calls. Learn more about it here.