— JavaScript, beginner, tutorial, learn-modern-javascript — 1 min read
By the end of this tutorial, you will be able to:
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:
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}`;
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)); // 76
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"));
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!