JavaScript Variables

JavaScript-Variables-Blog-image.jpg

In any programming language, variables are just like storage containers that are used to store data. They help us store information like numbers, text, or even complex data like objects and arrays. In programming, JavaScript variables are used to store values and use them later in the code. JavaScript is a dynamically typed language, which means you don’t need to define the type of a variable beforehand. In this blog, you will learn everything about JavaScript variable declaration, JavaScript variable scope, different ways of declaring JavaScript variables, and best practices for using JavaScript variables.

Table of Contents:

What are JavaScript Variables?

JavaScript variables are used to store data that you can use later in the program. Variables in JavaScript are used to store values such as names, numbers, or lists of values. Here is the basic syntax to create JavaScript variables.

Syntax:

let name = "Intellipaat";
let year= 2008;

In the above code, you store the values “Intellipaat” and 2008 in the variables called name and year. You can use these variables anywhere inside the code and also print their values by using the console.log() method.

Rules for Naming Variables

There are some rules to create JavaScript variables. These rules help you to understand how to create a valid JavaScript variable for storing data. Here are the most important rules for creating JavaScript variables:

  • A variable name must begin with a letter, underscore, or a dollar sign, not with a number in JavaScript.
  • JavaScript variable names are case sensitive, which means name and Name both are different variables in JavaScript.
  • JavaScript has some special words, like function, const, return, etc (called keywords). JavaScript didn’t allow you to use the keyword name as a variable.
  • The variable names cannot contain spaces in JavaScript.
Launch Your Web Development Career
Start Learning Now
quiz-icon

Different Methods of JavaScript Variable Declaration

Variables in JavaScript are the way to store data and use it in multiple places. You have three major ways to declare variables in JavaScript. Let’s discuss var vs let vs const in JavaScript and how each keyword works in different situations.:

1. JavaScript var Keyword

The var keyword in JavaScript is one of the oldest ways to declare variables in JavaScript. The var is a function-scoped variable, which means the variables declared using the var keyword are only accessible within the function, not outside the function.

Example:

var name = "Intellipaat!"
console.log(name);

Output:

JavaScript var keyword

2. JavaScript let Keyword

The let keyword was introduced in ES6 (ECMAScript 2015) and, along with const (explained in the next section), has become the modern standard for declaring variables. Unlike var, let is block-scoped, meaning it is only accessible within the {} where it is defined. This helps developers avoid unexpected bugs and write safer, more predictable code.

Example:

{
let name = "Intellipaat!"
console.log(name);
}
console.log(name);

Output:

JavaScript let keyword

Explanation: In this example, the name variable is declared by using let keywords inside { }. The first console.log(name), which is written inside the {}, prints Intellipaat, and the second console.log(name) shows you a ReferenceError because the let keyword is block-scoped.

3. JavaScript const Keyword

The const keyword is used when you don’t want the variable to change. In simple words, the const keyword is used to define constant values that cannot be further changed. It’s also block-scoped.

Example:

const name = "Intellipaat !"
name="Intellipaat";
console.log(name);

Output:

JavaScript const keyword

JavaScript Variable Scopes

Scopes in programming languages are defined as the place from which you can access a variable. In other words, variable scope in JavaScript decides where a variable is visible and where you can use it in your code. It is important for a developer and user to understand the scope of variables in JavaScript. Understanding JavaScript variable scope is crucial for writing clean and bug-free code. Here are the three types of variable scope:

1. Global Scope in JavaScript

Global scope in JavaScript means that you can access the variables that are declared outside the function or block ( {} ). The variable declared in the global scope can be easily accessed from each and every part of the code.

Note: The variables that are declared with var, let, and const outside the function are globally scoped.

Example: Creating a global variable and accessing it from different parts of the program.

let message = "Hello, From Intellipaat!";

function greet() {
console.log(message);
}

greet();
console.log(message);

Output:

Global Scope in JavaScript

2. Function Scope

As the name suggests, function scope means that if you declare a variable inside a function, it is only available within that function. Only var is function-scope, but let and const don’t follow this rule.

Example: Creating a function and understanding the function scope.

function showMsg() {
var msg = "Hello Learners";
console.log(msg);
}

showMsg();
console.log(msg);

Output:

Function Scope

Explanation: In this example, you are creating a JavaScript variable (msg) by using the var keyword, and this variable is function-scoped, which means it is only accessible within the function boundary. If you try to access the variable outside the function, then it will give a reference error.

3. Block Scope in JavaScript

A block in JavaScript means the content inside the curly braces ( {} ). Variables that are declared by using let or const inside a block can’t be used outside of it. This is called block scope in JavaScript.

Note: If you declared a variable by using the var keyword, then it ignores block scope and still gets hoisted to the function or global level.

Example: Block Scope in JavaScript

if (true) {
let count = 5;
console.log(count);
}
console.log(count);

Output:

block scope in javascript

Explanation: In this example, you are declaring a block scope variable count inside an if-block. This count variable is only accessed inside the if-block. If you try to access this variable outside the block, you get an error message.

JavaScript Variable Hoisting

Hoisting is defined as the behavior where the declarations of functions, variables, and classes are moved to the top of the scope during the compilation phase, before the code is executed. Below, we will explore JavaScript variable hoisting and how it behaves differently for var, let, and const.

Hoisting With var:

JavaScript moves the variable declaration to the top of its scope, before the code is executed. But it only moves the declaration, not the value that you assign. That’s why, by defaul,t it prints undefined.

Example:

console.log(name);
var name = "Intellipaat";

Output:

Hoisting with var

Hoisting With let and const:

In JavaScript, variables declared with let and const are hoisted, which means their declarations are moved to the top of the block during compilation. However, unlike var, these variables cannot be accessed before their declaration. This period between entering the block and the actual declaration is called the Temporal Dead Zone (TDZ). Accessing a variable in the TDZ results in a ReferenceError. This way TDZ helps you prevent accidental usage of uninitialized variables, which makes your code safer.

Example:

console.log(name);    // --> Refernce Error
let name = "Ananya";

console.log(city);
const city = "Bengaluru";

Output:

hoisting with let and const

Real-World Use Cases of JavaScript Variables

Now, that we have the complete understanding of JavaScript variables, let us now see a few real-world examples of how they are used in real-world scenarios.

1. Storing user input

The values that are entered by users in a forms or via prompt can be stored in a JavaScript variable. This allows programs to respond dynamically based on user input. It is the most easy and significant real-world application of variables in JavaScript. For a very simple example, in a web application, storing the user’s name lets you display personalized greetings, enhancing user experience.

Code:

let userName = prompt("Enter your name:");
console.log("Hello, " + userName);

Output:

Storing user input example

2. Counters in Loops

Another very common use of variables is using them as a counter in loops to track progress such as counting iterations, items in a list, or steps in a process.

Code:

let counter = 0;
for(let i = 0; i < 5; i++){
counter++;
console.log(counter);
}

Output:

Counter variable output

3. Storing API Responses

Variables can also store data fetched from APIs, allowing your program to use it later for display or calculations. Let say you develop a weather website, you can store an API response containing temperature data can be stored in a variable and displayed to users in real-time.

Code:

const apiData = fetch('https://api.example.com/data');

Output:

API response output

Best Practices for JavaScript Variables

You have multiple ways to declare variables in JavaScript, but choosing the right way to declare them is important to write clean code. Here are some best practices that you need to follow while declaring variables in the code:

  • Use the const keyword if you don’t want to change the value again and again in the code. For example, if in a math function you want to set a pi value that does not change, you can declare it using const pi = 3.14159;
  • Use the let keyword if you’re declaring variables that require change, like counter and user input.
  • It is recommended to avoid using the var keyword for declaring variables because it doesn’t follow block scope in JavaScript. var can cause unexpected behavior due to hoisting and function scope. Use let or const instead for safer, more predictable code.
  • Give proper and meaningful names to the variables. Avoid using short variable names like x, y, etc.
  • Declare variables close to where they are used, as this improves readability and reduces errors, especially in larger functions or blocks of code.
  • You should always initialize variables when possible. This avoids undefined errors and makes your code more predictable.
  • Always group related variables together to increase the readability of the code. It also helps you easily maintain the code. For example, if you want to save firstname, lastname and age you should declare them at one place following the best practices for javaScript variables.

Var vs Let vs Const in JavaScript

This section compares var vs let vs const in JavaScript, highlighting the differences in scope, redeclaration, and hoisting behavior.

Features var let const
Scope It has function scope. It has block scope. It also has a block scope.
Update and Redeclaration Variables declared by using var can be updated and redeclared within the scope. Can be updated but cannot be redeclared within the scope. Cannot be updated or redeclared within the scope.
Declaration without initialization It can be declared without being initialized. You can also declare these variables without being initialized. It cannot be declared without being initialized.
Access without initialization Accessible without initialization but returns undefined. Inaccessible and throws ReferenceError Inaccessible and throws ReferenceError
Hoisting Hoisted and initialized with a default value Hoisted but not initialized, which means it shows an error if you’re accessing a variable before declaration. Hoisted but not initialized.

Redeclaration Errors in Var vs Let vs Const in JavaScript

In JavaScript, understanding redeclaration rules is crucial to prevent bugs and unexpected behavior. Different variable types behave differently when you try to declare them multiple times in the same scope:

Code:

// Redeclaring var is allowed
var name = "Aarav";
var name = "Riya";

// Redeclaring let is not allowed
let age = 25;
let age = 30;

// Redeclaring const is not allowed
const city = "Mumbai";
const city = "Delhi";

Output:

image

Key Points:

  • Choosing the right declaration keyword is important for clean and maintainable code.
  • var can be redeclared within the same scope, which can lead to accidental overwrites.
  • let and const cannot be redeclared in the same scope, helping make your code safer and easier to debug.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

Understanding how JavaScript variables work is important while learning JavaScript. Whether you’re creating simple values like a name or number, or working with more complex data, using variables in the right way helps you write clean code. You can use const to declare variables if you don’t want to change the variable again, and let is used when you may want to change the value again. By understanding and following the best practices for using variables, you will be able to write clean and readable code in JavaScript.

To learn more about JavaScript functions, check out this Web Development course and also explore JavaScript Interview Questions prepared by industry experts.

JavaScript Variables – FAQs

Q1. What are variables in JavaScript?

Variables in JavaScript are defined as containers that are used to store values in the code.

Q2. How to create a variable?

In JavaScript, there are multiple ways to define variables, like you can use anyone from var, let, and const to create variables in JavaScript.

Q3. How to print a variable in JS?

You can use the console.log() method to print a variable in JavaScript.

Q4. What is ${} in JavaScript?

${} is used inside template strings to insert variables into text.

Q5. How to declare a string in JS?

String in JavaScript is defined as a sequence of characters. You can declare a string in JavaScript by using single quotes (‘ ‘), double quotes (” “), or backticks (` `).

About the Author

Software Developer | Technical Research Analyst Lead | Full Stack & Cloud Systems

Ayaan Alam is a skilled Software Developer and Technical Research Analyst Lead with 2 years of professional experience in Java, Python, and C++. With expertise in full-stack development, system design, and cloud computing, he consistently delivers high-quality, scalable solutions. Known for producing accurate and insightful technical content, Ayaan contributes valuable knowledge to the developer community.

Full Stack Developer Course Banner