Best of Modern JavaScript — Function Names and Arrow Functions

Image for post
Image for post
Photo by Belinda Fewings on Unsplash

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at function names and arrow functions in JavaScript.

Determine Whether a Function was Invoked via new

We can find out whether a function was invoked with new by using the new.target property.

For instance, we can write the following to let us stop the function from being called with new :

If we call it with new foo() , we get the error ‘Uncaught Error: cannot be called as constructor’.

With ES5, we can check for the value of this :

If this is undefined in strict mode, then we know it’s not called with new .

Arrow Functions

Arrow functions are new kinds of functions introduced with ES6.

It solves the problem of bindings with this , arguments and other built-in objects.

Also, they can’t be used as constructors and they’re shorter.

This means they’re great for callbacks.

Traditional Functions are Bad Non-Method Functions

Traditional functions are bad non-method functions since they bind to their own value of this inside the function.

Therefore, the following example won’t work:

The callback is defined with a traditional function, so it has its own value of this .

Therefore, there’s no suffix property in the callback.

To fix this, we can assign the this outside to another value.

For instance, we can write:

We assigned this outside the callback to that , so that we can use it in the callback.

We can also specify the value of this with the map method.

The value is passed into the 2nd argument:

We pass this into the 2nd argument to set this in the callback to the Suffix constructor.

And we can also use bind(this) to return a new function with the this value we want:

With ES6, we don’t need to do any of this.

We just use arrow functions:

We replace our function with an arrow function so won’t have to worry about the value of this in the callback.

We can replace the constructor with the class syntax:

We put everything inside the class.

Conclusion

We can determine whether a function is called with new in various ways.

Also, arrow functions don’t bind to any special values like this inside it, so we can use them for callbacks easily.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store