Skip to main content

Using the typeof method to detect primitive values is a great way to code defensively. Here are a few examples

var name = 'jonathan';
var count = 22;
var found = true;
var MyApp = undefined;

// detect a string
if (typeof name === "string") {
  console.log('name is a string type');
}

// detect a number
if (typeof count === "number") {
  console.log('count is a number type.');
}

// detect a boolean
if (typeof found === "boolean" && found) {
  console.log('found is boolean type.');
}

// detect undefined
if (typeof MyApp === "undefined") {
  console.log('MyApp is undefined.');
} else {
  console.log('MyApp is something else.');
}