Skip to content
Hou - Engineer & Tech Educator

Learn Modern JavaScript - Functions

JavaScript, beginner, tutorial, learn-modern-javascript1 min read

Introduction

By the end of this tutorial, you will be able to:

  • use the ES6 arrow function syntax
  • create default function parameters

ES6 Functions: Arrow Functions

Arrow functions were introduced in ES6 and provide a simpler syntax for creating functions along with more intuitive handling of this.

Take a look at this example, which uses an ES5 function expression syntax:

1var printName = function (firstName, lastName) {
2 return `${firstName} ${lastName}`;
3};

To convert the printName() function to use the ES6 arrow syntax, you will have to follow two steps:

  1. Drop the function keyword
  2. Add a fat arrow between the parentheses and opening curly brace

The resulting function will look like this:

1const printName = (firstName, lastName) => {
2 return `${firstName} ${lastName}`;
3};

If your function immediately returns a value, the curly braces wrapping the function body and return statements are not needed and the value is implicitly returned. Here's the shorthand you can use:

1const printName = (firstName, lastName) => `${firstName} ${lastName}`;

Default Parameters

JavaScript function parameters default to undefined. If you want to set a different default value, you can specify default parameters when you define your function. Default parameters allow named parameters of a function to be initialized with default values if no value or undefined is passed during function invocation. For example,

1function add(a, b = 1) {
2 return a + b;
3}
4
5console.log(multiply(5, 2)); // 7
6
7console.log(multiply(5)); // 6

Another example,

1function greeting(name = "Jane", greeting) {
2 return `${greeting}, ${name}! `;
3}
4
5console.log(greeting("John", "Good morning"));
6
7console.log(greeting(undefined, "Good afternoon"));

Want more content like this? Subscribe to get the latest updates in your inbox

Share your Feedback

What did you like or didn't like about this post? Let me know what worked well and what can be improved. Your feedback is much appreciated!