Variables with let and const
A variable is a named box where you store a value to use later. Without variables you would have to repeat the same numbers and texts all over the program; with them, you change the value in a single place. In modern JavaScript they are declared with two keywords: let and const. There is a third one, var, that you will see in old code, but today it is avoided because its rules are confusing.
let: a value that can change
Use let when the value is going to change during the program, such as a counter or a score. The declaration creates the variable and the equals sign gives it a value. Later you can reassign it without repeating the word let. Trying to declare the same name twice with let in the same place produces an error, which protects you from overwriting data by accident.
let score = 0;
console.log(score); // 0
score = score + 10;
console.log(score); // 10
score += 5; // shortcut for score = score + 5
console.log(score); // 15const: a value that is not reassigned
const declares a constant: once the value is assigned, you cannot assign it again. It must receive its value at the moment of declaration. The community recommendation is to use const by default and switch to let only when you really need to reassign. That way, when reading the code, you know a const always points to the same thing. Careful: later we will see that an object or array declared with const can be changed inside; what you cannot do is point the variable to something else.
const taxRate = 0.21;
const price = 100;
const total = price + price * taxRate;
console.log(total); // 121
// taxRate = 0.1; // TypeError: Assignment to constant variable.Rules for naming variables
A name can contain letters, digits, underscores and the dollar sign, but it cannot start with a digit, cannot contain spaces and cannot be a reserved word such as let or class. It is case sensitive: age and Age are different variables. The convention is camelCase, meaning the first word in lowercase and the next ones capitalized, like userName or totalPrice. Choose names that explain the content: finalPrice is better than x.
Frequent mistakes
- Using a variable before declaring it: gives a ReferenceError (with let and const there is a dead zone until the declaration line).
- Reassigning a const: gives a TypeError. Fix: switch to let if the value must change.
- Declaring the same name twice with let: gives a SyntaxError. Fix: just assign without repeating let.
- Mistyping a capital letter: userName and username are different names.
✎ ملاحظاتي
محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف