Skip to content

Instantly share code, notes, and snippets.

@dotherightthing
Created August 15, 2019 09:56
Show Gist options
  • Save dotherightthing/4af55a4b54ff31fcb1ac59d78b5e2109 to your computer and use it in GitHub Desktop.
Save dotherightthing/4af55a4b54ff31fcb1ac59d78b5e2109 to your computer and use it in GitHub Desktop.
[Arrow functions] Arrow functions are anonymous functions useful for 'one-liners'. #es6 #javascript

Arrow functions

Created: 2017.04.09

They offer a more concise syntax, implicit returns and inherit the value of this from the parent scope.

Explicit returns

function

function function_with_arguments(arg) {
  var arg = arg.toUpperCase();
  return arg; // explicit return
}

console.log( function_with_arguments('foo') ); // FOO

arrow function

var shout = (arg) => {
  return arg.toUpperCase();
}

shout('hello'); // HELLO

Implicit returns

With arguments

var shout = (arg) => arg.toUpperCase();

shout('hello'); // HELLO

Without arguments

var greet = () => console.log('hi!');

greet(); // hi!

Inheritance of parent scope

function

In this example, the timeout function call references the window rather than the button

var button = document.querySelector('button');
button.addEventListener('click', function() {
  console.log(this); // <button>

  // click again
  setTimeout(function() {
    console.log(this); // window
  }, 1000);
});

arrow function

var button = document.querySelector('button');
button.addEventListener('click', function() {
  console.log(this); // <button>

  // click again
  setTimeout( () => {
    console.log(this); // <button>
  }, 1000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment