DEV Community

Discussion on: Simple concepts of Modern JavaScript

Collapse
 
blindfish3 profile image
Ben Calder

Just to clarify: the intention of arrow functions is not simply to be a shorthand for a normal function; though in practice they do often get used that way. The main intent is to solve a common scoping problem.

When you use a normal function the keyword this is set to that function's scope; but in an arrow function this is set to the parent scope. To illustrate the difference try running the following and looking at the console output:

const PseudoClass = function() {
  this.message = 'this is a pseudo-class property';

  return {
    normalFunction : function() {
      console.log(`normalFunction says: ${this.message}`);
    },
    arrowFunction : () => {
      console.log(`arrowFunction says: ${this.message}`);
    }
  }
};

const instance = new PseudoClass();
// right now you just need to know that you can call
// the functions returned by the PseudoClass function like so:
instance.normalFunction(); // normalFunction says: undefined
instance.arrowFunction(); // arrowFunction says: this is a pseudo-class property

In normalFunction this is scoped to the function where there is no message property.

In arrowFunction this is scoped to the parent where a message property is defined.

Strictly speaking arrow functions are usually intended to be defined in the context of a 'class'.

If you want further detail I always recommend the You don't know JS books for an in-depth and clear explanation of this; scope and why JS doesn't actually have classes :D


One other useful feature of template literals is how they handle white space:

console.log(`there is a line break here
but here \
not`);

Useful to know if you deliberately want to output line breaks; or if you want to break source code onto multiple lines.

Collapse
 
pachicodes profile image
Pachi 🥑

Thank you Ben! As I mentioned, I am currently studying those concepts so your input is VERY helpful!

Collapse
 
blindfish3 profile image
Ben Calder

Happy to contribute. I have often posted my findings to forums precisely to help solidify concepts in my head and in case I had misunderstood anything. It's a really good learning process and has the benefit of helping others :)

One thing that I realised I didn't mention: a common use of arrow functions is in callbacks where you want to maintain the this context:

window.setTimeout(arrowFunction, 100);

Before arrow functions you had to use bind - which felt a little arcane:

window.setTimeout(normalFunction.bind(this), 100);