OS Authority

Tons of well written well thought and well explained programming and latest tech tutorial and videos

2 Cool JavaScript Programming Tricks


So, Welcome back Folks with another JavaScript Article. In this article, we will be discussing 2 cool javascript programming tricks that are life-saving while codding.

1-) Checking if the variable belongs to primitive or non-primitive data type

Now, first, let’s discuss primitive data types. Primitive are basics data types that are builtin available within language, like in javascript we have boolean, string, number, BigInt, null, Symbol and undefined.

Non-Primitive data types include classes, Interfaces, and Arrays. In javascript object is referred to as non-primitive data type.

Now, most of the time javascript developers need to check what type of value is stored in a variable either it is primitive or non-primitive?

consider we have a variable temp

let temp; // now either it can hold primitive or non-primitive data

we can check what type of value is stored in temp by using this simple snippet

function isPrimitive(value) {
    return Object(value) !== value;

So we used Object constructor as a wrapper. If value is non-primitive then the object constructor will give the same object and if the value is primitive then the object constructor will create a new wrapper object for the value.

!== is to check either is wrapped value and actual value are same or not if the value is primitive then it will return true and if value is non-primitive then it will return false

2-) Remove duplication from an array

So let’s say we have an array that contains duplicate values and we want to remove duplication. I will show you a simple but powerful trick to remove duplication

Consider this array

const arr =[1,2,2,2,3,4,1,2,9,3,4,5,6,4,7] // duplications

there can be multiple methods for remove duplication from an array but we can use SET to do this task.

so Set object is used to store only unique values here

const newArr = [...new Set(arr)]

Here we used Set object to store only unique values from arr. The spread operator (…) is used to spread array elements and then spread it inside a new array

Read More About The spread operator (…)

Read More The Console Object in JavaScript Explained

Leave a Comment

Your email address will not be published. Required fields are marked *

nineteen − 14 =

This div height required for enabling the sticky sidebar