Variables — let and const · ตัวแปร — let และ const
A variable is a named box
- A variable stores a value and gives it a name, so you can use it again later.
letmakes a box you can change.constmakes a box that must stay the same (a constant).
ตัวแปรคือกล่องที่มีชื่อ
- ตัวแปร (variable) เก็บค่าและ给它起一个 name เพื่อให้คุณสามารถใช้งานมันอีกครั้งในอนาคต
letสร้างกล่องที่คุณสามารถ เปลี่ยน ได้constสร้างกล่องที่ต้อง คงเดิม (a constant)
let age = 15; // a value that may change
const name = "Ada"; // a value that won't
console.log(name, age); // → Ada 15
Change a let with a new value
- Assign again —
count = count + 1— to update alet. count++is a handy shortcut for "add 1 tocount".
เปลี่ยน let ด้วยค่าใหม่
- Assign ใหม่ —
count = count + 1— เพื่ออัปเดตlet count++เป็นทางลัดที่ดีสำหรับ "เพิ่ม 1 เข้าไปในcount"
let count = 0;
count = count + 1;
count++;
console.log(count); // → 2
Watch the boxes change · ดูกล่องเปลี่ยนไป
A variable is a named box. let can be changed; const stays fixed. · ตัวแปรคือ กล่องที่มีชื่อ. let สามารถเปลี่ยนแปลงได้; const คงที่
Watch out
- A
constcannot be reassigned:const x = 1; x = 2;throws an error. - Good habit: use
constby default, and reach forletonly when the value truly changes.
ระวัง
- A
constไม่สามารถ Reassign ได้:const x = 1; x = 2;จะเกิด error - นิสัยดี: ใช้
constเป็นค่าเริ่มต้น และใช้letเฉพาะเมื่อค่ามีการเปลี่ยนแปลงจริงๆ
Common mistakes
- Use
constfor values that never change,letfor those that do. - Declare a variable before you use it.
ข้อผิดพลาดที่พบบ่อย
- ใช้
constสำหรับค่าที่ไม่เปลี่ยนแปลง ใช้letสำหรับค่าที่เปลี่ยนแปลง - Declare ตัวแปรก่อนนำไปใช้
Now you try
- Use
letorconstto store values. - Press Check answer to test it.
ลองดูเลย
- ใช้
letหรือconstเพื่อเก็บค่า - กด Check answer เพื่อทดสอบ
Store the text Cairo in a const called city, then log city. · เก็บข้อความ Cairo ในตัวแปร const ชื่อ city, แล้วบันทึก日志 city.
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
let w = 4 and let h = 3 are the width and height. Work out the area (w * h) and log it (it is 12). · let w = 4 และ let h = 3 คือ ความกว้างและความสูง คำนวณพื้นที่ (w * h) แล้วแสดงผลลัพธ์ (ค่าที่ได้คือ 12)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Make a let total = 10, add 5 to it, then log total (it is 15). · สร้าง let total = 10, เพิ่ม 5 เข้าไป, แล้ว log total (คือ 15).
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่