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 = "Janardhan"; // Invalid
let function = "gfg"; // Invalid
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 Local Variables
What are Local Variables in JavaScript?JavaScript local variables are declared inside a block ({} curly braces) or a function. Local variables are accessible inside the block or the function only where they are declared. Local variables with the same name can be used in different functions or blocks
2 min read
Variables and Datatypes in JavaScript
Variables and data types are foundational concepts in programming, serving as the building blocks for storing and manipulating information within a program. In JavaScript, getting a good grasp of these concepts is important for writing code that works well and is easy to understand. VariablesA varia
3 min read
Variables and Datatypes in JavaScript
Variables and data types are foundational concepts in programming, serving as the building blocks for storing and manipulating information within a program. In JavaScript, getting a good grasp of these concepts is important for writing code that works well and is easy to understand. VariablesA varia
3 min read
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
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
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
Difference Between Variables and Objects in JavaScript
The variables and objects are fundamental concepts but they serve different purposes. The Variables are used to store data values while objects are used to group related data and functions into a single entity. JavaScript VariableA variable in JavaScript is a named container that stores a value. It
2 min read
JavaScript Object Interview Questions
JavaScript objects are fundamental data structures used to store collections of data in key-value pairs. They are essential for handling more complex data and are often used in various JavaScript applications, such as APIs, web development, and data manipulation. We are going to discuss some JavaScr
9 min read
JavaScript Cheat Sheet - A Basic Guide to JavaScript
JavaScript is a lightweight, open, and cross-platform programming language. It is omnipresent in modern development and is used by programmers across the world to create dynamic and interactive web content like applications and browsers JavaScript (JS) is a versatile, high-level programming language
15+ min read
JavaScript Cheat Sheet - A Basic Guide to JavaScript
JavaScript is a lightweight, open, and cross-platform programming language. It is omnipresent in modern development and is used by programmers across the world to create dynamic and interactive web content like applications and browsers JavaScript (JS) is a versatile, high-level programming language
15+ min read
JavaScript Output Based Interview Questions
JavaScript (JS) is the most widely used lightweight scripting and compiled programming language with first-class functions. It is well-known as a scripting language for web pages, mobile apps, web servers, and many more. In this article, we will cover the most asked output-based interview questions
15+ min read
Difference between Java and JavaScript
Java is a statically typed, object-oriented programming language for building platform-independent applications. JavaScript is a dynamically typed scripting language primarily used for interactive web development. Despite similar names, they serve different purposes and have distinct syntax, runtime
5 min read
Difference between Java and JavaScript
Java is a statically typed, object-oriented programming language for building platform-independent applications. JavaScript is a dynamically typed scripting language primarily used for interactive web development. Despite similar names, they serve different purposes and have distinct syntax, runtime
5 min read
Java Variables
Variables are the containers for storing the data values or you can also call it a memory location name for the data. Every variable has a: Data Type - The kind of data that it can hold. For example, int, string, float, char, etc.Variable Name - To identify the variable uniquely within the scope.Val
7 min read
Java Variables
Variables are the containers for storing the data values or you can also call it a memory location name for the data. Every variable has a: Data Type - The kind of data that it can hold. For example, int, string, float, char, etc.Variable Name - To identify the variable uniquely within the scope.Val
7 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
Java Programming Basics
Java is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming console
4 min read
Java Programming Basics
Java is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming console
4 min read
Scope of Variables in Java
The scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e. scope of a variable can be determined at compile time and independent of the function call stack. In this article, we will learn about J
6 min read