Bootstrap FreeKB - NodeJS - Determine Object Type
NodeJS - Determine Object Type

Updated:   |  NodeJS articles

Let's say you have a file named app.js that contains the following.

const my_string  = "Hello World";
const my_boolean = true;
const my_integer = 42;
const my_json    = '{"foo": "Hello", "bar" :"World"}';
const my_object  = JSON.parse(my_json);

console.log("my_string  =", Object.prototype.toString.call(my_string));
console.log("my_boolean =", Object.prototype.toString.call(my_boolean));
console.log("my_integer =", Object.prototype.toString.call(my_integer));
console.log("my_json    =", Object.prototype.toString.call(my_json));
console.log("my_object  =", Object.prototype.toString.call(my_object));

 

If you use the node CLI to run app.js, the following should be displayed as stdout on your console.

~]$ node app.js
my_string  = [object String]
my_boolean = [object Boolean]
my_integer = [object Number]
my_json    = [object String]
my_object  = [object Object]

 

Or like this, using typeof.

const my_string  = "Hello World";
const my_boolean = true;
const my_integer = 42;
const my_json    = '{"foo": "Hello", "bar" :"World"}';
const my_object  = JSON.parse(my_json);

console.log("my_string  =", typeof my_string);
console.log("my_boolean =", typeof my_boolean);
console.log("my_integer =", typeof my_integer);
console.log("my_json    =", typeof my_json);
console.log("my_object  =", typeof my_object);

 

Or like this, using backticks.

console.log(`my_string  = ${typeof my_string}`);
console.log(`my_boolean = ${typeof my_boolean}`);
console.log(`my_integer = ${typeof my_integer}`);
console.log(`my_json    = ${typeof my_json}`);
console.log(`my_object  = ${typeof my_object}`);

 

Which should output the following.

my_string  = string
my_boolean = boolean
my_integer = number
my_json    = string
my_object  = object

 

Here is an example of how to use this in an if else statement.

if (typeof my_string === "string") {
  console.log("my_string is a string");
} else {
  console.log("my_string is NOT a string");
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 9f563c in the box below so that we can be sure you are a human.