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 Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read