Arrow Functions
๐จโ๐ผ Modern JavaScript has a shorter syntax for writing functions called arrow
functions. They're especially useful for short, simple functions.
The syntax:
// Traditional function
function add(a, b) {
return a + b
}
// Arrow function
const add = (a, b) => {
return a + b
}
// Even shorter for single expressions
const add = (a, b) => a + b
- Create
doubleas an arrow function that takes a number and returns it doubled - Create
greetas an arrow function that takes a name and returns "Hello, [name]!" - Create
isPositiveas an arrow function that takes a number and returnstrueif it's greater than 0 - Call each function and log the results
๐ฐ For single-expression functions, you can omit the
{} and return:const square = (n) => n * n