Top 5 Potent Javascript Tips and Tricks

Top 5 Potent Javascript Tips and Tricks

In this article, I’ll share five potent JavaScript tips, tricks, and best practices that I follow and found useful.

Practising clean code on daily basis seems to be the sign for proficient developer. But we need to know some of the time saving, line of code reduction tips and tricks in order to make our code more optimize. Also I would recommend you to test the code snippets described in below on some editors side by side.

Here comes the top 7 tips and tricks which I found highly potent on practise.

1. Experience more clear and detailed debugging

console.table()

This technique provides us to return our objects, arguments, data in a tabular form on console. Also in this we have an option to restrict number of columns.

Console.table(data); 
/* deafult console.table() */
/* data stands for object need to be printed */
console.table(data,column);
/* data stands for object need to be printed */
/* column parameter used to select a subset of columns to be display on output */

console.time() and console.timeEnd()

It is used to display time took to run the code. Also this is useful with analyzing performance of pieces of our code.

console.time(); // Start the timer 

// Enter the code or function for which you need to analyze the      performance

console.timeEnd(); // Ends the timer

2. Enhanced conditional statements

Multiple Condition Checking

For multiple condition checking we can use either indexOf() or includes() method.

/* Default Approach */
if (letter === a || value === 'A' || value === b || value === 'B' || value === c || value === 'C') 
{ 

}

indexOf()

/* Index of approach */
if ([a, 'A', 2, 'B'].indexOf(letter) >= 0) { 

}

includes()

/* includes approach */
if (['a', 'A', b, 'B'].includes(letter)) { 

}

Optional Chaining

Optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

/* WITHOUT OPTIONAL CHAINING */

if(words && words.letter)
{
  console.log(words.letter.value);
}
/*OPTIONAL CHAINING */

console.log(words?.letter?.value);

Conditionally setting a variable

This approach reduces if else statements.

/* Before */
let employeeType = 'Permanent/Temporary'

if (employee.preferred_empType) {
    employeeType = employee.preferred_empType;
}
/* Conditionally setting a variable */
const employeeType= employee.preferred_empType || 'Permanent/Temporary';

Comparison returns

By declaring comparisons in return statement will reduces 5 to 6 lines of code of conditional statements.

/* Default Approach */

// Longhand
let data;
function checkData() {
    if (!(data === undefined)) {
        return data;
    } else {
        return 'Some error occurred';
    }
}

var userData = checkData();
console.log(userData); //output userData
// Comparison returns
let data;
function checkData() {
    return data || 'Some error occurred';
}
var userData = checkData();
console.log(userData); //output userData

3. Arrays

To Get an Array of Unique Value

set() is used to get an array of unique values.

const studentId = [101, 101, 102, 103, 105, 105, 101];
const uniqueId = [...new Set(studentId)];
console.log(uniqueId); 

// Result: [101, 102, 103, 105]

To Split a String into an Array

const string = "Form"
const splitValue = [...string] // the spread operator ...
console.log(splitValue);

// Result: ["F", "o", "r", "m"]

To Find Max and Min in an array

var  values = [25,100,30,55,15,80,200,360,70,40,45,130]; 
var maxValue = Math.max.apply(Math, values); 
var minValue = Math.min.apply(Math, values);

Truncate an array

This method allows you to truncate an array without using splice() .

/* Our approach */

let names = ['Ram', 'Sita', 'Nithya', 'Varun ', 'Devi']
names.length(3);
console.log(names); 

// Result: ['Ram', 'Sita', 'Nithya']
/* Using slice() */

let names = ['Ram', 'Sita', 'Nithya', 'Varun ', 'Devi']
names.slice(0,3);
console.log(names); 

// Result: ['Ram', 'Sita', 'Nithya']

To Cast values in an array

let values=['201','202','203,'204','205]
values = values.map(Number) 

// Result: [ 201, 202, 203, 204, 205 ]

4. Objects

Object Destructring

Using destructuring we can able to directly get the objects.

/* Default approach */

const user = {
status:'Active';
ratings:'5';
}
const rating = user.ratings;
console.log(rating);
/* Default approach */

const user = { status:'Active'; ratings:'5'; }
const  { status, ratings } = user;
console.log(ratings);

Object.entries()

object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.

const userOne = {
  id: '101',
};

for (const [key, value] of Object.entries(userOne)) {
  console.log(`${key}: ${value}`);
}

// Result:  id: 101

Object.values()

object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided.

const userOne = {
  id: '101',
};

console.log(Object.values(userOne));

// Result: ['101']

5. Tips to note further

Quick Powers

The ** operator returns the result of the first variable to the power of the second variable.

/* Quick Powers */
10 ** 10; // 100

/* Default approach */
Math.pow(10, 10); //100

To repeat a string multiple times

/* Default approach */

let name = 'x'; 
for(let i = 0; i < 6; i ++) { 
  name += name; 
} 
console.log(name); // x x x x x x
/* using repeat() */

var x = "x".repeat(6);

console.log(x);

// x x x x x x

Final tip is to use Semicolons at the end of each statements to improve readability.

Conclusion

I hope you found these tips useful. Thank you so much for reading !

Also I am going write a series of article on javascript with underhood concepts. So be sure to checkout my blog page.

Do comment out the tips which I would have missed out but it has helped you in much better way.