Functions · פונקציות
Functions
- A function is a named block of code you can run again and again.
function name(params) { ... return value; }. Theparamsare the inputs.returnhands a value back to whoever called the function.
פונקציות
- פונקציה היא חבילת קוד בעלת שם שתוכל להפעיל שוב ושוב.
function name(params) { ... return value; }. ה-paramsהם הקלט.returnמחזירה ערך למי שקרא לפונקציה.
function square(n) {
return n * n;
}
console.log(square(6)); // → 36
Functions that just do something
- A function can do something (like print) instead of returning a value.
- Call it by writing its name and brackets:
greet("Ada").
פונקציות שעושות דבר מה
- פונקציה יכולה לעשות משהו (כמו הדפסה) במקום להחזיר ערך.
- קראו לה על ידי כתיבת השם שלה והסוגריים:
greet("Ada").
function greet(name) {
console.log("Hi, " + name); // → Hi, Ada
}
greet("Ada");
Call and return · קריאה והשבה
Each call runs the body with its own input, then return hands a value back. · כל קריאה מבצעת את הגוף עם הקלט הייחודי שלה, ולאחר מכן return מחזיר ערך חזרה.
Watch out
- The names in the brackets (
n,name) are parameters — they only exist inside the function. - A function with no
returngives backundefined. Addreturnwhen you want an answer out.
שימו לב
- השמות בסוגריים (
n,name) הם פרמטרים — הם קיימים רק בתוך הפונקציה. - פונקציה ללא
returnמחזירהundefined. הוסיפוreturnכאשר אתם רוצים תשובה בחוץ.
Common mistakes
returngives back a value; without it a function returnsundefined.- Call the function with
().
טעויות נפוצות
returnמחזירה ערך; בליה, פונקציה מחזירהundefined.- קראו לפונקציה עם
().
Now you try
- Write each function — it is called for you in the check.
- Press Check answer to test it.
כעת תנסו בעצמכם
- כתבו כל פונקציה — היא תיקרא עבורכם בבדיקה.
- לחץ על בדיקת תשובה כדי לבדוק אותה.
Write a function double(n) that returns n times 2. · כתוב פונקציה double(n) שתשב ערכים n כפול 2.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Write a function add(a, b) that returns a + b. · כתוב פונקציה add(a, b) שתשיב a + b.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Write a function greet(name) that logs Hi, then the name, then call greet("Ada"). Output should be Hi, Ada. · כתוב פונקציה greet(name) שתדפיס Hi, , לאחר מכן את השם, ותיקרא את greet("Ada"). התוצאה תהיה Hi, Ada.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.