Beginner · First steps: values, variables and operators · topic 3 of 61 · 20 min
Variables: let, const and var
Explanation
Why variables?
Programs need to remember things: a price, a user name, a running total. A variable is a name that refers to a value, so you can use the value later and give it a meaning. total is much clearer than writing 1499 + 250 + 99 again and again.
Declaring and assigning
Declaring means creating the name. Assigning means giving it a value with the = sign. You can do both in one line. = in JavaScript does not mean "is equal to"; it means "put the value on the right into the name on the left".
let cartItems = 0; // declare and assign
cartItems = cartItems + 1; // assign a new value
cartItems += 2; // short form of cartItems = cartItems + 2
console.log(cartItems); // 3
const GST_RATE = 18; // never changes
console.log(GST_RATE); // 18const: the binding cannot change
const means the NAME is locked to one value; you cannot assign to it again. A binding is the link between a name and a value. If the value is an object or array, its contents can still change. const locks the link, not the object.
const prices = [100, 200];
prices.push(300); // allowed: the same array, changed inside
console.log(prices); // [100, 200, 300]
prices = [1, 2]; // TypeError: Assignment to constant variable.let: when the value must change
Use let for counters, running totals, and values you update in a loop. Both let and const are block-scoped: a block is the code between { and }, and a let or const made inside a block does not exist outside it.
if (true) {
let message = 'inside';
console.log(message); // inside
}
console.log(message); // ReferenceError: message is not definedWhy not var?
var was the only way before 2015. It has three problems. It ignores blocks (it is function-scoped), so a var inside an if leaks out. It can be declared twice without any error. And it is hoisted, which means you can use it before the line that declares it and silently get undefined. You will see old code with var, so you must be able to read it, but do not write it.
if (true) {
var leaked = 'oops';
}
console.log(leaked); // 'oops' (var ignores the block)
var count = 1;
var count = 2; // no error with var
console.log(count); // 2Naming rules and style
- Names may use letters, digits, _ and $, but cannot start with a digit (2total is invalid).
- Names are case-sensitive: total and Total are different.
- Reserved words like let, class or return cannot be names.
- Use camelCase for normal variables (orderTotal, isPaid) and UPPER_SNAKE_CASE for fixed settings (MAX_RETRIES).
- Booleans read well with is/has/can: isLoggedIn, hasCoupon.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Variables: let, const and var · 1/6
In this lesson you will store values in variables using let and const.
Prefer a video by a teacher? Find free videos on “javascript let const var difference explained” on YouTube ↗
In real life: An EMI calculator
A bank's loan page keeps the interest rate and loan amount in const variables because they do not change during one calculation. The remaining balance changes every month, so it is a let variable that is updated in a loop.
const principal = 100000; // loan amount in rupees
const monthlyPayment = 9000;
let balance = principal;
let months = 0;
while (balance > 0) {
balance -= monthlyPayment;
months += 1;
}
console.log('Paid off in', months, 'months');Practice (0/2 done)
Fix this code. It should end with total equal to 60, but it crashes because total is declared with const and then changed. Change the declaration so the code works.
Write a function addToCart(cart, item) that pushes item into the cart array and returns the new number of items. The cart is declared with const outside; you should change the array's contents, not reassign it.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Operators and type coercionFirst steps: values, variables and operators · same module
- Values, types and variablesFrontend Web Development · JavaScript basics
- Types and variablesC# and .NET · Getting started with C# and .NET
- Scope, hoisting and closuresFrontend Web Development · JavaScript in depth
- Variables: giving names to valuesPython Programming · First steps in Python
- References: another name for a variableC++ Programming (modern C++ and DSA) · References, pointers, arrays and strings
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
const list = [1]; list.push(2); What happens?
Answer: list becomes [1, 2]
const stops reassignment of the name, not changes inside the array.
Which keyword should you use by default for new variables?
Answer: const
Use const by default and switch to let only when you must reassign.
if (true) { let a = 1; } console.log(a); What happens?
Answer: ReferenceError
let is block-scoped, so a does not exist outside the braces.
Which is a valid variable name?
Answer: orderTotal
Names cannot start with a digit, cannot contain -, and cannot be reserved words like class.
What value does a declared variable have before you give it one?Related
const int Max = 10; Max = 20; What happens?Related
Answer: Compile error: a const cannot be changed
A const value is fixed at compile time and cannot be assigned again.
From Types and variables
A loop with var i pushes () => i three times. Calling them gives [3, 3, 3]. Why?Related
Answer: var makes one i for the whole function, shared by all the functions
All three functions see the same i, which is 3 when the loop ends. let gives each round its own i.
Which is a valid variable name?Related
Answer: total_marks
Names cannot start with a digit, cannot contain spaces, and cannot be keywords like class.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “First steps: values, variables and operators” before its exam: Operators and type coercion, Numbers and Math.
- Module 1 exam: First steps · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
- Then the next module, Strings, decisions and loops. 61 topics left in the course before the final exam.