Skip to main content

Command Palette

Search for a command to run...

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.

Published
5 min read
Top 5 Potent Javascript Tips and Tricks
G
I am a results-driven professional with a strong background in business development, strategic planning, and project management across both startups and established environments. Combining technical and leadership skills, I excel at leading cross-functional teams to deliver projects on time and identify new growth opportunities. Passionate about community building, I actively contribute to open-source projects and regularly deliver talks and hands-on sessions on Flutter and Dart.

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.

Comments (24)

Join the discussion
J

This is so cool👍

1
G

Thank you Jeevitha

1
T

Great article for beginners !

2
S

Awesome article. Found it very useful. Feel free to write over High orde functions , closure , prototype and most importantly async / await . Waiting for positive response . Thanks

2
G

Feeling great and happy to receive your comments. Also thanks for the article suggestions sure you can expect articles on the same, very soon.

2
H

Awesome content ⚡️! One can also add the following for getting floor values of POSITIVE numbers

let floorValue = ~~(3/2); //1
2
G

Great tip to add to queue ! Thanks Harsh 🙂

2
G
Gene4y ago

Which is faster between JavaScript and an ASP script?

2
G

Javascript seems to be faster than ASP Script.

2
P
Pawan4y ago

It's cool but not a big deal !!

1
G

Sure, I will try to improve the content with some more complex topics.

2
P

Post Array techniques and tips

1
G

Sure, Thank you Prithi

2
S

Good one👍

1
G

Thank you

2
K
karthik4y ago

Keep posting good content !!

3
G

Sure, Thank you

2
D
Darsh4y ago

How i get the object.values ?

1
G

You can directly get the object values using the method object.values(objectname) also check this once in console for better understanding.

2