Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Basics
Next article icon

JavaScript Variables

Last Updated : 29 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 keyword
  • JavaScript let keyword
  • JavaScript const keyword 
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); 

Output
10 20 30 

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) 

Output
20 10 
  • 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); 

Output
10 

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] */ 

Output
[ 10, 20, 40 ] 

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

ScopeFunction scopedBlock scopedBlock scoped
UpdationMutableMutableImmutable
RedeclarationCan be redeclaredCannot be redeclaredCannot be redeclared
HoistingHoisted at topHoisted at topHoisted at top
OriginsPre ES2015ES2015(ES6)ES2015(ES6)
SupportSupported in the old version of BrowserNot supported in the old version of the BrowserNot supported in the old version of the Browser

Next Article
JavaScript Basics

S

shobhit_sharma
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-basics

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences