Languages
[Edit]
EN

JavaScript - arrow functions

0 points
Created by:
Violetd
385

In this article, we would like to show you how to create and use arrow functions in JavaScript.

Quick solution:

const functionName = () => {
  // function body here
}

with arguments:

const functionName = (arg1, arg2) => {
  // function body here
}

without parentheses:

const multiply = x => x * 2;  // example function that multiplies by 2

 

1. Arrow function with no arguments

In this example, we create a simple arrow function with no arguments.

// ONLINE-RUNNER:browser;

const helloWorld = () => {
  console.log('Hello World!');
}

helloWorld();  // Hello World!

2. Arrow functions with arguments

In this example, we create a simple arrow function that displays its arguments in the console.

// ONLINE-RUNNER:browser;

const display = (x, y) => {
  console.log('Argument1 = ' + x);
  console.log('Argument2 = ' + y);
}

display(1, 2);
display('a', 'b');

Output:

Argument1 = 1
Argument2 = 2
Argument1 = a
Argument2 = b

3. Arrow functions without parentheses

In this example, we create an arrow function with no parentheses. The function multiplies the given number by 2. Notice that in this kind of function you don't need the return statement.

// ONLINE-RUNNER:browser;

const multiply = x => x * 2;


// usage example

const result1 = multiply(1);
const result2 = multiply(2);

console.log(result1);  // 2
console.log(result2);  // 4

4. Arrow function vs regular function

In this example, we present a comparison of arrow function with a normal function.

Arrow function solution:

// ONLINE-RUNNER:browser;

const multiply = x => x * 2;

// usage example
const result = multiply(1);
console.log(result);  // 2

is equal to:

// ONLINE-RUNNER:browser;

const multiply = function (x) {
  return x * 2;
}

// usage example
const result = multiply(1);
console.log(result); // 2
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join