Learn modern javascript in 10 simple ways

Adebisi Ahmed Philip
10 min readJun 17, 2018

Es6 has come to stay, with the cool new features added to javascript developing javascript applications has now become easier and fun.
I would like to show you this 10 hot tips that would ease your work flow and help you write modern and efficient JavaScript (less lines of code). I won’t bore you with less important information, plus you can always read up on es6 if you want. Let’s dive right in.

1. Template Strings

String interpolation before was done with the + operator in javascript, now you can use the template strings `` called backticks and ${variable} to add a variable to the string. This allows you to interpolate variables with strings easily. The backticks button is to left of 1 on the keyboard.

//The old way
const age = 20;
let message = 'I am '+age+' years old';
console.log(message); // I am 20 years old
// The new way
message = `I am ${age} years old`;
console.log(message); // I am 20 years old

2. Exchanging data in variables

If you wanted to exchange the values of two variables say x and y. The way you would do that before was to declare a temp variable which would store the x value, now x can store the value of y then restore the value of temp into y.

//The old way
let x = 10;
let y = 5;
let temp = x;
x = y;
y = temp;
console.log(`x = ${x}`, `y = ${y}`); //x = 5 y = 10

//The new way
x = 10;
y = 5;
[x, y] = [y, x];
console.log(`x = ${x}`, `y = ${y}`); //x = 5 y = 10

The new way is pretty simple. This simply means take the value of y on the right store it in x on the left and take the value of x on the right and store it in y on the left.

How would you exchange 3 variables? huh!👈

let a = 10;
let b = 5;
let c = 6;
[b, c, a] = [a, b, c];
console.log(`a = ${a}`, `b = ${b}`, `c = ${c}`);
//a = 6 b = 10 c = 5

3. Destructuring

Destructuring allows you to pick and choose the data you want from an array of items, objects, maps and sets.

const [a, b] = [1, 2, 7];
console.log(a, b); // 1 2
// Omit certain values
const [c, , d] = [1, 2, 3];
console.log(c, d); //1 3

When destructuring arrays you use a square bracket on the left hand side of the assignment operator and put in as many variables as you want. The data picked out of the array is dependent on the order of the variables. a maps to 1 and b maps to 2. You can omit certain variables if you want by using commas.

const user = {
firstname: "Ahmed",
lastname: "Adebsi",
socials: [
{ twiterHandle: "Ade_Phil" },
{ instagramHandle: "Ade_Phil" },
]
}
//To get first and lastname without destructuring
console.log(user.firstname, user.lastname); //Ahmed Adebsi
//With destructuring
const { firstname, lastname } = user;
console.log(firstname, lastname); //Ahmed Adebsi
//Destructuring with new variable names
const { firstname: first, lastname: last } = user;
console.log(first, last); // Ahmed Adebsi

The first method works fine but imagine i had to use my firstname and lastname in multiple places in my code i would keep referencing user.firstname and user.lastname. what i can do is destructure them into their own seperate variables. Notice the curly braces which firstname and lastname are wrapped around, this shows that they are properties of an object, in this case the user. In destructuring the name of the variable has to match the property on that object. You can change the variable names as shown above if you want.

4. Spread and Rest

The spread and rest operator are both represented with (…). It is called spread or rest depending on the use case.

  • spread

The importance of the spread operator is immutability. It helps you create a new array without modifying the old one. Let’s look at some examples.

const oldArray = [1, 3, 5,6];
const newArray = [...oldArray, 8];
console.log(oldArray); //[ 1, 3, 5, 6 ]
console.log(newArray); //[ 1, 3, 5, 6, 8 ]

The first line creates an array with some numbers in it. The second line creates a new array, spreads the data of the oldArray into it and the adds the new number which is 8. The spread opearator here takes each element in the oldArray and adds it to the newArray before adding the new number 8.

console.log(Math.min(2, 3, 1));
// expected output: 1
const numbers = [2, 3, 1];
console.log(Math.min(...numbers));
// expected output: 1

In this case the the min function expects a comma separated list of arguments which should be numbers. What we can simply do is to spread the data in the array into the function. Yes! it works.

  • Rest

The rest operator allows you to group items you are destructuring together. A simple login example in react.

state = {
email: '',
password: '',
errors: {}
}

const {errors, ...formData} = state;
const validationErrors = validate(formData);

In this example, the state object contains the errors object which is not part of the data we are getting from the user. The data we need to do validation on and submit to the backend is the email and password. so using destructuring we take out the errors object and the rest of the data left is called formData in this case. formData is now an object with only email and password properties.

5. Map method in javascript

The map method is an immutable (The old array is not modified) array method that produces a new array with each items modified. You can sort of think of it as an assembly line of products in which labels are added to each item by the machine. The map method takes a callback function as an argument. The callback function takes as argument, a variable that references each element in the array.

Example 1

const surname = 'Adebisi';
const siblings= ['Taofeek', 'Saheed', 'Akeem', 'Motunrayo', 'Bukola'];
const siblingsWithSurname = siblings.map(member => {
return `${member} ${surname}`;
});
siblingsWithSurname.forEach(person => console.log(person));// Taofeek Adebisi
// Saheed Adebisi
// Akeem Adebisi
// Motunrayo Adebisi
// Bukola Adebisi

Here the surname variable represents the label that is attached to each of the products in this case the name of my siblings. To produce a concatenation of each of the names to with the surname. You can shorten the code to one line. If it’s one line of code there’s no need for the return keyword. It is implied.

const siblingsWithSurname = siblings.map(member =>`${member} ${surname}`);

Example 2

linksDiv.innerHTML = links.map((link, i) => {
return `
<li class = "items">
<span class="fa fa-star " data-star=star${i}></span>
<label for="item${i}">${link.text}</label>
<span data-index=${i} class="fa fa-close options"></span>
<span data-index=${i} class="fa fa-external-link options"> </span>
</li>
`
}).join('');

links is an array of links. Each of the link is meant to be represented by some html. The link name, the star rating for the link, open in a new tab button and a close button. Mapping the links returns an array where each link is now represented by an html for it. Since this is an array of strings separated by commas we can join() on the returned array to concatenate them into one big string. linksDiv is just a div where we can insert our html.

One last example.

const productItems = this.state.products.map(product => {
return (
<Product product={product} key={product.id} addToCart={this.addToCart} />
)
});

In react land, we have a list of products set in state. Each product is an object which will be represented by a component. So we map over it to return a Product component.

In conclusion, the map method returns a new array of the same number of items represented in a new way.

6. Reduce method in javascript

Reduce takes in an array of items and returns a single item. The way i like to think of this is baking a cake. You need ingredients such as flour, sugar, eggs, milk... The ingredients represent what you pass into reduce and the cake represents the output (A single entity).

Example 1

const orderItems = [
{name: 'hp-envy m6', price: 2500, rating: 4},
{name: 'lenovo', price: 2500, rating: 5},
{name: 'mac book pro', price: 2500, rating: 5}
];
const totalPrice = orderItems.reduce((sum, item) => {
return sum + item.price;
},0);

Reduce requires two arguments a callback function which takes two arguments the sum so far and an a reference to each item in the array and an initial value of the sum. In this case the initial value of the sum is 0. Sum starts out being 0. we add the first item’s price to the sum, then second, third…last.

Example 2

const people = ['boy', 'girl', 'girl', 'girl', 'man', 'woman','boy']; const count = people.reduce((sum, person) => {
sum[person] = (sum[person] === undefined) ? 1 : ++sum[person];
return sum;
}, {});
console.log(count); // { boy: 2, girl: 3, man: 1, woman: 1 }

