Variables
Variables are named containers for storing data values.
Syntax
let 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
constwhen the value will not be reassigned. - Use
letwhen the value may change. - Give variables meaningful names.
Example
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.
let username = "alice";
console.log(username); // aliceUpdate a running total
Uses a variable to accumulate a shopping cart total as items are added.
let cartTotal = 0;
cartTotal += 19.99;
cartTotal += 5.49;
console.log(cartTotal); // 25.48Multiple variables in context
Declares three variables of different types and interpolates them into a template string.
let firstName = "Maria";
let age = 28;
let isLoggedIn = true;
console.log(`${firstName}, age ${age}, logged in: ${isLoggedIn}`);
Discussion