Variable

Term side of the Card.
Topic: Basics
Unit title: Variable
Categories: Concept
Explanation side of the Card

Explanation: The named storage location used to hold data that can vary throughout the execution of a program. It can store values such as numbers, text or other data types.

Example

Wrongjs
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));
}
Rightjs
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));
}

var is function-scoped, so it logs 3, 3, 3; let creates a new binding per pass and logs 0, 1, 2.

Common mistakes

  • A var inside a loop is shared by every callback, so all of them see the last value.

Key points

  • New JavaScript code declares variables with const or let, not var.
  • Variables have descriptive names, not x, data2 or temp.
  • Each variable is declared in the smallest scope that needs it.

Interview questions

What is the difference between a variable and a constant?

A variable can be reassigned while the program runs. A constant keeps the value it got first.

Should I use let or const in JavaScript?

Use const by default and let only when the value must be reassigned.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy