Variables

Variables are named containers for storing data values.

Syntaxlet name = value; const name = value;

Variables are containers for storing data. In modern JavaScript you declare them with let, const, or (rarely) var.

Declaring and using

  • Use const when the value will not be reassigned.
  • Use let when the value may change.
  • Give variables meaningful names.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Store a user's username after login so it can be displayed across multiple page sections.
  • Hold a running subtotal in a variable that updates as items are added to a shopping cart.
  • Keep the current page number in a variable to control which results are shown in a paginated list.

More examples

Declare and assign a variable

Declares a variable with let and assigns a string value to it, then logs it.

Example · js
let username = "alice";
console.log(username); // alice

Update a running total

Uses a variable to accumulate a shopping cart total as items are added.

Example · js
let cartTotal = 0;
cartTotal += 19.99;
cartTotal += 5.49;
console.log(cartTotal); // 25.48

Multiple variables in context

Declares three variables of different types and interpolates them into a template string.

Example · js
let firstName = "Maria";
let age = 28;
let isLoggedIn = true;
console.log(`${firstName}, age ${age}, logged in: ${isLoggedIn}`);

Discussion

  • Be the first to comment on this lesson.
Variables — JavaScript | SoundsCode