Variables
Learn how to store, change, and use values in JavaScript programs with variables.
What is a Variable?
A variable is a named place used to store a value. That value can be used later in your program.
For example, we can store a student's name, course name, or marks inside variables.
Comparison of JavaScript variable declaration keywords.
Why Do We Need Variables?
Simple Idea
Instead of writing the same value again and again, we can store it in a variable and use the variable whenever we need the value.
JavaScript Variable Keywords
let
Use let when a variable may need to be assigned a new value.
const
Use const when the variable should not be reassigned.
var
var is the older variable declaration style and is generally avoided in modern JavaScript code.
How a Variable Works
Example 1: Creating Variables
We can create variables using let and const.
let studentName = "Samadhan";
let course = "JavaScript";
const institute = "CIIT Training Institute";
console.log("Welcome to " + institute + " ❤️🧑🎓.....!");
console.log("Student:", studentName);
console.log("Course:", course);
Output
Student: Samadhan
Course: JavaScript
Changing a Variable Value
A variable created using let can be assigned a new value later.
Example 2: Reassigning a Variable
let course = "HTML";
console.log("Current Course:", course);
course = "JavaScript";
console.log("Updated Course:", course);
console.log("Learning at CIIT Training Institute ❤️.....!");
Output
Updated Course: JavaScript
Learning at CIIT Training Institute ❤️.....!
Using const
A const variable must be initialized when it is created and cannot be reassigned later.
Example 3: const Variable
const institute = "CIIT Training Institute";
const course = "JavaScript";
console.log("Institute:", institute);
console.log("Course:", course);
console.log("Welcome to CIIT ❤️🧑🎓.....!");
Output
Course: JavaScript
Welcome to CIIT ❤️🧑🎓.....!
Variable Naming Rules
Good Variable Names
• Use meaningful names.
• Use letters, numbers, underscore, or dollar sign.
• Do not start a variable name with a number.
• JavaScript variable names are case-sensitive.
• Prefer clear names such as studentName instead of x.
Real-World Example
A training website can store information such as institute name, course name, and student count using variables.
const institute = "CIIT Training Institute";
const course = "JavaScript";
let students = 150;
console.log("Institute:", institute);
console.log("Course:", course);
console.log("Students:", students);
console.log("Keep Learning ❤️🧑🎓.....!");
Output
Course: JavaScript
Students: 150
Keep Learning ❤️🧑🎓.....!
Summary
Variables are used to store values in JavaScript. Modern JavaScript mainly uses let and const. Use let when a value may change and const when reassignment is not required. Meaningful variable names make programs easier to understand.