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;

  // expected output: 20

// 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() {
  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

How do you decode or encode a URL in JavaScript?

Learn how to encode and decode URLs in JavaScript with this comprehensive guide. Avoid common mistakes and ensure data security. Read more now.

JavaScript Template Literals Explained

JavaScript template literals are one of JavaScript's most powerful capabilities. They enable us to generate dynamic strings without the need for conca...

Learn JavaScript Closures with Code Examples

Master JavaScript closures with code examples! Our comprehensive guide explains how closures work and how to use them in your code. Start learning now...

What is JSON? Know how it Works with Examples

Learn what JSON is and how it works with examples in this comprehensive guide. Discover the basics of JSON syntax, its applications, and why it has be...

10 JavaScript Tricks Every Developer Should Know

I'll show you several JavaScript tricks for optimizing your JavaScript code. Use these JavaScript tricks to optimize your JavaScript code.