JavaScript TypeOf – How to Check the Type of a Variable or Object in JS

[ad_1]

Data varieties and kind checking are elementary features of any programming language.

Many programming languages like Java have strict kind checking. This implies that if a variable is outlined with a particular kind it could include a worth of solely that kind.

JavaScript, nonetheless, is a loosely typed (or dynamically typed) language. This implies that a variable can include a worth of any kind. JavaScript code can execute like this:

let one = 1;
one = 'one';
one = true;
one = Boolean(true);
one = String('It is feasible');

With this in thoughts, it’s vital to know the kind of a variable at any given time.

The kind of a variable is set by the kind of the worth assigned to it. JavaScript has a particular operator known as typeof which helps you to get the kind of any worth.

In this text, we’ll find out how typeof is used, together with a few gotchas to be careful for.

Let’s take a fast take a look at JavaScript information varieties earlier than we dig into the typeof operator.

In JavaScript, there are seven primitive varieties. A primitive is information that’s not an object and has no strategies. They are:

  1. String
  2. Number
  3. MassiveInt
  4. Symbol
  5. Boolean
  6. undefined
  7. null

Everything else is an object – even together with array and operate. An object kind is a assortment of key-value pairs.

The typeof operator takes just one operand (a unary operator) and evaluates its kind to return the kind as a string. Here is how you utilize it if you’re evaluating the kind of a quantity, 007.

typeof 007;  // returns 'quantity'

There is different syntax for the typeof operator the place you should utilize it like a operate:

typeof(operand)

This syntax is beneficial if you need to consider an expression fairly than a single worth. Here is an instance of that:

typeof(typeof 007); // returns 'string'

In the above instance, the expression typeof 007 evaluates to the kind quantity and returns the string ‘quantity’. typeof('quantity') then outcomes in 'string'.

Let’s take a look at one other instance to perceive the significance of the parenthesis with the typeof operator.

typeof(999-3223); // returns, "number"

If you omit the parenthesis, it should return, NaN(Not a Number):

typeof 999-3223; // returns, NaN

This is as a result of, first typeof 999 will consequence in a string, “number”. The expression "number" - 32223 outcomes in NaN as occurs if you carry out a subtraction operation between a string and quantity.

Examples

The following code reveals the kind verify of varied values utilizing the typeof operator.

typeof 0;  //'quantity'
typeof +0;  //'quantity'
typeof -0;  //'quantity'
typeof Math.sqrt(2);  //'quantity'
typeof Infinity;  //'quantity'
typeof NaN;  //'quantity', even whether it is Not a Number
typeof Number('100');  //'quantity', After efficiently coerced to quantity
typeof Number('freeCodeCamp');  //'quantity', regardless of it can't be coerced to a quantity

typeof true;  //'boolean'
typeof false;  //'boolean'
typeof Boolean(0);  //'boolean'

typeof 12n;  //'bigint'

typeof '';  //'string'
typeof 'freeCodeCamp';  //'string'
typeof `freeCodeCamp is superior`;  //'string'
typeof '100';  //'string'
typeof String(100); //'string'

typeof Symbol();  //'image'
typeof Symbol('freeCodeCamp');  //'image'

typeof {weblog: 'freeCodeCamp', writer: 'Tapas A'};  //'object';
typeof ['This', 'is', 101]; //'object'
typeof new Date();  //'object'
typeof Array(4);  //'object'

typeof new Boolean(true);  //'object'; 
typeof new Number(101);  //'object'; 
typeof new String('freeCodeCamp');  //'object';
typeof new Object;  //'object'

typeof alert;  //'operate'
typeof operate () {}; //'operate'
typeof (() => {});  //'operate' - an arrow operate so, parenthesis is required
typeof Math.sqrt;  //'operate'

let a;
typeof a;  //'undefined'
typeof b;  //'undefined'
typeof undefined;  //'undefined'

typeof null;  //'object'

The desk beneath summarizes the potential return values of typeof:

Type Return worth of typeof
String 'string'
Number 'quantity'
MassiveInt 'bigint'
Symbol 'image'
Boolean 'boolean'
undefined 'undefined'
Function object 'operate'
null 'object'(see beneath!)
Any different objects 'object'

There are circumstances the place the typeof operator could not return varieties you’d count on. This could trigger confusion and errors. Here are a few circumstances.

The kind of NaN is a quantity

typeof NaN;  //'quantity', even whether it is Not a Number

The typeof NaN is 'quantity'. This is unusual, as we should not be detecting a NaN utilizing typeof. There are higher methods to cope with it. We will see them in a minute.

The kind of null is the object

  typeof null;  //'object'

In JavaScript, typeof null is an object which wrongly means that null is an object the place it’s a primitive worth.

This is definitely a bug in the language and an try was made to repair it. But it was rejected as a result of of backward compatibility points.

The kind of an undeclared variable is undefined

