Open In App

How to Check if a Variable is a MomentJS Object?

Last Updated : 20 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Variables are used to hold different types of data in JavaScript. Sometimes, we see a variable and we don't know if it is a Moment.js object or just a regular object or string. Knowing how to identify a Moment.js object can be really helpful in these situations. This is important because Moment.js objects have special methods and properties that are specific to handling dates and times.

Installing Moment.js in Node.js

We have to first install moment.js using the following command in the terminal:

npm install moment

Below are the different approaches to checking if a variable is a MomentJS object:

Using moment.isMoment() Method

The moment.isMoment() method is provided by Moment.js to check if a variable is a Moment.js object. This method is simple and directly answers whether the variable is a Moment.js object or not. It is the easiest method.

Syntax:

moment.isMoment(variable);

Example: The code checks whether the variables date and notADate are Moment.js objects, returning true for date and false for notADate.

JavaScript
// Import Moment.js
const moment = require('moment');

let date = moment();
console.log(moment.isMoment(date)); 
let notADate = "2024-08-14";
console.log(moment.isMoment(notADate)); 

Output:

var-check
Output

Using instanceof Operator

The instanceof operator is a general JavaScript operator that checks if a variable is an instance of a specific constructor or class. In the case of Moment.js, we can use it to check if the variable is an instance of the Moment.js constructor. This method is useful if we know about JavaScript object-oriented features.

Syntax:

variable instanceof moment.constructor;

Example: The code checks if date and notADate are instances of the Moment.js constructor, returning true for date and false for notADate.

JavaScript
// Import Moment.js
const moment = require('moment');

let date = moment();
console.log(date instanceof moment.constructor); 
let notADate = {};
console.log(notADate instanceof moment.constructor); 

Output:

Screenshot-2024-08-20-181801
Output

Next Article

Similar Reads