JavaScript Variables

A variable is a named box that stores a value. You can use the name later to read or change the value.

let name = "Robin";
let age = 25;
console.log(name);
console.log(age);
Output of the above program is

Robin
25


let, const and var

KeywordCan change value?ScopeUse
letYesBlockFor values that change
constNo (cannot be reassigned)BlockFor values that stay the same. Use it by default
varYesFunctionOld way. Avoid in new code

let

let score = 10;
score = 15;          // allowed
console.log(score);
Output of the above program is

15

const

const PI = 3.14159;
PI = 3;   // TypeError: Assignment to constant variable.
Output of the above program is

TypeError: Assignment to constant variable.

const stops you from reassigning the variable. If the value is an object or an array, its inside items can still change.

const colors = ["red", "green"];
colors.push("blue");     // allowed
console.log(colors);
Output of the above program is

[ "red", "green", "blue" ]


Naming rules

  • Start with a letter, _ or $.
  • Use camelCase: userName, totalPrice.
  • Do not use keywords like let or class.
  • Choose clear names: age is better than a.

Declare many variables

let x = 5, y = 10, z = x + y;
console.log(z);
Output of the above program is

15

Note: A good habit: use const first, and change it to let only when you know the value must change.

Summary

  • Declare variables with let (changeable) or const (fixed).
  • Avoid var.
  • Learn where variables can be used in JavaScript Scope.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a JavaScript program to add two numbers
Write a JavaScript program to swap two variables
Interview Questions & Answers
What are the data types in JavaScript?
What is the difference between == and === in JavaScript?
What is NaN in JavaScript?
What is the difference between null and undefined?
What is scope in JavaScript?
What is the difference between var, let and const?
What is hoisting in JavaScript?