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").
ฟังก์ชันที่ทำแค่บางอย่าง
- ฟังก์ชันสามารถ ทำอะไรsomething (เช่น Print) แทนที่จะส่งค่ากลับมา
- เรียกมันโดยการพิมพ์ชื่อและวงเล็บ:
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. · แต่ละ call ทำงานด้วย input ของมันเอง, แล้ว 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) คือ Parameters - พวกมันมีอยู่เฉพาะภายในฟังก์ชัน - ฟังก์ชันที่ไม่มี
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.
ลองดูเลย
- เขียนแต่ละฟังก์ชัน — ระบบจะเรียกใช้ให้คุณในขั้นตอนตรวจสอบ
- กด Check answer เพื่อทดสอบ
Write a function double(n) that returns n times 2. · เขียนฟังก์ชัน double(n) ที่ คืนค่า ผลคูณของ n กับ 2
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Write a function add(a, b) that returns a + b. · เขียนฟังก์ชัน add(a, b) ที่ return a + b.
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Write a function greet(name) that logs Hi, then the name, then call greet("Ada"). Output should be Hi, Ada. · เขียนฟังก์ชัน greet(name) ที่ log Hi, ตามด้วยชื่อ, แล้วเรียก greet("Ada"). Output ควรเป็น Hi, Ada.
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่