Do you think IIT Guwahati certified course can help you in your career?
No
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.
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);
You can also try this code with Online Javascript Compiler
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);
You can also try this code with Online Javascript Compiler
With const, we declare a constant named PI, assigned the value 3.14. Constants cannot be reassigned or redeclared.
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);
You can also try this code with Online Javascript Compiler
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);
You can also try this code with Online Javascript Compiler
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);
You can also try this code with Online Javascript Compiler
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
Property
var
let
const
Scope
Function scope
Block scope
Block scope
Hoisting
Variables are hoisted to the top of their scope
Variables are not hoisted to the top of their scope
Variables are not hoisted to the top of their scope
Re-Declaration
Allowed in the same scope
Not allowed in the same block scope
Not allowed in the same block scope
Re-Assignment
Allowed
Allowed
Not Allowed
Initialization
Not required
Not required
Required at declaration
Use Case
When you need a variable to be accessible throughout a function
For variables that are used within a specific block (e.g., loops, conditions)
For values that should not change (constants)
Best Practice
Generally, it's recommended to avoid using var in favor of let and const for clearer scoping
Use let when you expect the variable to change
Use 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.