לדלג לתוכן

2.2 משתנים, טיפוסים ואופרטורים תרגול

תרגול - משתנים, טיפוסים ואופרטורים

תרגיל 1 - let, const, var

נתון הקוד הבא. מה ידפיס כל שורה? ענו לפני שתריצו ובדקו:

var a = 1;
let b = 2;
const c = 3;

a = 10;
b = 20;
// c = 30; // what happens if we uncomment this line?

console.log(a);
console.log(b);
console.log(c);

var a = 100; // is this allowed?
// let b = 200; // is this allowed?
// const c = 300; // is this allowed?

console.log(a);

כתבו את התשובות שלכם ואז הריצו כדי לבדוק.

תרגיל 2 - typeof

מה יהיה הפלט של כל שורה? ענו בלי להריץ, ואז בדקו:

console.log(typeof 42);
console.log(typeof "42");
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof null);
console.log(typeof NaN);
console.log(typeof [1, 2, 3]);
console.log(typeof {name: "Alice"});

תרגיל 3 - type coercion

מה יהיה הפלט? זה החלק המוזר של JS - נסו לנחש לפני שמריצים:

console.log("5" + 3);
console.log("5" - 3);
console.log("5" * "2");
console.log("hello" - 1);
console.log(true + true);
console.log(false + "1");
console.log("" + 0);
console.log(null + 1);
console.log(undefined + 1);
console.log("3" + 4 + 5);
console.log(3 + 4 + "5");

תרגיל 4 - == מול ===

מה יהיה הפלט? שימו לב ההבדל בין == ל-===:

console.log(5 == "5");
console.log(5 === "5");
console.log(0 == false);
console.log(0 === false);
console.log(null == undefined);
console.log(null === undefined);
console.log("" == false);
console.log("" === false);
console.log(NaN == NaN);
console.log(NaN === NaN);

תרגיל 5 - truthy ו-falsy

כתבו פונקציה checkTruthy שמקבלת ערך ומדפיסה אם הוא truthy או falsy:

function checkTruthy(value) {
    // your code here
    // should print: "VALUE is truthy" or "VALUE is falsy"
}

// test with these values:
checkTruthy(0);
checkTruthy("");
checkTruthy("0");
checkTruthy(null);
checkTruthy(undefined);
checkTruthy(false);
checkTruthy([]);
checkTruthy({});
checkTruthy(NaN);
checkTruthy("false");
checkTruthy(-1);
checkTruthy(1);

תרגיל 6 - ternary ו-nullish coalescing

שכתבו את הקוד הבא באמצעות:

א. אופרטור ternary (? :)

let age = 20;
let category;
if (age >= 18) {
    category = "adult";
} else {
    category = "minor";
}

ב. אופרטור ??

let userInput = null;
let name;
if (userInput !== null && userInput !== undefined) {
    name = userInput;
} else {
    name = "Anonymous";
}

ג. מה ההבדל בין שתי השורות האלה?

let value1 = 0 || "default";
let value2 = 0 ?? "default";

תרגיל 7 - תרגום מפייתון ל-JS

תרגמו את הקוד הבא מפייתון לג׳אווהסקריפט:

name = input("Enter your name: ")
age = int(input("Enter your age: "))

if age >= 18:
    status = "adult"
    can_drive = True
else:
    status = "minor"
    can_drive = False

print(f"{name} is {age} years old")
print(f"Status: {status}")
print(f"Can drive: {can_drive}")

if name == "" or name is None:
    print("No name provided")
else:
    print(f"Hello, {name}!")

תרגיל 8 - מחשבון טמפרטורה

כתבו תוכנית שמבקשת מהמשתמש טמפרטורה בצלזיוס (עם prompt) וממירה לפרנהייט.

הנוסחה: F = C * 9/5 + 32

  • זכרו ש-prompt מחזיר מחרוזת
  • השתמשו ב-Number() להמרה
  • הציגו את התוצאה ב-alert
  • השתמשו באופרטור ternary כדי להוסיף הודעה: אם מעל 30 צלזיוס - "Hot!", אחרת - "Nice weather"

תרגיל 9 - Optional Chaining

נתון האובייקט הבא:

const student = {
    name: "Alice",
    grades: {
        math: 95,
        english: 88
    },
    address: null
};

כתבו קוד שמדפיס בצורה בטוחה (בלי שגיאות) את:
1. שם הסטודנט
2. ציון במתמטיקה
3. ציון בהיסטוריה (לא קיים)
4. עיר מגורים (address הוא null)
5. שם ההורה (לא קיים בכלל באובייקט)

השתמשו ב-?. ו-?? כדי להדפיס "N/A" כשהערך לא קיים.

תרגיל 10 - חידות JS

הסבירו למה כל אחת מהתוצאות הבאות היא כזו:

console.log([] + []);        // ""
console.log([] + {});        // "[object Object]"
console.log(typeof NaN);     // "number"
console.log(0.1 + 0.2 === 0.3); // false
console.log("b" + "a" + +"a" + "a"); // "baNaNa"

רמז לאחרון: +"a" מנסה להמיר את "a" למספר.

שאלות

  1. מה ההבדל בין null ל-undefined? תנו דוגמה למתי כל אחד מופיע.
  2. למה כדאי להשתמש ב-=== תמיד ולא ב-==?
  3. מה ההבדל בין || ל-??? מתי עדיף להשתמש ב-???
  4. רשימה ריקה [] היא truthy ב-JS אבל falsy בפייתון. למה זה חשוב לדעת?
  5. מה ההבדל בין let ו-const? מתי נשתמש בכל אחד?