Lesson goal: Create named values and decide when to use let or const.
A variable gives a name to information your program uses.
Suppose a notebook costs ₹60. Instead of writing 60 throughout your program, you can give that value a useful name:
const notebookPrice = 60;
console.log(notebookPrice);
60
Create a name called
notebookPriceand assign it the value60.
| Part | Meaning |
|---|---|
const |
Declares a name that cannot be reassigned |
notebookPrice |
The name we chose |
= |
Assigns the value on the right |
60 |
The value |
; |
Ends this statement |
The single = means assignment. It does not compare two values.
Use let when the value needs to change
Imagine a customer first chooses two notebooks and then adds another.
let notebookQuantity = 2;
console.log(notebookQuantity);
notebookQuantity = 3;
console.log(notebookQuantity);
2
3
let again.Correct:
let score = 0;
score = 10;
let score = 0;
let score = 10;
Use const when reassignment is not needed
const courseName = "JavaScript Basics";
console.log(courseName);
const courseName = "JavaScript Basics";
courseName = "Python Basics";
const by default. Choose let when your program needs to assign a new value later.A const declaration must also have a starting value:
const shopName = "NHP Stationery";
const shopName;.Later, you will learn that const prevents reassignment but does not make the contents of an object or array unchangeable.
Choose clear names
| Clear name | Why it helps |
|---|---|
studentName |
Describes whose name it stores |
notebookPrice |
Identifies the item and the value |
totalMarks |
Explains what the number represents |
isPaid |
Suggests a true-or-false value |
Use camelCase for names containing several words: start with a lowercase letter and capitalise later words.
const studentName = "Simran";
const pricePerNotebook = 60;
studentName and StudentName as different names.You may see var in older code. We will use let and const in this course.
Your turn
studentName.completedLessons with the value 5.completedLessons to 6.One possible solution:
const studentName = "Aman";
let completedLessons = 5;
completedLessons = 6;
console.log(studentName);
console.log(completedLessons);
Answer: let, because the score will be reassigned.
Lesson recap
Variables give meaningful names to values. Use const when reassignment is unnecessary and let when the value needs to change.