JavaScript Variables
Store values and understand common JavaScript data types.
Variables store information that a JavaScript program can use later.
What Is a Variable?
A variable is a named container that stores a value.
- Variables can store names, ages, prices, and other information.
- JavaScript variables are declared with let, const, or var.
JavaScript
let name = "John";
let age = 25;- name stores the value John.
- age stores the value 25.
Declaring Variables
Using let
Use let when the value may change later.
JavaScript
let score = 100;
score = 150;
console.log(score);Output:
JavaScript
150Using const
Use const when the variable should not be reassigned.
JavaScript
const country = "India";
console.log(country);Using var
var is the older way to declare variables; prefer let or const.
JavaScript
var city = "Delhi";Rules for Writing Variables
- Start the name with a letter, underscore (_), or dollar sign ($).
- Numbers are allowed after the first character.
- Spaces and hyphens are not allowed in variable names.
- Do not use keywords such as const, class, or return.
- Names are case-sensitive: userName and username are different.
- Use clear camelCase names, such as totalPrice.
JavaScript
// Valid variable names
let firstName = "Asha";
let _score = 95;
let $price = 499;
let item2 = "Laptop";
// Invalid variable names
// let 2items = 2; // Cannot begin with a number
// let first-name = "Asha"; // Hyphens are not allowed
// let user name = "Asha"; // Spaces are not allowed
// let class = "JavaScript"; // Reserved keywordKey Takeaways
- Use const by default and let when the value must change.
- Choose short, clear, and valid variable names.
- Use camelCase for names made from multiple words.
