Best of Modern JavaScript — Methods, IIFEs, and this

Image for post
Image for post
Photo by Ethan Schut 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 the spread operator and functions in JavaScript.

Method Definitions Syntax for Methods

We should use the method definition syntax for methods.

For example, we can write:

to define methods in obj .

This is the same as:

If we don’t need the value of this , we can also write:

We used arrow functions so that we don’t have to worry about the value of this in the function.

Avoid IIFEs in ES6

We don’t really need IIFEs in ES6 or later.

The most common use of IIFEs is to define private variables that are only available within a function.

In ES5, we have something like:

In ES6, we can just define tmp within a block:

We also used to use IIFEs as modules.

For instance, we may write something like:

We return an object with the public properties so that we can use them elsewhere.

With ES6, we don’t need this anymore since we have native modules.

For example, we can just write:

module.js

We just create a module file and use export to export what we want from it.

Then we can use it by importing the function.

For example, we can write:

We can still use IIFEs to immediately invoked arrow functions.

For example, we can write:

to sort our array.

The Rules for this

this is defined differently in various situations.

For traditional standalone functions in strict mode, this is undefined .

For traditional standalone functions in sloppy mode, this is the window object.

Generator functions, generator methods, and methods work like traditional functions.

Arrow functions always take the value of this from the function outside of it.

Classes are implicitly strict so we can’t call a class directly.

We’ll get a TypeError if we try to call it directly.

Traditional Functions

Traditional functions are functions that we have from ES5 or earlier.

We can create it as a function expression:

or we can create a function declaration;

this is undefined in strict mode and it’s a global object in sloppy mode.

In method calls this is the receiver of the method call.

It’s the first argument of call or apply .

In constructor calls, this is the newly created instance.

Image for post
Image for post
Photo by Harry Cunningham on Unsplash

Conclusion

There’re various kinds of functions in ES6.

Also, they all have different values of this depending on the type of function and location.

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