Variables in JavaScript can be declared using var, let, or const. JavaScript is dynamically typed, so variable types are determined at runtime without explicit type definitions.
JavaScript
var a = 10 // Old style
let b = 20; // Prferred for non-const
const c = 30; // Preferred for const (cannot be changed)
console.log(a);
console.log(b);
console.log(c);
Declaring Variables in JavaScript
1. JavaScript var keyword
var is a keyword in JavaScript used to declare variables and it is Function-scoped and hoisted, allowing redeclaration but can lead to unexpected bugs.
JavaScript
var a = "Hello Geeks";
var b = 10;
console.log(a);
console.log(b);
2. JavaScript let keyword
let is a keyword in JavaScript used to declare variables and it is Block-scoped and not hoisted to the top, suitable for mutable variables
JavaScript
let a = 12
let b = "gfg";
console.log(a);
console.log(b);
3. JavaScript const keyword
const is a keyword in JavaScript used to declare variables and it is Block-scoped, immutable bindings that can't be reassigned, though objects can still be mutated.
JavaScript
const a = 5
let b = "gfg";
console.log(a);
console.log(b);
Rules for Naming Variables
When naming variables in JavaScript, follow these rules
- Variable names must begin with a letter, underscore (_), or dollar sign ($).
- Subsequent characters can be letters, numbers, underscores, or dollar signs.
- Variable names are case-sensitive (e.g., age and Age are different variables).
- Reserved keywords (like function, class, return, etc.) cannot be used as variable names.
JavaScript
let userName = "Suman"; // Valid
let $price = 100; // Valid
let _temp = 0; // Valid
let 123name = "Ajay"; // Invalid
let function = "gfg"; // Invalid
Variable Shadowing in JavaScript
Variable shadowing occurs when a variable declared within a certain scope (e.g., a function or block) has the same name as a variable in an outer scope. The inner variable overrides the outer variable within its scope.
JavaScript
let n = 10; // Global scope
function gfg() {
let n = 20; // Shadows the global 'n' inside this function
console.log(n); // Output: 20
}
gfg();
console.log(n); // Output: 10 (global 'n' remains unchanged)
- The inner n shadows the outer n in its scope.
- The outer n is still accessible outside the function.
To read more about this follow the Article- Variable Shadowing in JavaScript
Variable Scope in JavaScript
Scope determines the accessibility of variables in your code. JavaScript supports the following types of scope
1. Global Scope
Variables declared outside any function or block are globally scoped. While var, let, and const can all have global scope when declared outside a function, their behavior differs:
- var is added to the window object in browsers.
- let and const do not attach to the window object, making them safer for modern usage.
JavaScript
var globalVar = "I am global";
let globalLet = "I am also global";
const globalConst = "I am global too";
2. Function Scope
Variables declared inside a function are accessible only within that function. This applies to var, let, and const:
JavaScript
function test() {
var localVar = "I am local";
let localLet = "I am also local";
const localConst = "I am local too";
}
console.log(localVar); // Error: not defined
3. Block Scope
Variables declared with let or const inside a block (e.g., inside {}) are block-scoped, meaning they cannot be accessed outside the block. var, however, is not block-scoped and will leak outside the block.
JavaScript
{
let blockVar = "I am block-scoped";
const blockConst = "I am block-scoped too";
}
console.log(blockVar); // Error: not defined
Interesting Facts about Variables in JavaScript
1. let or const are preferred over var: Initially, all the variables in JavaScript were written using the var keyword but in ES6 the keywords let and const were introduced. The main issue with var is, scoping.
2. var is function scoped: Can be accessed outside block if within the function.
JavaScript
if (true) {
var x = 10;
}
// Accessible outside the block
// because we are in same function
console.log(x);
3. let and const are block scoped : Cannot be accessed outside block even if inside the same function
JavaScript
if (true) {
let y = 20;
const z = 30;
}
console.log(y, z); // ReferenceError
Output:
Hangup (SIGHUP)
/home/guest/sandbox/Solution.js:5
console.log(y, z); // ReferenceError
^
4. var can be redeclared in the same scope, but let and const cannot be
JavaScript
var x = 10;
var x = 20; // Allowed
let y = 30;
let y = 40; // SyntaxError
const z = 50;
const z = 60; // SyntaxError
Output
SyntaxError: Identifier 'y' has already been declared
5. We can change elements of array or objects even if declared as const.
JavaScript
const ob = { a: 10 };
ob.a = 20; // Allowed
const arr = [10, 20, 30]
arr[2] = 40
console.log(arr) // Allowed
/* TypeError in the below lines
obj = { b: 30 };
arr = [50, 100] */
When to Use var, let, or const
- We declare variables using const if the value should not be changed
- We should use let if we want mutable value or we can not use const
- We use var only if we support old browser.
To learn more about the scope of variables refer to this article Understanding variable scopes in JavaScript
Comparison of properties of let, var, and const keywords in JavaScript:
Property | var | let | const |
---|
Scope | Function scoped | Block scoped | Block scoped |
Updation | Mutable | Mutable | Immutable |
Redeclaration | Can be redeclared | Cannot be redeclared | Cannot be redeclared |
Hoisting | Hoisted at top | Hoisted at top | Hoisted at top |
Origins | Pre ES2015 | ES2015(ES6) | ES2015(ES6) |
Support | Supported in the old version of Browser | Not supported in the old version of the Browser | Not supported in the old version of the Browser |
Similar Reads
JavaScript Course Variables in JavaScript
Variables in JavaScript are containers that hold reusable data. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory loca
4 min read
JavaScript Syntax
JavaScript syntax refers to the rules and conventions dictating how code is structured and arranged within the JavaScript programming language. This includes statements, expressions, variables, functions, operators, and control flow constructs. Syntax console.log("Basic Print method in JavaScript");
6 min read
What is JavaScript?
JavaScript is a powerful and flexible programming language for the web that is widely used to make websites interactive and dynamic. JavaScript can also able to change or update HTML and CSS dynamically. JavaScript can also run on servers using tools like Node.js, allowing developers to build entire
6 min read
How to Use Dynamic Variable Names in JavaScript?
Dynamic variable names are variable names that are not predefined but are generated dynamically during the execution of a program. This means the name of a variable can be determined at runtime, rather than being explicitly written in the code. Here are different ways to use dynamic variables in Jav
2 min read
JavaScript Basics
JavaScript is a versatile, lightweight scripting language widely used in web development. It can be utilized for both client-side and server-side development, making it essential for modern web applications. Known as the scripting language for web pages, JavaScript supports variables, data types, op
6 min read
JavaScript Object Constructors
An object is the collection of related data or functionality in the form of key. These functionalities usually consist of several functions and variables. All JavaScript values are objects except primitives. const GFG = { subject : "programming", language : "JavaScript",}Here, subject and language a
4 min read
JavaScript Interview Questions and Answers (2025) - Intermediate Level
In this article, you will learn JavaScript interview questions and answers intermediate level that are most frequently asked in interviews. Before proceeding to learn JavaScript interview questions and answers â intermediate level, first we learn the complete JavaScript Tutorial, and JavaScript Inte
6 min read
JavaScript Programs
JavaScript Programs contains a list of articles based on programming. This article contains a wide collection of programming articles based on Numbers, Maths, Arrays, Strings, etc., that are mostly asked in interviews. Table of Content JavaScript Basic ProgramsJavaScript Number ProgramsJavaScript Ma
13 min read
Java Variables
In Java, variables are containers that store data in memory. Understanding variables plays a very important role as it defines how data is stored, accessed, and manipulated. Key Components of Variables in Java: A variable in Java has three components, which are listed below: Data Type: Defines the k
9 min read
Rules For Variable Declaration in Java
Variable in Java is a data container that saves the data values during Java program execution. Every variable is assigned a data type that designates the type and quantity of value it can hold. Variable is a memory location name of the data. A variable is a name given to a memory location. For More
2 min read