We as developers must be trying to use the best tools and features in our disposition to make our job more easy and efficient.
Here I’m going to explain 5 features of modern Javascript that are very helpful and you are going to be using all the time:
It’s 2019 and every modern browser support all these features so there is no excuse!.
You can run all the example code in your browser Developer Tools
In Javascript var was the only way to declare a variable, the problem with var is it has no scope and you can declare the same variable multiple times, that is why now we have let and const keywords.
let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.[1]
Let’s see an example:
var date = new Date("2015-01-01");
var region = "US";
// Some were further in the code
if (region === "US") {
var date = new Date();
console.log("New date", date); // We get the current date as expected
}
console.log(date); //Expecting 2015-01-01T00:00:00.000Z but we get the current date
We developers are bad at naming and if we are working with others the problem is magnified 10x. So is no rare that we use the same name for different things.
Let’s see how this work with let
let date = new Date("2015-01-01");
let region = "US";
// Some were further in the code
if (region === "US") {
let date = new Date();
console.log("New date", date); // We get the current date as expected
}
console.log(date); //We get 2015-01-01T00:00:00.000Z as expected :)
For me scoping is the more important feature of let. Other features are:
const allows us to declare a constant variable, a value that shouldn’t change in our code. Let’s see an example:
const speedOfLight=299792458; //m*s-1
try {
speedOfLight=300;
} catch(error) {
console.log(error); // TypeError: Assignment to constant variable.
// Note - error messages will vary depending on browser
}
console.log(speedOfLight); // Expected output 299792458
Other features of const:
Note: Another good practice for variables is always declare variables on the top of your function or block scope, is more easy to keep track.
For this 2019 please please don’t use var anymore.
Arrow functions (also known as fat arrow for the => symbol) has a shorter syntax that a regular function and allow us to write more concise code.
Let’s see the difference between old function expressions and arrow functions:
//ES5
let doubleNumbers = [1,2,3,4,5].map(function(number) {
return number*2;
});
//ES6 Arrow function
let doubleNumbers = [1,2,3,4,5].map((number) => {
return number*2
});
In arrow functions, you don’t need parenthesis when you have only one argument and if a one-liner expression like this you can drop the return and the curly braces:
//ES6 Arrow function one-liner
let doubleNumbers = [1,2,3,4,5].map(number => number*2);
//ES6 Arrow function multiple arguments
handleClick((event, seconds) => {
event.preventDefault();
displayFireworks();
showAnimation(seconds);
});
Arrow functions save us a lot of typing and also, in my opinion, make the code more readable.
What we lose with arrow functions is that we don’t have reference to this, arguments, super or new.target. This means that if you really need any of these arguments inside a function you should use traditional functions.
My recommendation is that you should use arrow functions as much as you can. In code, readability is key.
This is one of my favorite features of ES6.
Let’s see first an example:
// Old method
const myArray = ['apple', 'pear', 'orange', 'banana'];
let fruit1 = myArray[0];
let fruit2 = myArray[1];
let fruit3 = myArray[2];
let fruit4 = myArray[3];
//ES6 destructuring
let [fruit1, fruit2, fruit3, fruit4] = myArray; // much better isn't?
We can use it on objects to:
let dog = {
name: 'Toby',
age: 3,
breed: 'Beagle',
features: {
color: 'White and brown',
favoriteToy: 'Plastic duck'
}
}
// We can obtain the values like this with destructuring
let {name, age, breed} = dog;
// What if we want only name and age and all the other in another variable
let {name, age, ...info} = dog;
So what destructuring assignment allows us is extracting data from arrays or objects into distinct variables in an easy useful way.
I use it all the time for JSON objects.
Bonus
You can also go the other way around:
let firstName="Albert"
let lastName="Einstein"
let person = {firstName, lastName}
console.log(person.firstName); // "Albert"
console.log(person.lastName); // "Einstein"
Spread operator allows us to “spread” (duh!) or “explode” an array into its individual items.
Let’s see an example:
let first = [1,2,3];
let second = [4,5,6];
// If we do this
first.push(second);
// We get
console.log(first); // [1,2,3,[4,5,6]] that is not right
// Using the spread operator
first.push(...second);
console.log(first); // [1,2,3,4,5,6] that's what we wanted!
Using the spread operator (…) we manage to obtain each individual element without doing an iteration, this is very helpful in many situations. Let’s see another example:
let scores = [23, 45, 56];
function averageThreeScores(a, b, c) {
let sum = a + b + c;
return sum/3;
}
console.log(averageThreeScores(...scores)); // Result 41.333333...
Here we are using the spread operator to pass arguments to a function.
Spread operator also works with objects. As with arrays, the spread operator allows us to obtain each individual element of an object:
let name='Toby';
let age=3;
let features = {race: 'Beagle', size: 'small'};
let dog = {name, age, ...features}; // We expand the features object
console.log(dog); // {name: 'Toby', age: 3, race: 'Beagle', size: 'small'}
Spread operator also allow us to clone an object instead of using Object.assign:
let dog = {name: 'Toby', age: 3, race: 'Beagle', size: 'small'}
let puppy = {...dog, name: 'Max', age: 1}; // Clone dog object and modify its properties
console.log(puppy); // {name: 'Max', age: 1, race: 'Beagle', size: 'small'}
console.log(dog); // {name: 'Toby', age: 3, race: 'Beagle', size: 'small'}
As we can see we clone the dog object, and we changed the value of age and name without modifying the original object.
We use strings everywhere, and we usually have to pass some variable to the string. Here is where Template literals come to the rescue.
Template literals are enclosed by the back-tick () character instead of double or single quotes.
Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}):
let a = 5;
let b = 10;
console.log(`The sum of a and b is ${a+b} and the multiplication is ${a*b}`);
// The sum of a and b is 15 and the multiplication is 50
We can also write multiline text like:
let name='Mike';
let age=30;
let country='Italy';
console.log(`${name} is
${age} years old and
lives in ${country}
`);
// Mike is
// 30 years old and
// lives in Italy
Here Javascript will show multiline text and will respect the spaces without the requirement of special characters such as \n.
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/
That is, for now, I hope that find this helpful. If you have any questions or anything that you want to add please leave a comment!
*Originally published by ****Olivers De Abreu ****at *dev.to
==============================
Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter
☞ The Complete JavaScript Course 2019: Build Real Projects!
☞ Become a JavaScript developer - Learn (React, Node,Angular)
☞ JavaScript: Understanding the Weird Parts
☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
☞ The Full JavaScript & ES6 Tutorial - (including ES7 & React)
☞ JavaScript - Step By Step Guide For Beginners
☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js
#javascript