3 minutes read

When writing a calculator program in JavaScript, functions can be used to develop its functionality. These functions can be written using the syntax we already know. For example, here is a function for adding two numbers:

function append(a, b) {
  result = a + b;
  return result;
}

JavaScript has a shorter and more convenient way to write functions — arrow functions. Here is the same example as above written with the arrow functions syntax:

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

We don't just declare a function, but we are also storing it in a variable. An arrow function can be used as an ordinary function:

let result = append(30, 5)
console.log(result) // 35

Setting arrow functions

You can use two methods to assign arrow functions:

let append = (a, b) => a + b; // short syntax

And:

let append = (a, b) => { return a + b; }; // block syntax

Unlike parentheses, the main difference is that curly braces allow us to write multiline instructions inside a function. However, remember that when using this method, you must specify a return directive to return the value.

If there is one parameter in your function, you do not need to frame it with parentheses. For example:

let sum = a => a + 2;
sum(1);  // 3

At the same time, parentheses are required in functions without parameters.

Arrow functions are anonymous functions. Therefore, you cannot call them before initialization.

Comparison

Let's create some functions using traditional syntax, block arrow function syntax, and short arrow function syntax and compare them:

function mult1(a, b) {
  return a * b;
}
let mult2 = (a, b) => { return a * b; };
let mult3 = (a, b) => a * b;

console.log(mult1(3, 2)) // 6
console.log(mult2(3, 2)) // 6
console.log(mult3(3, 2)) // 6

As you can see, the results of all these functions are identical, but the shorter syntax of the arrow function makes it more convenient to write.

Using a tool appropriate for the particular problem is essential. Don't use Arrow functions if you have code where all functions are written traditionally. Always think in terms of the existing code structure.

Conclusion

We considered Arrow functions and two ways of setting them in the topic. We checked that different methods yield the same results, but some are more convenient. Be wise about this new knowledge, and good luck with the practice tasks!

522 learners liked this piece of theory. 4 didn't like it. What about you?
Report a typo