Javascript Tips and Tricks

Image for post
Image for post
Photo by Artem Sapegin on Unsplash

JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm. Javascript is being used by millions of developers out there in both Server Side and Client Side Programming. Today, I’m going to share a set of JavaScript tips, tricks and best practices that should be known by all JavaScript developers.

1. Array with distinct elements

We all may reach a point in our day-to-day code level where we have a combined array of all the identifiers and may need to have an array, as a result, with unique identifiers. ES6 introduced the Set object to make our job easier.

const arrayWithUniqueItems = […new Set([1, 2, 3, 3, 4, 5, 5, 6])]

2. Know when to use === and ==

Double equals(==) is named as Equality Operator and Triple equals(===) is named as Identity / Strict equality Operator.
Double equals first convert the operands into the same type and then compare i.e comparison would perform once both the operands are of the same type. On the other hand, triple equals do not perform any type of conversion before comparison and return true only if type and value of both operands are exactly the same.

console.log (true == 1); //true
console.log (true === 1); //false

3. Decrease length of your if statement

Decreasing the length of your simple if statement can provide easy code readability & simplicity.

// Instead of using this
if (true) {
console.log(true);
}

// You can use this
if(true) console.log(true);

// Or this
true? console.log(true) : 0

4. Check for an empty array or an empty object

One most common mistake that you can make is to check for an empty array or an empty object with a simple if condition.

if([]) console.log(true); // true
if({}) console.log(true); // true

An empty array or an empty object still gives a true condition when treated in a simple if condition because of the length. The array/object may be empty but we can calculate their length. It doesn’t matter if their length is 0.

The correct way to find if the object is empty is to find if it has any key or not and the correct way to find if the array is empty is to find it’s length and compare it to zero(0).

Object.keys(obj).length == 0; // true
array.length == 0; // true

5. Avoid confusing between slice(), splice(), and split()

Javascript in-built methods are to help us code faster and not to confuse us but we all need to accept that we do get confused between these three methods sometimes.

The slice() method copies a given part of an array(from the given index and until the given index) and returns that copied part as a new array. It doesn’t change the original array.

let array = [1,2,3];
console.log(array.slice(0,1)); // [1]

The splice( ) method changes the original array by adding or removing elements from it.
In case of removal, array.splice(from, number of elements);
In case of addition, array.splice(from, number of elements, element, element);

let array = [1,2,3,4,5];
array.splice(0,1); // from 0, 1 element has to be removed. [1] removed.
console.log(array); // [2,3,4,5]
array.splice(2); /* if number of elements is not provided, the method removes all elements after the given index */
console.log(array); // [2,3]

array.splice(0,0, 7,8,9); //addition of 7,8,9 at index 0
console.log(array); // [7, 8, 9, 2, 3]

The split(separator, limit) method is used for strings. It divides a string into substrings and returns them as an array. It takes 2 parameters, and both are optional. Separator serves as the character by which the string will be split. It can be ‘,’ ‘@’ ‘.’ etc. Limit limits the number of splits with a given number.

let myString = “hello,my,name,is,deepika,wadhera”;
let newArray = myString.split(“,”, 3); // separator is , and limit is 3
console.log(newArray); // [“hello”, “my”, “name”]

6. Difference between shift and pop

The shift() method removes the element at the 0th index and shifts the values at consecutive indexes down.
The pop() method removes the last element from an array.

let names1 = [‘shahid’, ‘aditya’, ‘ranveer’, ‘kunal’];
let names2 = [‘shahid’, ‘aditya’, ‘ranveer’, ‘kunal’];
names1.pop();
names2.shift();

console.log(names1); // [‘shahid’, ‘aditya’, ‘ranveer’];
console.log(names2); // [‘aditya’, ‘ranveer’, ‘kunal’]

7. Don’t use delete to remove an item from the array

Using delete replaces the item with undefined instead of the removing it from the array and trust me, you don’t want that.

let array = [1,2,3,4,5];
delete array[3];
console.log(array); // [1, 2, 3, undefined, 5]

8. Combine objects

The easiest way to combine objects is by using Spread operator (…)

let obj = {a:1};
let obj2 = {b:2};
let obj3 = {…obj, …obj2};
console.log(obj3); // {a: 1, b: 2}

9. switch vs nested ifs

When there’s a huge number of cases or choices, a switch statement is easily the choice to go with over the if-else statement. Switch also makes your code easy to read and use.

int value = // some value
if (value == 1) {
doThis();
} else if (value == 2) {
doThat();
} else {
doTheOther();
}

switch(value) {
case 1: doThis();
break;
case 2: doThat();
break;
default: doTheOther();
}

Never forget the break statement in switch and save yourself from making a blunder.

10. Difference between null and undefined

Null means an empty or non-existent value. Null is assigned, and explicitly means nothing. null is also an object. Interestingly, this was actually an error in the original JavaScript implementation:

var test1 = null;
console.log(typeof test1); // object

Undefined means a variable has been declared, but the value of that variable has not yet been defined. Unlike null, undefined is of the type undefined:

var test2;
console.log(test2); // undefined
console.log(typeof test2); // undefined

Thank you for reading!

Do give a clap if you liked these tips. Happy Coding!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store