Arrow functions
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
English
Arrow functions
- A shorter way to write a function:
const square = (n) => n * n;. - With a single expression after
=>, the value is returned automatically — noreturn, no{ }.
ไทย
ฟังก์ชันลูกศร (Arrow functions)
- วิธีเขียนฟังก์ชันที่สั้นกว่า:
const square = (n) => n * n; - เมื่อมีนิพจน์เดียวหลัง
=>ค่าจะถูก ส่งกลับอัตโนมัติ — ไม่ต้องใช้returnและไม่ต้องใช้{ }
const square = (n) => n * n;
console.log(square(5)); // → 25
English
More than one parameter
- List the parameters in the brackets, separated by commas.
ไทย
พารามิเตอร์มากกว่าหนึ่งตัว
- รายการพารามิเตอร์ในวงเล็บ คั่นด้วยเครื่องหมายจุลภาค
const add = (a, b) => a + b;
console.log(add(3, 4)); // → 7
English
Watch out
- Need a longer body? Use
{ }and then you must writereturnyourself. - Arrow functions shine as short helpers — you will hand them to
.mapand.filterwhen we reach array methods.
ไทย
ระวัง
- ต้องการบอดี้ที่ยาวขึ้น? ใช้
{ }แล้วคุณต้องเขียนreturnเอง - ฟังก์ชันลูกศรเหมาะ用作短助手 — คุณจะใช้มันกับ
.mapและ.filterเมื่อเราถึงส่วนวิธีจัดการอาร์เรย์
English
Common mistakes
x => x + 1is a short function; with no braces it returns the expression.- Arrow functions are handy as arguments to array methods.
ไทย
ข้อผิดพลาดที่พบบ่อย
x => x + 1เป็นฟังก์ชันสั้นๆ โดยไม่ต้องมี curly braces จะคืนค่าเป็น expression- ฟังก์ชันลูกศรมีประโยชน์เมื่อใช้เป็นอาร์กิวเมนต์ให้กับวิธีของอาร์เรย์
English
Now you try
- Write each arrow function.
- Press Check answer to test it.
ไทย
ลองดูเลย
- เขียนฟังก์ชันลูกศรแต่ละตัว
- กด Check answer เพื่อทดสอบ
Write an arrow function triple that returns its argument times 3: const triple = (n) => n * 3;. · เขียน อาร์โรว์ฟังก์ชัน triple ที่คืนค่าพารามิเตอร์คูณด้วย 3: const triple = (n) => n * 3;
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Write an arrow function add with two parameters that returns their sum. · เขียน arrow function add ที่มี two parameters ที่ return ผลรวมของพวกมัน.
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Write an arrow function isEven that returns true when its argument is even (n % 2 === 0). · เขียนอาร์โรว์ฟังก์ชัน isEven ที่คืนค่า true เมื่อพารามิเตอร์เป็นเลขคู่ (n % 2 === 0)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่