Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Examples of JavaScript Variables
2.1.
Declaring a Variable with var
2.2.
JavaScript
2.3.
Using let to Declare a Variable
2.4.
JavaScript
2.5.
Creating a Constant with const:
2.6.
JavaScript
3.
JavaScript Assignment Operator
3.1.
Assigning a Value to a Variable
3.2.
Updating a Variable's Value
3.3.
Using Variables to Assign Values
4.
JavaScript Identifiers
4.1.
Naming Variables
4.2.
Case Sensitivity
4.3.
Choosing Meaningful Names
4.4.
Using var
4.5.
JavaScript
4.6.
Choosing let
4.7.
JavaScript
4.8.
Using const
4.9.
JavaScript
5.
Comparison of properties of let, var, and const keywords in JavaScript
6.
Frequently Asked Questions
6.1.
Can I change the value of a variable declared with const?
6.2.
Why do I get an error when using a variable before declaring it with let or const?
6.3.
Is it necessary to always use let or const instead of var?
7.
Conclusion
Last Updated: Apr 7, 2024
Medium

Javascript Variable

Author Ravi Khorwal
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Javascript is a widely used script to create the dynamic webpages and JavaScript variables are the basics of any web application. They let us store, update, and manipulate data right within our scripts, making our web pages dynamic and interactive. 

Javascript Variable

In this article, we'll learn the essentials of JavaScript variables, from what they are to how they're used, including the different ways to declare them with var, let, and const. 

Examples of JavaScript Variables

In JavaScript, variables are like containers for storing data values. You can think of them as labels that point to the data rather than the data itself. 

Let's look at some examples to see how variables work in JavaScript.

Declaring a Variable with var

  • JavaScript

JavaScript

var message = 'Hello, world!';

console.log(message);

Outputs

Hello, world!


In this example, var is used to declare a variable named message. The variable is assigned the value 'Hello, world!'. When we log message to the console, it displays the assigned value.

Using let to Declare a Variable

  • JavaScript

JavaScript

let age = 25;

console.log(age);

Outputs

25


Here, let is used to declare a variable named age with the value 25. The let keyword allows this variable to be reassigned later.

Creating a Constant with const:

  • JavaScript

JavaScript

const PI = 3.14;

console.log(PI);

Outputs

3.14


With const, we declare a constant named PI, assigned the value 3.14. Constants cannot be reassigned or redeclared.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

JavaScript Assignment Operator

The assignment operator in JavaScript is the equal sign (=). It's used to set the value of a variable. 

For example : .

Assigning a Value to a Variable

let name = 'Alex';


In this line of code, the assignment operator (=) assigns the value 'Alex' to the variable name. Now, the variable name holds the value 'Alex'.

Updating a Variable's Value

let score = 10;
score = 15; // The value of score is now updated to 15


Initially, the variable score is assigned the value 10. Later, using the assignment operator again, the value of score is updated to 15.

Using Variables to Assign Values

let originalPrice = 50;
let discountPrice = originalPrice - 10; // discountPrice is now 40


Here, the value of originalPrice is used in an expression to determine the discountPrice. The result, 40, is then assigned to discountPrice.

The assignment operator is a fundamental part of JavaScript, allowing us to initialize variables and update their values as our program runs.

JavaScript Identifiers

Identifiers in JavaScript are names given to variables, functions, and other entities to identify them uniquely. Just like any other programming language we use, they follow specific rules and strictly needs to declared as per those instructions.

For example -: 

Naming Variables

Identifiers can include letters, digits (0-9), underscores (_), and dollar signs ($). However, they must start with a letter, an underscore, or a dollar sign. Numbers can't be the first character.

let userName = 'Charlie';  // Valid identifier
let _userID = 102;         // Valid identifier
let $amount = 150.50;      // Valid identifier
// let 2ndChoice = 'B';    // Invalid identifier, starts with a number

Case Sensitivity