In this case there are duplicate items in the array. So what we want is an object whose key is the item in the array and the value is number of times each of the items occur. Initially the sum is an empty object. The first thing we want to check is if the sum object has property whose name correspond to the person. if its doesn’t exist set the count to 1 i.e this is the first time we are seeing that person. (the first time we encounter boy, sum[‘boy’] will be undefined so we set the value to 1). The next time the same person is encountered the property already exist on the object so we simply increment the initial count.

In conclusion anytime you have an array of items and you need to return just one item, use reduce.

7. Filter method in javascript

Filter takes in an array and returns a new array based on some Boolean condition. The way i like to think of filter is a recruitment process where some candidates are selected for the job based on some criteria.

const orderItems = [
{name: 'hp-envy m6', price: '2500', rating: 4},
{name: 'lenovo', price: '2500', rating: 5},
{name: 'mac book pro', price: '2500', rating: 5}
];
const fiveStarOrders = orderItems.filter((order) => order.rating == 5);/*
[ { name: 'lenovo', price: '2500', rating: 5 },
{ name: 'mac book pro', price: '2500', rating: 5 }
]
*/

Here, i’m checking for ordered Items with 5 star rating.

8. Object Literal Upgrades

Object literals have undergone an upgrade. If the key of the object literal is the same as the value then you just leave out the key and use only the value. There’s also a new way for declaring functions inside an object which to remove the function keyword and the colon in front of it.

const price = 4.20;
const quantity = 20;
// The old way
let invoiceData = {
price: price,
quantity: quantity,
printInvoice: function () {
console.log(`price = ${this.price}`, `quantity = ${this.quantity}`);
}
}
invoiceData.printInvoice(); // price = 4.2 quantity = 20// The new way
invoiceData = {
price,
quantity,
printInvoice() {
console.log(`price = ${this.price}`, `quantity = ${this.quantity}`);
}
}
invoiceData.printInvoice(); //price = 4.2 quantity = 20

9. Using && and || shorthand syntax

You can use the && and || operators in javascript to check the truthy/falsey nature of a variable in javascript. Then based on that do something.

  • && syntax
param && fieldProps.input.onChange(param.value);

In the code above i am checking if the variable (param) is a truthy value. If it is i get the value property from the param object and pass it the onChange function and call it. Note the function is only called if the param object has a truthy value. The essence of doing this is to ensure that the param object is defined while calling the value property on it.

  • || syntax
const links = JSON.parse(localStorage.getItem(‘links’)) || [];

In the code above i’m getting a list of links from localStorage and converting it to a javascript object. If links doesn’t exist in localStorage it returns null and calling JSON.parse on it returns null. Since what is on the left of the || operator is null, it takes what is on the right of it which is an empty array and stores it in the links variable.

In summary, if what is on the left of the || operator is a falsey value it defaults to what is on the right of it else it uses what is on the left.

10. Using some method in javascript

The some method returns a Boolean (true or false) which signifies if an item is present in an array or not. The good old way is to use a for loop to iterate through the array, check if the item exists and break out of the loop. some() is a cleaner way to do this.

const friends = [
{ name: 'deji', age: 16 },
{ name: 'damola', age: 18 },
{ name: 'itunu', age: 20 },
{ name: 'ore', age: 21 },
{ name: 'Maxy', age: 20 },
{ name: 'jide', age: 19 },
{ name: 'Dami', age: 20 },
{ name: 'Philip', age: 26 },
{ name: 'Bridget', age: 44 },
{ name: 'Yusuf', age: 30 },
{ name: 'OG', age: 35 },
];
const minor = friends.some(friend => friend.age < 18); //true

This article is targeted at beginners and I honestly hope you can pick out one or two things which you can use in your daily development. This was edited by Adegoke Damola. You can follow me on twitter Adebisi Ahmed Philip. More exciting articles coming up soon.

📝 Read this story later in Journal.

🗞 Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: Get the noteworthy newsletter >

--

--

Adebisi Ahmed Philip

Software Developer. Focusing on concepts rather than tools and languages.