Variables in JavaScript
let, const and why var is retired — plus the difference between a constant name and a constant value.
4 minute read · Free · Taught properly in our Front End Development Training in Amritsar
JavaScript has three ways to make a variable. You need two of them.
const fee = 4500; // will not be reassigned
let count = 0; // will change
var old = "avoid"; // the old way
Use const by default
Start with const. Switch to let only when you actually reassign the name. Code where most names are const is easier to read, because a let becomes a signal that something changes.
const name = "Simran";
name = "Ravi"; // TypeError: Assignment to constant variable
const does not mean frozen
This is the part that confuses everybody. const stops the name being pointed somewhere else. It does not stop the value being changed:
const student = { name: "Simran" };
student.name = "Ravi"; // fine — same object, different contents
student.city = "Amritsar"; // also fine
student = {}; // TypeError — now you are moving the name
Same with arrays: const marks = [1,2]; marks.push(3); works. If you want the contents locked too, Object.freeze() does that, and you will rarely need it.
Why not var
var ignores blocks:
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1 — escaped the block
console.log(b); // ReferenceError — stayed inside
var is also hoisted: you can use it before the line that declares it and get undefined instead of an error, which hides typos. You will still see var in older tutorials and in code you inherit. Read it, do not write it.
Types are decided by the value
let x = 5; // number
x = "five"; // string — allowed
typeof x; // 'string'
The types you will meet constantly: number, string, boolean, undefined, null, object (which includes arrays), and function.
One oddity to know before it bites: typeof null returns 'object'. It is a bug from 1995 that can never be fixed without breaking the web.
Stuck on this in your own code?
That is what a class is for. Sit one for free at WebPrims on Majitha Road, Amritsar — write some JavaScript, ask the mentor why yours is not working, and decide afterwards.