JavaScript is case-sensitive. This means userName and Username would be considered different identifiers.

let age = 25;
let Age = 30;  // Different variable than 'age'

Choosing Meaningful Names

It's important to use descriptive and meaningful names for your identifiers. This makes your code easier to read and understand.

let birthYear = 1995;  // Clear and descriptive
let x = 1995;          // Unclear and non-descriptive


When to Use var, let, or const

In JavaScript, you have three keywords for declaring variables: var, let, and const.

 Each serves a different purpose and comes with its own set of rules. Understanding when to use each is key to writing effective and error-free code.

Using var

The var keyword is the oldest method of declaring variables in JavaScript. Variables declared with var are function-scoped, meaning they are recognized throughout the function in which they are declared. However, var has some limitations, such as potential issues with variable hoisting and scope confusion.

  • JavaScript

JavaScript

var greeting = 'Hello';

if (greeting) {

   var greeting = 'Howdy';  // Re-declares and overwrites 'greeting'

}

console.log(greeting);

Outputs

'Howdy'

Choosing let

Introduced in ES6 (ECMAScript 2015), let provides block-scoped variables. Unlike var, a let variable is limited to the block, statement, or expression where it is declared. This makes let a better choice for controlling variable scope more precisely.

  • JavaScript

JavaScript

let message = 'Hello';

if (message) {

   let message = 'Howdy';  // This 'message' is different from the outer 'message'

   console.log(message); // Outputs: 'Howdy'

}
console.log(message);

 Outputs

'Howdy'
 'Hello'

Using const

Also introduced in ES6, const is used to declare constants. A const variable must be assigned a value when declared, and that value cannot be changed later. const is block-scoped, similar to let.

  • JavaScript

JavaScript

const PI = 3.14;
// PI = 3.14159;  // This would cause an error because 'PI' is a constant.
console.log(PI); 

Outputs

3.14


Note -: We can use var for function-scoped variables (though its use is becoming less common), let for block-scoped variables, and const for constants that won’t change their value throughout your code.

Comparison of properties of let, var, and const keywords in JavaScript

Propertyvarletconst
ScopeFunction scopeBlock scopeBlock scope
HoistingVariables are hoisted to the top of their scopeVariables are not hoisted to the top of their scopeVariables are not hoisted to the top of their scope
Re-DeclarationAllowed in the same scopeNot allowed in the same block scopeNot allowed in the same block scope
Re-AssignmentAllowedAllowedNot Allowed
InitializationNot requiredNot requiredRequired at declaration
Use CaseWhen you need a variable to be accessible throughout a functionFor variables that are used within a specific block (e.g., loops, conditions)For values that should not change (constants)
Best PracticeGenerally, it's recommended to avoid using var in favor of let and const for clearer scopingUse let when you expect the variable to changeUse const for constants and when you want to protect the variable from being reassigned

Frequently Asked Questions

Can I change the value of a variable declared with const?

No, you cannot change the value of a variable declared with const once it has been assigned. Attempting to do so will result in a runtime error. const is used for constants whose value should remain the same throughout the execution of the program.

Why do I get an error when using a variable before declaring it with let or const?

This happens because of the Temporal Dead Zone (TDZ), a behavior in JavaScript where variables declared with let and const are not accessible before their declaration in the code. This helps catch errors by ensuring variables are declared before use.

Is it necessary to always use let or const instead of var?

While var is still a part of JavaScript, it's generally recommended to use let and const for variable declarations because they provide block-level scoping, which makes your code more readable and reduces the chance of bugs related to variable scoping.

Conclusion

In this article, we learned the basics of JavaScript variables, including how to declare them using var, let, and const. We discussed about the assignment operator, cleared the concept of identifiers, and learned when to use each type of variable declaration. We also compared var, let, and const to help you understand their differences and where to use them efficiently.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Concatenate Javascript
Next article
Sets in Javascript
Live masterclass