Skip to main content

Command Palette

Search for a command to run...

Fat arrow functions and default parameters in ES6

There were *two* major additions regarding functions: 1. (Fat) Arrow Functions ( () => {} ) 2. default arguments ( doSmth(arg = 1) )

Updated
•3 min read•View as Markdown
Fat arrow functions and default parameters in ES6

There were two major additions regarding functions:

  1. (Fat) Arrow Functions ( () => {} )
  2. default arguments ( doSmth(arg = 1) )

Function / Arrow Functions

Fat Arrow functions allow you to use a shorter syntax when writing functions:

const fn = (arg1, arg2) => {
    return arg1 * 2 + arg2;
}

Please note:

  1. You may leave out the parenthesis around the arguments if only one argument is passed.
const fn = arg1 => { // no () as only one argument is passed
    return arg1 * 2;
}
  1. If no argument is passed, empty parentheses are required.
const fn = () => { // empty () is required if no arguments are passed
    return 'Hello!';
}
  1. The function body may be written inline and without curly braces if you’re only writing a return statement (return then also may be left out).
const fn = (arg1, arg2) => return arg1 * 2 + arg2; // no curly braces for the body as a single line of code is written for the body

const fn = (arg1, arg2) => arg1 * 2 + arg2; // no return written too

Besides the shorter syntax, fat arrow functions also change the behavior of the this keyword.

Arrow functions have no “this”

Arrow functions are special: they don’t have their “own” this. If we reference this from such a function, it’s taken from the outer “normal” function.

For instance, here arrow() uses this from the outer user.sayHi() method:

let user = {
  firstName: "Ilya",
  sayHi() {
    let arrow = () => alert(this.firstName);
    arrow();
  }
};

user.sayHi(); // Ilya

That’s a special feature of arrow functions, it’s useful when we actually do not want to have a separate this, but rather to take it from the outer context.

Default parameters

Default parameters allow you specify default values for parameters passed to functions.

function fn(arg1 = ‘default string’, arg2 = 23) { return arg1 + arg2 };

fn('Hello!');

This way we can omit arg2 declarations in body of the function. It will take the default value defined in the argument section of the function.

When declaring the function, the order of the arguments in between the () is important. Omitting one argument if the latter has not default parameter will result in an error.

Moreover, no hoisting is applicable to the arguments. Example:

function fn(arg1 = arg2, arg2 = 23) { return arg1 === arg2 };

fn();

The above code will result into an error since arg2 is defined later.

More info on Arrow Functions: Click here to read more

More info on Default Parameters: Click here to read more

More from this blog

I

Is A Web Learning

54 posts