if / else replacement
Longhand:
const x = 20;
let answer;
if (x > 10) {
answer = "greater than 10";
}else {
answer = "less than 10";
}
Shorthand:
const answer = x > 10 ? "greater than 10" : "less than 10"
variable assignment checking to see if variable exists first
Longhand:
if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
let variable2 = variable1;
}
Shorthand:
const variable2 = variable1 || 'new';
multiple variables at the same time and assignments
Longhand:
let x;
let y;
let z = 3;
Shorthand:
let x, y, z=3;
if checks can be trivial if the value is truthy value already
Longhand:
if (likeJavaScript === true)
Shorthand:
if (likeJavaScript)
case for not truthy
Longhand:
let a;
if ( a !== true ) {
// do something...
}
Shorthand:
let a;
if ( !a ) {
// do something...
}
super helpful vanilla js method of looping
Longhand:
const fruits = ['mango', 'peach', 'banana'];
for (let i = 0; i < fruits.length; i++)
Shorthand:
for (let fruit of fruits)
also works if you want the index as well
for (let index in fruits)
and accessing keys in a literal object
const obj = {continent: 'Africa', country: 'Kenya', city: 'Nairobi'}
for (let key in obj)
console.log(key) // output: continent, country, city
Shorthand for Array.forEach
function logArrayElements(element, index, array) {
console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[2] = 9
instead of six lines to assign a default value if the intended param is null or undefined
Longhand:
let dbHost;
if (process.env.DB_HOST) {
dbHost = process.env.DB_HOST;
} else {
dbHost = 'localhost';
}
Shorthand:
const dbHost = process.env.DB_HOST || 'localhost';
It’s essentially a fancy way to write numbers without the trailing zeros.
Longhand:
for (let i = 0; i < 10000; i++) {}
Shorthand:
for (let i = 0; i < 1e7; i++) {}
// All the below will evaluate to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;
Defining object literals makes es6 way better
Longhand:
const x = 1920, y = 1080;
const obj = { x:x, y:y };
Shorthand:
const obj = { x, y };
Classical functions are easy to read and write in their plain form, but they do tend to become a bit verbose and confusing once you start nesting them in other function calls.
Longhand:
function sayHello(name) {
console.log('Hello', name);
}
setTimeout(function() {
console.log('Loaded')
}, 2000);
list.forEach(function(item) {
console.log(item);
});
Shorthand:
sayHello = name => console.log('Hello', name);
setTimeout(() => console.log('Loaded'), 2000);
list.forEach(item => console.log(item));
Return is a keyword associated with final results of a function. Using a () will eval in a single statement
Longhand:
function calcCircumference(diameter) {
return Math.PI * diameter
}
Shorthand:
calcCircumference = diameter => (
Math.PI * diameter;
)
Using if statements to define default values for function params. You can in es6 define in the function declaration itself
Longhand:
function volume(l, w, h) {
if (w === undefined)
w = 3;
if (h === undefined)
h = 4;
return l * w * h;
}
Shorthand:
volume = (l, w = 3, h = 4 ) => (l * w * h);
volume(2) //output: 24
end the concat ' + ' stuff with strings
Longhand:
const welcome = 'You have logged in as ' + first + ' ' + last + '.'
const db = 'http://' + host + ':' + port + '/' + database;
Shorthand:
const welcome = `You have logged in as ${first} ${last}`;
const db = `http://${host}:${port}/${database}`;
working with any framework high chances of arrays or data in forms of object literals to pass data in components or apis
Longhand:
const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');
const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;
Shorthand:
import { observable, action, runInAction } from 'mobx';
const { store, form, loading, errors, entity } = this.props;
or even assign your own variables
const { store, form, loading, errors, entity:contact } = this.props;
Really gross concat strings can be changed with backticks
Longhand:
const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'
+ 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'
+ 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'
+ 'veniam, quis nostrud exercitation ullamco laboris\n\t'
+ 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'
+ 'irure dolor in reprehenderit in voluptate velit esse.\n\t'
Shorthand:
const lorem = `Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse.`
The spread operator, introduced in ES6, has several use cases that make JavaScript code more efficient and fun to use. It can be used to replace certain array functions. The spread operator is simply a series of three dots.
Longhand:
// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()
Shorthand:
// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];
unlike the concat() function you can use the spread operator to insert an array anywhere inside another array
const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];
you can also combine the spread operator with the es6 destructuring notation
const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }
by default js will set function params to undefined if they are not passed a value. to enforce param assignement you can use an if statement to throw an error if a undefined
Longhand:
function foo(bar) {
if(bar === undefined) {
throw new Error('Missing parameter!');
}
return bar;
}
Shorthand:
mandatory = () => {
throw new Error('Missing parameter!');
}
foo = (bar = mandatory()) => {
return bar;
}
old method was a for loop to find, now es6 has find()
Longhand:
const pets = [
{ type: 'Dog', name: 'Max'},
{ type: 'Cat', name: 'Karl'},
{ type: 'Dog', name: 'Tommy'},
]
function findDog(name) {
for(let i = 0; i<pets.length; ++i) {
if(pets[i].type === 'Dog' && pets[i].name === name) {
return pets[i];
}
}
}
Shorthand:
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }
Did you know that Foo.bar can also be written as Foo['bar']? At first, there doesn’t seem to be a reason why you should write it like that. However, this notation gives you the building block for writing re-usable code.
Longhand:
function validate(values) {
if(!values.first)
return false;
if(!values.last)
return false;
return true;
}
console.log(validate({first:'Bruce',last:'Wayne'})); // true
Shorthand:
// object validation rules
const schema = {
first: {
required:true
},
last: {
required:true
}
}
// universal validation function
const validate = (schema, values) => {
for(field in schema) {
if(schema[field].required) {
if(!values[field]) {
return false;
}
}
}
return true;
}
console.log(validate(schema, {first:'Bruce'})); // false
console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true
Bitwise operators are one of those features you learn about in beginner JavaScript tutorials and you never get to implement them anywhere. Besides, who wants to work with ones and zeroes if you are not dealing with binary?
There is, however, a very practical use case for the Double Bitwise NOT operator. You can use it as a replacement for Math.floor(). The advantage of the Double Bitwise NOT operator is that it performs the same operation much faster. You can read more about Bitwise operators here.
Longhand:
Math.floor(4.9) === 4 //true
Shorthand:
~~4.9 === 4 //true
Shorthand for a Math exponent power function:
Longhand:
Math.pow(2,3); // 8
Math.pow(2,2); // 4
Math.pow(4,3); // 64
Shorthand:
2**3 // 8
2**4 // 4
4**3 // 64
There are times when your code receives data that comes in String format but needs to processed in Numerical format. It’s not a big deal, we can perform a quick conversion.
Longhand:
const num1 = parseInt("100");
const num2 = parseFloat("100.01");
Shorthand:
const num1 = +"100"; // converts to int data type
const num2 = +"100.01"; // converts to float data type
Consider the following piece of code:
let fname = { firstName : 'Black' };
let lname = { lastName : 'Panther'}
How would you merge them into one object? One way is to write a function that copies data from the second object onto the first one. Unfortunately, this might not be what you want — you may need to create an entirely new object without mutating any of the existing objects. The easiest way is to use the Object.assign function introduced in ES6:
let full_names = Object.assign(fname, lname);
You can also use the object destruction notation introduced in ES8:
let full_names = {...fname, ...lname};
When performing a lookup using an array, the indexOf() function is used to retrieve the position of the item you are looking for. If the item is not found, the value -1 is returned. In JavaScript, 0 is considered ‘falsy’, while numbers greater or lesser than 0 are considered ‘truthy’. As a result, one has to write the correct code like this.
Longhand:
if(arr.indexOf(item) > -1) { // Confirm item IS found
}
if(arr.indexOf(item) === -1) { // Confirm item IS NOT found
}
Shorthand:
if(~arr.indexOf(item)) { // Confirm item IS found
}
if(!~arr.indexOf(item)) { // Confirm item IS NOT found
}
The bitwise() operator will return a truthy value for anything but -1. Negating it is as simple as doing !. Alternatively, we can also use the includes() function:
if(arr.includes(item)) { // Returns true if the item exists, false if it doesn't
}
This is a feature that was introduced in ES8 that allows you to convert a literal object into a key/value pair array. See the example below:
const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.entries(credits);
console.log(arr);
/** Output:
[ [ 'producer', 'John' ],
[ 'director', 'Jane' ],
[ 'assistant', 'Peter' ]
]
**/
This is also a new feature introduced in ES8 that performs a similar function to Object.entries(), but without the key part:
const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.values(credits);
console.log(arr);
/** Output:
[ 'John', 'Jane', 'Peter' ]
**/