HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

A complete guide to JavaScript typechecking

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascripttypecheckingguidecomplete

Problem

JavaScript's dynamic typing is one of its most powerful features. Nonetheless, it's often the source of issues and confusion, especially for inexperienced developers. Thus, typechecking is a crucial skill for any JavaScript developer.
Before we dive into the different ways to typecheck values in JavaScript, let's take a look at the different types of values we can encounter in JavaScript.
| Type | Description | Example |
| ---- | ----------- | ------- |
| undefined | The value of a variable that has not been assigned a value. | let x; |

Solution

const isUndefined = val => val === undefined;

isUndefined(undefined); // true


| Type | Description | Example |
| ---- | ----------- | ------- |
| undefined | The value of a variable that has not been assigned a value. | let x; |
| null | The intentional absence of any object value. | const x = null; |
| boolean | A logical value, either true or false. | const x = true; |
| number | A numeric value. | const x = 50; |

Code Snippets

const isUndefined = val => val === undefined;

isUndefined(undefined); // true
const isNull = val => val === null;

isNull(null); // true
const isNil = val => val === undefined || val === null;

isNil(null); // true
isNil(undefined); // true
isNil(''); // false

Context

From 30-seconds-of-code: complete-guide-to-js-type-checking

Revisions (0)

No revisions yet.