본문으로 건너뛰기

Arrow Functions

Arrow Functions

Arrow functions are a way to express functions more succinctly in JavaScript.

They are written using the arrow (=>) symbol, allowing functions to be expressed more concisely than traditional function expressions.


Basic Structure of Arrow Functions

let functionName = (parameter1, parameter2) => {
// function body
};

Example:

const add = (a, b) => a + b;

console.log(add(1, 2)); // Outputs 3

Advantages of Arrow Functions

  • You can write code more simply than with traditional functions.

Example:

// Traditional function
let sayHello = function (name) {
return 'Hello, ' + name + '!';
};

// Arrow function
let sayHello = (name) => 'Hello, ' + name + '!';

Examples of Arrow Functions

When there are no parameters: You need to use parentheses.

let greet = () => 'Hello!';

When there is one parameter: You can omit the parentheses.

let double = (x) => x * 2;

When there are two or more parameters: You need to use parentheses.

let add = (a, b) => a + b;

When the function body spans multiple lines: You must use curly braces and specify return if you want to return a value.

let getMax = (a, b) => {
if (a > b) {
return a;
} else {
return b;
}
};