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).
משתנה היא קופסה עם שם
- משתנה מאחסן ערך ומעניק לו שם, כך שתוכל להשתמש בו שוב בעתיד.
letיוצר קופסה שניתן לשנות אותה.constיוצר קופסה שחייבת להישאר כפי שהיא (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 בערך חדש
- הוסף שוב —
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.
שימו לב
- ל-
constאין אפשרות להקצאת מחדש:const x = 1; x = 2;גורם ל-שגיאה. - הרגל טוב: השתמש ב
constכברירת מחדל, והיעז בletרק כאשר הערך אכן משתנה.
Common mistakes
- Use
constfor values that never change,letfor those that do. - Declare a variable before you use it.
טעויות נפוצות
- השתמש ב
constלערכים שלא משתנים לעולם, ו-letלערכים שעושים זאת. - הכרז משתנה לפני השימוש בו.
Now you try
- Use
letorconstto store values. - Press Check answer to test it.
כעת תנסו בעצמכם
- השתמש ב-
letאוconstלאחסון ערכים. - לחץ על בדיקת תשובה כדי לבדוק אותה.
Store the text Cairo in a const called city, then log city. · שמור את הטקסט Cairo במשתנה const בשם city, ואז הקלט city.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
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. · לחץ על הרץ כדי לראות את התוצא כאן.
Make a let total = 10, add 5 to it, then log total (it is 15). · צור משתנה let total = 10, הוסף לו 5, ואז הקלט total (הוא 15).
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.