As we all know that JavaScript has completely changed the way of web development, Earlier javascript was only used for frontend tasks like form validation, UI manipulation as per the user activity, etc, but now complete web application is being developed by using JavaScript after Node.js came into existence.
When I started my development career in 2013, I used JavaScript for only frontend purposes, and then I started working on Node.js then Angular.js(Angular 1st version), and today I am working on JavaScript Frameworks like node.js, Angular 2+, React. The reason to share this is that I have felt the change occurred in web development.
So today, I am going to share with you the 11 most useful tips which will change your JavaScript Programming or your code quality while working with JavaScript.
JavaScript ES6 introduced a new way to define a variable, let and const. Where let is used for a variable which value may change later and const is used for a variable which will hold a value which will not change anyway. Earlier var was used for all types of variable requirements.
In JavaScript, It is not good practice to define a variable as a global variable. The reason is that there is a possibility to inadvertently modify the global variable from anywhere within the code. To prevent this we need to ensure the scope of the variable limited to the code block where it is required.
Example:
Let and const is block-level(code block surrounded by curly brace {}) where as var is function scoped, means its scope is in entire function with in which it is defined.
With var
{ // block 1
Var x = 10;
Console.log(x); // Output:10
}
{ // block 2
X++;
console.log(x); Output : 11, value increment because it is function scoped.
}
With let
{ // block 1
let x = 10;
Console.log(x); // Output:10
}
{ // block 2
X++;
console.log(x); We have declared x with let so the scope of x is within that block only so x is not recognized in block 2
}
It is introduced by ES6 which simplifies the function definition and makes the code more cleaner.
Without Arrow Function
const helloMsg = function(firstName, lastName){
console.log(‘Hello ’+ firstName+’ ’+lastName);
}
With Arrow function
const helloMsg =(firstName, lastName){
console.log(‘Hello ’+ firstName+’ ’+lastName);
}
The use of Higher Order Functions are much helpful and easy, It reduces our code so we should try to use this as much as we can.
I have already posted a detailed article on this topic, Click here Higher Order Function in JavaScript
With the help of this operator, more than 5 lines of code can be converted into a single line of code.
Syntax:
condition ? ( if condition is true) : (if condition is false)
Example:
Without ternary operator
const age = 15;
if (age < 18) {
console.log('User is not adult');
} else {
console.log('User is adult');
}
// Output: User is not adult
With ternary operator
const age = 15;
age<18 ? console.log('User is not adult') : console.log('User is adult');
console.log('User is adult');
Console messages can be shown in a much-improved way using the console.table when you want to console an object variable or array of objects.
const fruits =[
{“name”:”Orange”,”count”:12,”availableForSell”:true},
{“name”:”Apple”,”count”:22,”availableForSell”:false},
{“name”:”Banana”,”count”:24,”availableForSell”:true}
];
console.table(fruits);
console.table will print the data like below:
Template literals are enclosed by the backtick (` `) (grave accent) character instead of double or single quotes. It is very useful when we need to print message/assign value with concatenating string value with variable.
See the example below:
Let name = “John”;
Let city = “Sydney”;
//Without template string/literals
Let helloMsg = “Hi ”+ name+”!, Welcome to ”+city;
//With template string
Let helloMsg = `Hi ${name}!, Welcome to ${city}`;
With Object, destructuring code repetition can be removed and the code will look more readable.
See the example below:
const user = {“name”:”Ram”,”age”:25};
const func = (user) => {
const { name, age } = user; // object can be also destructured in above line ({ name, age }) in place of (user)
return `${name} is ${age} years old.`;
};
console.log(func(user));
JavaScript ES6 (ECMAScript 6) introduced the spread operator. It expends the array in individual elements. The syntax is three-dot(...) before the item you want to spread.
With the help of this operator the task like Copy an array, concatenate arrays, Add elements into Array, Convert String to Array, and other very common tasks can be done in a very easy and shorter way. I have already posted a detailed article on Spread Operator, Click here Improve your code in JavaScript with Use of ES6 Spread Operator
It looks very similar to the syntax of spread operator but it’s use is to destructuring arrays and objects. It allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements.
See the example below:
function xyz(x, y, ...z) {
console.log(x, ' ', y); // hey hello
console.log(z); // ["wassup", "goodmorning", "hi", "howdy"]
console.log(z[0]); // wassup
console.log(z.length); // 4
}
xyz("hey", "hello", "wassup", "goodmorning", "hi", "howdy");
ES6 supports computed object property names, It mainly allows us to put an expression in brackets [], that will be computed and used as the property name/key.
let key = 'A_KEY_NAME_STRING';
let obj = { [key]: 'ASSIGNED_VALUE', };
console.log(obj) // Result: { 'A_KEY_NAME_STRING': 'ASSIGNED_VALUE' }
If it is required to remove array items from the end of the array, there is a much simpler approach to do this task than using splice.
See the example below:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // output: [0,1,2,3]
If want to remove all items in it
array.length= 0;
console.log(array); // output: []
The above tips mentioned can improve the coding standard a lot while coding in JavaScript.
Let me know your thoughts over email pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.
Thanks!