Before ES6, a kind verify on an undeclared variable used to consequence in 'undefined'. But this isn’t an error-safe approach to cope with it.

With ES6 we’ve got block-scoped variables declared utilizing the let or const key phrases. These will throw a ReferenceError when used with the typeof operator earlier than they’re initialized.

 typeof cat; // ReferenceError
 let cat = 'brownie'; 

The kind of a constructor operate is an object

All constructor capabilities, apart from the Function constructor, will all the time be typeof  ‘object’.

typeof new String('freeCodeCamp'); //'object'

This could lead to some confusion, as we count on it to be the precise kind (in the above instance, a string kind).

The kind of an Array is an object

Though technically appropriate, this may very well be the most disappointing one. We need to differentiate between an Array and Object even when an Array is technically an Object in JavaScript.

typeof Array(4);  //'object'

Fortunately there are methods to detect an Array accurately. We will see that quickly.

Now that we have seen some of the limitations with the typeof operator, let’s have a look at how to repair them and do higher kind checking.

How to Detect NaN

In JavaScript, NaN is a particular worth. The worth NaN represents an consequence when the consequence of an arithmetic expression can’t be represented. For instance,

let consequence = 0/0;
console.log(consequence);  // returns, NaN

Also, if we carry out any arithmetic operations that contain NaN, it should all the time consequence in a NaN.

console.log(NaN + 3); // returns, NaN

The kind checking on NaN utilizing the typeof operator does not assist a lot because it returns the kind as a 'quantity'. JavaScript has a international operate known as isNaN() to detect if a result’s NaN.

isNaN(0/0); // returns, true

But there may be a drawback right here, too.

isNaN(undefined); // returns true for 'undefined'

In ES6, the technique isNaN() is added to the international Number object. This technique is rather more dependable and so it is the most popular one.

Number.isNaN(0/0); // returns, true
Number.isNaN(undefined); // returns, false

Another fascinating side of NaN is that it’s the solely JavaScript worth that’s by no means equal to some other values together with itself. So that is one other approach to detect NaN for the environments the place ES6 isn’t supported:

operate isNaN (enter) {
  return enter !== enter;
}

How to Detect null

As we’ve got seen, detecting null utilizing the typeof operator isn’t helpful. The most popular approach to verify if one thing is null is through the use of the strict equality operator(===).

operate isNull(enter) {
 return enter === null;
}

Make positive not to use the == by mistake. Using the == in place of === will consequence in deceptive kind detection.

How to Detect an Array

From ES6 onwards, we are able to detect an array utilizing the Array.isArray technique.

Array.isArray([]); // returns true
Array.isArray({}); // returns false

Prior to ES6, we might use the instanceof operator to decide an Array:

operate isArray(enter) {
  return enter instanceof Array;
}

There is a approach we are able to create a generic resolution to kind checking. Have a take a look at the technique, Object.prototype.toString. This could be very highly effective and very helpful for writing a utility technique for kind checking.

When Object.prototype.toString is invoked on a worth utilizing name() or apply(), it returns the object kind in the format: [object Type]. The Type in the return worth is the precise kind.

Let’s see the way it works with some examples:

// returns '[object Array]'
Object.prototype.toString.name([]); 

// returns '[object Date]'
Object.prototype.toString.name(new Date()); 

// returns '[object String]'
Object.prototype.toString.name(new String('freeCodeCamp'));

// returns '[object Boolean]'
Object.prototype.toString.name(new Boolean(true));

// returns '[object Null]'
Object.prototype.toString.name(null);

So which means if we simply take the return string and take out the Type half, we may have the precise kind. Here is an try to do that:

operate kindCheck(worth) {
  const return_value = Object.prototype.toString.name(worth);
  // we are able to additionally use regex to do that...
  const kind = return_value.substring(
           return_value.indexOf(" ") + 1, 
           return_value.indexOf("]"));

  return kind.toLowerCase();
}

Now, we are able to use the kindCheck operate to detect the varieties:

kindCheck([]); // 'array'
kindCheck(new Date()); // 'date'
kindCheck(new String('freeCodeCamp')); // 'string'
kindCheck(new Boolean(true)); // 'boolean'
kindCheck(null); // 'null'

To Summarize what we have realized in this text:

  • JavaScript kind checking isn’t as strict as different programming languages.
  • Use the typeof operator for detecting varieties.
  • There are two variants of the typeof operator syntax: typeof and typeof(expression).
  • The consequence of a typeof operator could also be deceptive at instances. We want to depend on different obtainable strategies (Number.isNaN,  Array.isArry, and so forth) in these circumstances.
  • We can use Object.prototype.toString to create a generic kind detection technique.

Thank you for studying this far! Let’s join. You can @ me on Twitter (@tapasadhikary) with feedback.

You may additionally like these different articles:

That’s all for now. See you once more with my subsequent article quickly. Until then, please take excellent care of your self.



[ad_2]

Source hyperlink

Write a comment