לדלג לתוכן

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

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

פתרון תרגיל 1

קובץ index.html:

<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>My First JS Page</title>
    <script src="script.js" defer></script>
</head>
<body>
    <h1>JavaScript works!</h1>
</body>
</html>

קובץ script.js:

console.log("Amit Pinchasi");

פתרון תרגיל 2

קובץ hello.js:

let name = "Amit";
let age = 30;
let city = "Tel Aviv";
let languages = "Hebrew, English, Python, JavaScript";

console.log(name);
console.log(age);
console.log(city);
console.log(languages);
console.log(`My name is ${name}, I am ${age} years old, I live in ${city}, and I know ${languages}.`);

הרצה:

node hello.js

פתרון תרגיל 3

console.log("This is a regular message");
console.warn("This is a warning - something might be wrong");
console.error("This is an error - something went wrong!");
console.table([10, 20, 30, 40, 50]);

פתרון תרגיל 4

alert("Welcome to the site!");

let name = prompt("What is your name?");

let wantsMessage = confirm("Do you want to see a special message?");

if (wantsMessage) {
    alert("Hello " + name + "! You are awesome!");
} else {
    alert("Maybe next time!");
}

פתרון תרגיל 5

let name = "Alice";
let age = 25;
let isStudent = true;

console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
console.log(`Student: ${isStudent}`);

if (age >= 18) {
    console.log(`${name} is an adult`);
} else {
    console.log(`${name} is a minor`);
}

// print numbers 0 to 4
for (let i = 0; i < 5; i++) {
    console.log(i);
}

שימו לב להבדלים:
- is_student הפך ל-isStudent (camelCase במקום snake_case)
- True הפך ל-true (אות קטנה)
- f"..." הפך ל-`...` (backticks עם ${} במקום {})
- print() הפך ל-console.log()
- if age >= 18: הפך ל-if (age >= 18) {
- for i in range(5): הפך ל-for (let i = 0; i < 5; i++) {

פתרון תרגיל 6

קובץ without-defer.html:

<!DOCTYPE html>
<html>
<head>
    <script src="script.js"></script>
</head>
<body>
    <h1>Hello World</h1>
</body>
</html>

קובץ with-defer.html:

<!DOCTYPE html>
<html>
<head>
    <script src="script.js" defer></script>
</head>
<body>
    <h1>Hello World</h1>
</body>
</html>

קובץ script.js:

let title = document.querySelector("h1");
console.log("Title content:", title);

בקובץ הראשון הקונסול ידפיס Title content: null כי ה-h1 עדיין לא קיים בזמן שהסקריפט רץ.
בקובץ השני הקונסול ידפיס Title content: <h1>Hello World</h1> כי defer גורם לסקריפט לרוץ רק אחרי שכל ה-HTML נטען.

פתרון תרגיל 7

let firstInput = prompt("Enter the first number:");
let secondInput = prompt("Enter the second number:");

let num1 = Number(firstInput);
let num2 = Number(secondInput);

let result = `Results:
Addition: ${num1} + ${num2} = ${num1 + num2}
Subtraction: ${num1} - ${num2} = ${num1 - num2}
Multiplication: ${num1} * ${num2} = ${num1 * num2}
Division: ${num1} / ${num2} = ${num1 / num2}`;

alert(result);

בלי Number(), הקוד היה מתנהג לא נכון. למשל "5" + "3" יתן "53" (שרשור מחרוזות) במקום 8.

פתרון תרגיל 8

קובץ ראשון no-strict.js:

x = 10;
console.log(x); // prints 10 - works but bad practice

קובץ שני with-strict.js:

"use strict";
x = 10; // ReferenceError: x is not defined
console.log(x);

הקובץ השני יזרוק שגיאה: ReferenceError: x is not defined. כדי לתקן:

"use strict";
let x = 10; // now it works - variable is properly declared
console.log(x);

תשובות לשאלות

  1. עם defer ב-<head>, הדפדפן מתחיל להוריד את קובץ ה-JS כבר בזמן שהוא קורא את ה-head, במקביל לבניית ה-HTML. אם שמים את ה-script בסוף ה-body, ההורדה מתחילה רק אחרי שכל ה-HTML נבנה. defer נותן ביצועים טובים יותר.

  2. defer מריץ את הסקריפט רק אחרי שכל ה-HTML נטען, ושומר על סדר הסקריפטים. async מריץ את הסקריפט מיד כשהוא מוכן, בלי לחכות ל-HTML ובלי סדר מובטח. משתמשים ב-defer לסקריפטים שצריכים את ה-DOM, ו-async לסקריפטים עצמאיים כמו אנליטיקס.

  3. console.log מדפיס לקונסול של המפתח ולא מפריע למשתמש. alert מציג חלון קופץ שחוסם את הדף עד שהמשתמש לוחץ OK.

  4. prompt מחזירה null כשהמשתמש לוחץ Cancel.

  5. strict mode מונע שגיאות נפוצות כמו שימוש במשתנים בלי הגדרה, מוחק התנהגויות מוזרות של השפה, ועוזר למנוע באגים. בפרויקטים מודרניים זה בדרך כלל מופעל אוטומטית.

  6. חמישה הבדלי תחביר:

  7. בלוקים: { } ב-JS מול הזחה בפייתון
  8. משתנים: let/const ב-JS מול השמה ישירה בפייתון
  9. הערות: // ב-JS מול # בפייתון
  10. בוליאני: true/false ב-JS מול True/False בפייתון
  11. מוסכמת שמות: camelCase ב-JS מול snake_case בפייתון