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:
const obj = {
foo() {},
bar() {}
}
to define methods in obj
.
This is the same as:
const obj = {
foo: function() {},
bar: function() {}
}
If we don’t need the value of this
, we can also write:
const obj = {
foo: () => {},
bar: () => {}
}
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:
(function() {
var tmp = 'foo';
//...
}());
In ES6, we can just define tmp
within a block:
{
let tmp = 'foo';
//...
}
We also used to use IIFEs as modules.
For instance, we may write something like:
var module = (function() {
var foo = 0;
function bar(x) {
foo++;
//...
}
return {
bar: bar
};
}());
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
let foo = 0;
export function bar(x) {
foo++;
//...
}
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:
import { foo } from './module';
foo(100);
We can still use IIFEs to immediately invoked arrow functions.
For example, we can write:
const arr = [3, 2, 1];
const sorted = (() => {
arr.sort();
return arr.join('');
})();
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:
const foo = function(x) {
//...
};
or we can create a function declaration;
function foo(x) {
//...
}
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.
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.
The post Best of Modern JavaScript — Methods, IIFEs, and this appeared first on The Web Dev.