Some cool and awesome JavaScript tricks
An article from www.knowledgescoops.com
In this article, we will cover some of the cool and awesome JavaScript tricks which you may find useful at some point while coding in JavaScript.
Trick 1
Identifying if a variable is of primitive or non-primitive data type
There are primitive and non-primitive data types in Javascript. The primitive types include boolean, string, number, BigInt, null, Symbol and undefined. The non-primitive types include the Objects.
Often we might need to identify what type of value is stored in a variable — Primitive or Non-Primitive?
Consider a variable var
var val; // contains either primitive or non-primitive value
This can be achieved with the help of a simple code snippet.
function isPrimitive(val) {
return Object(val) !== val;
}
We are using the Object constructor to create a wrapper object for a value.
If the value is a primitive data type, the Object constructor creates a new wrapper object for the value.
If the value is a non-primitive data type (an object), the Object constructor will give the same object.
Hence, a strict check (!== or ===) can help us identifying if a variable is of primitive or non-primitive type.
Trick 2
Creating a pure object in Javascript
Before creating a pure object, let’s understand “What is a pure object?”
A pure object in JavaScript means that it should not have any functions in its prototype.
An object is created with the following syntax.
var obj = {};
Upon checking the obj.__proto__ we get many functions available inside it.
What if we want to create an object that does not have any of the prototype functions inside it?
We can achieve this by using the Object constructor’s create method.
var obj = Object.create(null);
Upon checking the object’s prototype, we get the following result
An object with no prototype.
Hence, a pure object is created.
Trick 3
Removing duplicates from an array
Consider the following array
var arr = [1, 2, 3, 3, 4, 5, 6, 6, 7, 7, 7, 7];
We can see many duplicate elements in the array. To remove the duplicate elements from the array, we can use a Set.
A Set object lets us store unique values only. A set cannot have a duplicate value in it. Read more about it in the MDN Web Docs.
To remove duplicates from the array, we write the code
const newArr = [...new Set(arr)];
Here we created a new Set containing only the unique values of an array, then spread it inside a new array.
The … is the Spread operator. Read more about it in the MDN Web Docs
As a result, we get an array with only unique values.
Loved the article? SUPPORT MY WRITING…
Patreon — https://www.patreon.com/kunaltandon
Paypal — https://www.paypal.com/paypalme2/kunaltandon94
For more such articles, visit www.knowledgescoops.com
Want to read more articles like this?
Follow me on medium @kunaltandon.ktConnect with me on LinkedIn:
https://www.linkedin.com/in/kunal-tandon/