To check if the provided value is of the specified type in JavaScript, we have multiple approaches.
Below are the approaches used to check if the provided value is of the specified type in JavaScript:
Table of Content
Approach: Using Object.is()
Object.is() determines whether two values are the same value. Two values are the same if both are undefined, both null, both true or both false, both strings of the same length with the same characters in the same order, both the same object (meaning both values reference the same object in memory), both numbers and both +0, both -0, both NaN, or both non-zero and both not NaN and both have the same value
Key Difference Between Object.is() and === (Strict Equality)
- Object.is(+0,0) is false, Object.is(NaN,NaN) is true.
- So Object.is() is just === with different behavior for negative zero -0 and NaN.
Syntax :
Object.is(value1, value2);
Example : In this example, the Object.is() method is checking if the provided value is of the specified type.
// Evaluation result is the same as using === console.log(Object.is(25, 25)); // true
console.log(Object.is( 'foo' , 'foo' )); // true
console.log(Object.is( 'foo' , 'bar' )); // false
console.log(Object.is( null , null )); // true
console.log(Object.is(undefined, undefined)); // true
console.log(Object.is([], [])); // false
let foo = { a: 1 }; let bar = { a: 1 }; console.log(Object.is(foo, foo)); // true
console.log(Object.is(foo, bar)); // false
|
true true false true true false true false
Approach 2: Using TypeOf Operator
In JavaScript, the typeof operator returns the data type of its operand in the form of a string. The operand can be any object, function, or variable.
Syntax:
typeof operand
OR
typeof (operand)
Example: Typeof Number, in this sample, we used ‘===’ (strict equality comparison operator) which compare value and type both and then return true or false. For example- consider the first console.log(), the js starts compiling from left to right and it first calculates the type of 25 which is ‘number’, and then compares it with ‘number’ and then finally returns true or false accordingly.
//Number console.log( typeof 25 === 'number' );
console.log( typeof 3.14 === 'number' );
console.log( typeof (69) === 'number' );
// log base 10 console.log( typeof Math.LN10 === 'number' );
console.log( typeof Infinity === 'number' );
// Despite being "Not-A-Number" console.log( typeof NaN === 'number' );
// Wrapping in Number() function console.log( typeof Number( '100' ) === 'number' );
|
true true true true true true true
Note: As an ES6 feature, it may not be supported by older browsers, but it can be transpired using Babel for compatibility.