Lesson 6 +10 XP

JavaScript Variables

JavaScript Variables

A variable is a named container for storing data values.

Declaring variables

In modern JavaScript, you declare variables with let or const:

let name = "Ada";
let age = 36;
const pi = 3.14;

The three ways

KeywordCan change laterModern choice
letyespreferred for changing values
constnopreferred when the value never changes
varyesold way, avoid in new code

Assigning values

Use the assignment operator = to put a value into a variable:

let price = 10;
price = 15; // change the value

Using variables

Once declared, use the variable name wherever you need the value:

let firstName = "Ada";
let lastName = "Lovelace";
let fullName = firstName + " " + lastName;

Undeclared variables

Using a variable before declaring it causes an error. Always declare variables before you use them.

TL;DR

  • A variable stores a value under a name.
  • Use let for values that change and const for fixed values.
  • var is the old way; avoid it.
  • = assigns a value to a variable.