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 variables in JavaScript, including different ways to declare 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 name, number, or a list 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 Ways to Declare Variables

Variables in JavaScript are the way to store data and use it in multiple places. You have 3 major ways to declare variables in JavaScript. Let’s discuss each of them in detail:

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, 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 and is now used most to declare variables in JavaScript. It is block-scoped, which means it is accessible inside the {}, where it’s defined. This will help the developers and the users to avoid unexpected bugs.

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

Variable Scopes in JavaScript

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. 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 the variable inside a function, it is only available within that function. Initially, only var is function-scope, but now let and const also 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.

Hoisting Behavior of var, let, and const in JavaScript

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.

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 default it prints undefined.

Example:

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

Output:

Hoisting with var

Hoisting With let and const:

JavaScript also hoists the declaration when you use let and const, but the variable stays in something called a temporal dead zone, which means you can’t use the variable before it’s declared. If you use it, it gives you a ReferenceError.

Example:

console.log(name);
let name = "intellipaat";

Output:

hoisting with let and const

Best Practices of Using 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.
  • 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.
  • Give proper and meaningful names to the variables. Avoid using short variable names like x, y, etc.

Difference Between let, var, and const

Since let, var, and const are all used to declare variables, they all behave differently. Here are some important differences between let, var, and const in JavaScript.

Featuresvarletconst
ScopeIt has function scope.It has block scope.It also has a block scope.
Update and RedeclarationVariables 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 initializationIt can be declared without being initialized.You can also declare these variables without being initialized.It cannot be declared without being initialized.
Access without initializationAccessible without initialization but returns undefined.Inaccessible and throws ReferenceErrorInaccessible and throws ReferenceError
HoistingHoisted and initialized with a default valueHoisted but not initialized, which means it shows an error if you’re accessing a variable before declaration.Hoisted but not initialized.

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 in writing 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

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner