DEV Community

Brendon O'Neill
Brendon O'Neill

Posted on

Handling types in JavaScript

Introduction

Whenever I'm not sure what a user input is, I normally have to check to see its type to figure out how to deal with the information. Most of the time, people will say to use TypeScript, but when I work on personal projects or solo projects, I would rather not deal with TypeScript's added bloat of syntax. So today is a quick post on how I handle each type in JavaScript.

Basics

When you want to check basic values like strings, numbers, bigints, booleans, undefined and symbols, it is as easy as just using the typeof operator. As they are primitive types, they have their own set value and are easy as just checking their type.

console.log(typeof "Hello World");    // string
console.log(typeof 100);              // number
console.log(typeof 42n);              // bigint
console.log(typeof true);             // boolean
console.log(typeof undefined);        // undefined
console.log(typeof Symbol("id"));     // symbol

Enter fullscreen mode Exit fullscreen mode

And with these values, if it's not the value you need, you can parse it to the value that suits your needs using one of these parsers.

For strings, I use String() to parse data. You can use toString(), but values like null and undefined don't have a toString() method and would crash your programme with a type error.

TypeError: Cannot read properties of null (reading 'toString')
TypeError: Cannot read properties of undefined (reading 'toString')
Enter fullscreen mode Exit fullscreen mode

Example:

// String

function convertToString(value){
  if(typeof value !== 'string')
  {
    let returnValue = String(value);
    return returnValue;
  }

  return value;
}

console.log(convertToString("Hello"));       // "Hello"
console.log(convertToString(145));           // "145"
console.log(convertToString(12n));           // "12"
console.log(convertToString(true));          // "true"
console.log(convertToString(null));          // "null"
console.log(convertToString(undefined));     // "undefined"
console.log(convertToString(Symbol("id")));  // "Symbol(id)"
Enter fullscreen mode Exit fullscreen mode

For numbers, I use the parser Number() as it has good performance and it is similar to the String() parser, keeping a clean pattern to my code. The only downside is that you can't parse Symbol to a number, but I have never had to do this before.

Example:

function convertToNumber(value){
  if(typeof value !== 'number')
  {
    let returnValue = Number(value);
    return returnValue;
  }

  return value;

}

console.log(convertToNumber("Hello"));   // NaN
console.log(convertToNumber(145));       // 145
console.log(convertToNumber(12n));       // 12
console.log(convertToNumber(true));      // 1
console.log(convertToNumber(null));      // 0
console.log(convertToNumber(undefined)); // NaN
Enter fullscreen mode Exit fullscreen mode

As you can see, we got back two NaN (Not a Number). This happens when a parser wasn't able to parse the value as a number. We can also check if a value is NaN using the Number.isNaN() method.

Example:

Number.isNaN(NaN);       // true
Number.isNaN("hello");   // false
Number.isNaN(undefined); // false
Number.isNaN(123);       // false
Enter fullscreen mode Exit fullscreen mode

For BigInt, we can use the BigInt() function, but it can't be used on strings, nulls, or undefineds, as we will get type errors as they can not be parsed to BigInts.

Example:

BigInt(123);     // 123n
BigInt(12n);   // 12n
BigInt(true);    // 1n
Enter fullscreen mode Exit fullscreen mode

Just like string and number, boolean also has a function Boolean() that parses values to booleans.

Example:

function convertToBoolean(value){
  if(typeof value !== 'boolean')
  {
    let returnValue = Boolean(value)
    console.log(typeof returnValue)
    return returnValue;
  }

  return value;

}

console.log(convertToBoolean("Hello"));    // true
console.log(convertToBoolean(145));        // true
console.log(convertToBoolean(0));          // false
console.log(convertToBoolean(12n));        // true
console.log(convertToBoolean(true));       // true
console.log(convertToBoolean(null));       // false
console.log(convertToBoolean(undefined));  // false
Enter fullscreen mode Exit fullscreen mode

Complex Values

When we deal with non-primitive type values and nulls, we can't really use the typeof operator, as everything comes back as objects.

Example:

console.log( typeof null);        // object
console.log( typeof [1,2,3]);     // object
console.log( typeof {});          // object
console.log( typeof new Date());  // object
Enter fullscreen mode Exit fullscreen mode

This could be bad if we are looking for an object, and the user sends us an array value, it will take that as an object. So let's fix this.

When working with nulls, it is best to check if a value is equal to null, as this will catch all null values. If you use three equals it will check for nulls, but if you want to check for null or undefined, you can use two equals.

Example:

function checkObject(value){
  if(value === null)
  {
     return 'I am a null';    
  }
  if(typeof value === 'object')
  {
    return value;
  }

  return 'not an object';

}

console.log( checkObject(null));  // I am a null
console.log( checkObject({}));    // {}
console.log( checkObject([]));    // []

Enter fullscreen mode Exit fullscreen mode

Arrays are another one that returns as an object. To check if the value is an array, we can use the method Array.isArray() to check if the value returned is true to confirm it is an array.

Example:

console.log(Array.isArray([]));    // true
console.log(Array.isArray({}));    // false
console.log(Array.isArray(null));  // false
Enter fullscreen mode Exit fullscreen mode

This last method is used to check for objects, but can also be used to check for all types. Object.prototype.toString.call(yourValue) forces JavaScript to use the original toString() from Object.prototype, giving a reliable string that reveals the internal classification of the value.

Example:


function getType(value){
  return (
    console.log(Object.prototype.toString.call(value));
  );
}

getType({});            // [object, Object]
getType([]);            // [object, Array]
getType(123);           // [object, Number]
getType("hello");       // [object, String]
getType(Symbol("id"));  // [object, Symbol]
getType(null);          // [object, Null]
getType(undefined);     // [object, Undefined]
getType(() => {});      // [object, Function]
getType(new Date());    // [object, Date]
getType(/abc/);         // [object RegExp]

Enter fullscreen mode Exit fullscreen mode

Also, if you want it without the [object, value].

Example:


function getType(value){
  return (
    console.log(Object.prototype.toString.call(value).slice(8, -1));
  );
}

getType({});            // Object
getType([]);            // Array
getType(123);           // Number
getType("hello");       // String
getType(Symbol("id"));  // Symbol
getType(null);          // Null
getType(undefined);     // Undefined
getType(() => {});      // Function
getType(new Date());    // Date
getType(/abc/);         // RegExp

Enter fullscreen mode Exit fullscreen mode

Yes, it's a bit hacky, but it gets the job done.

This was just a quick one to help check types in JavaScript and I hope it was helpful.

Top comments (0)