[JavaScript] Complete Guide to Modern Function Definition with Arrow Functions (=>)

目次

Overview

Introduced in ES6 (ECMAScript 2015), “Arrow Functions” provide a new way to define functions using the arrow symbol => instead of the function keyword. This syntax reduces the amount of code you write and improves readability. It also offers powerful shorthand options, such as omitting parentheses for single arguments and omitting the return keyword for single-line expressions. This article covers basic syntax and common shorthand patterns used in professional development.

Specifications (Input/Output)

  • Input: Arguments such as numbers.
  • Output: Calculation results (returned values) printed to the console.

Basic Usage

Arrow functions are typically used by assigning them to variables (constants). The basic syntax is: const functionName = (arguments) => { process };.


Full Code (HTML / JavaScript)

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arrow Function Demo</title>
    <script src="arrow-demo.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Please check the Console</h1>
        <p>The results of the arrow function execution are displayed in the console.</p>
    </div>
</body>
</html>

JavaScript (arrow-demo.js)

/**
 * 1. Basic Arrow Function (Multiple Arguments)
 * Parentheses () are required for two or more arguments.
 * Braces {} and the return keyword are required for multi-line processes.
 */
const calcSum = (a, b, c) => {
    const result = a + b + c;
    return result;
};

console.log(`Total: ${calcSum(1, 2, 3)}`); // 6


/**
 * 2. Shorthand for Single Arguments
 * If there is exactly one argument, you can omit the parentheses ().
 * Note: Many formatting tools like Prettier may add them back for consistency.
 */
// Basic form
const myFunction1 = (a) => {
    return a + 2;
};

// Omitting parentheses
const myFunction2 = a => {
    return a + 2;
};

console.log(`myFunction1: ${myFunction1(10)}`); // 12
console.log(`myFunction2: ${myFunction2(10)}`); // 12


/**
 * 3. Single-line Shorthand (Implicit Return)
 * If the process is a single expression that returns a value,
 * you can omit both the {} braces and the return keyword.
 * This makes the code very concise.
 */
const myFunction3 = (a) => a + 2;

console.log(`myFunction3 (Shorthand): ${myFunction3(10)}`); // 12


/**
 * Advanced: No Arguments
 * If there are no arguments, empty parentheses () must be used.
 */
const sayHello = () => console.log("Hello Arrow Function!");
sayHello();

Customization Points

  • Shorthand Standards: In team development, rules are often set, such as “always include parentheses for arguments” or “only allow implicit returns for simple calculations.” It is recommended to use formatting tools like Prettier to maintain consistency.
  • Immediately Invoked Function Expressions (IIFE): You can define and execute an arrow function immediately using the pattern (() => { process })();.

Important Points

  • Returning Objects: If you try to return an object using an implicit return, the {} of the object will be mistaken for a function block, causing an error. To return an object shorthand, wrap the object in parentheses: const getObj = () => ({ id: 1 });.
  • Behavior of ‘this’: Unlike traditional functions, arrow functions do not have their own this context. They inherit this from the surrounding scope. Be careful when using them for object methods or event handlers where you expect this to refer to the object or the element.

Advanced Usage

Combining with Array Methods

The shorthand version of arrow functions is most effective when used with array methods like map or filter.

const numbers = [1, 2, 3, 4, 5];

// Traditional way
// const doubled = numbers.map(function(num) {
//     return num * 2;
// });

// Arrow function (very concise)
const doubled = numbers.map(num => num * 2);

console.log(doubled); // [2, 4, 6, 8, 10]

Summary

Arrow functions are the standard way to write functions in modern JavaScript.

  • You do not need the function keyword.
  • You can omit return and {} for single-line processes.
  • You can omit () for a single argument. Mastering these points makes your code much cleaner. Start by getting used to the basic const func = () => { ... } structure.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次