Categories
JavaScript Answers

How to Check That a Number is NaN in JavaScript?

The isNaN Function

We can use the isNaN function to check whether a number is NaN .

For instance, we can write:

const nan = isNaN(parseFloat("abc"))  
console.log(nan)

isNaN will try to parse the argument we pass into it automatically to a number.

But to be safe, we can parse it ourselves with parseFloat first to make sure we get the expected result.

We parseFloat should return NaN since we passed in a non-numeric string into it.

So isNaN should return NaN .

Therefore, nan is true .

Check Whether a Value Equals Itself

Since NaN is the only value in JavaScript which doesn’t equal itself, we can check whether a variable equals itself to check if the variable’s value is NaN .

For instance, we can write:

const nan = NaN  
console.log(nan !== nan)

Then the console log will show true since NaN doesn’t equal itself.

If nan has any other value, the console log would log false .

So if we have:

const nan = true  
console.log(nan !== nan)

Then the console log would show false .

The Number.isNaN Method

The Number.isNaN method is another method that lets us check whether a value we pass into it is NaN .

The difference between isNaN and Number.isNaN is that Number.isNaN doesn’t try to convert a value to a number before it’s checked.

For instance, we can write:

const nan = Number.isNaN('abc');  
console.log(nan)

Then console log shows false since we didn’t pass in NaN .

We just passed in something that’s not a number.

But if we write:

const nan = Number.isNaN(NaN);  
console.log(nan)

Then nan is true .

Object.is

Another method we can use to check for NaN is the Object.is method.

Object.is takes 2 arguments with the values that we want to compare.

If both values are NaN , then it returns true instead of false like we have with === .

For instance, we can write:

const a = NaN  
const nan = Object.is(a, NaN);  
console.log(nan)

Then nan is true according to the console log.

Conclusion

We can check for NaN with various functions and methods provided by JavaScript.

Also, we can use the === operator to check if a value doesn’t equal itself.

If it doesn’t, then we know the value must be NaN since NaN is the only value that doesn’t equal itself in JavaScript.

Categories
JavaScript Answers

How to Get the Number of Days Between Two Dates in JavaScript?

We often have to get the number of days between 2 dates in our JavaScript apps.

In this article, we’ll look at how to get the number of days between 2 dates with JavaScript.

Using String and Date Methods

We can calculate the number of days between 2 dates with JavaScript by using native string and date methods.

For instance, we can write:

const parseDate = (str) => {
  const [month, day, year] = str.split('/');
  return new Date(year, month - 1, day);
}

const datediff = (first, second) => {
  return Math.round((second - first) / (1000 * 60 * 60 * 24));
}

const diff = datediff(parseDate("1/1/2000"), parseDate("1/1/2001"))
console.log(diff)

We have the parseDate function that takes str date string in MM/DD/YYYY format.

We parse it by splitting the date string with '/' as the separator.

Then we get the year , month and day by destructuring.

And we pass all that into the Date constructor to return a date object.

We’ve to subtract month by 1 to get the correct JavaScript month.

Then we calculate the date difference with the dateDiff method by subtracting the second by first .

When we subtract 2 dates, both dates will be converted to timestamps automatically before subtraction.

So we can subtract them directly.

And then we divide this by 1 day in milliseconds.

Finally, we round the division result with Math.round .

Now we can call all the functions we created to parse and get the date difference from the parsed dates.

And so we get diff is 366.

moment.js

We can use moment.js to get the difference between 2 dates easily.

For instance, we can write:

const start = moment("2000-11-03");
const end = moment("2001-11-04");
const diff = end.diff(start, "days")
console.log(diff)

We just pass the date strings into the moment function.

Then we call diff to get the difference between the moment date it’s called on and the moment date object we passed in.

The 2nd argument is the unit of the difference we want to return.

So diff is also 366 since the 2 dates differ by 366 days.

Categories
JavaScript Answers

How to Get a String in YYYYMMDD Format From a JavaScript Date Object?

Using Native JavaScript Date and String Methods

One way to get a JavaScript date into a string in YYYYMMDD format is to use native JavaScript date and string methods.

For instance, we can write:

const date = new Date(2021, 1, 1)
const year = date.getFullYear()
const month = ('0' + (date.getMonth() + 1)).substr(-2)
const day = ('0' + date.getDate()).substr(-2)
const dateStr = [year, month, day].join('')
console.log(dateStr)

We create a date object with the Date constructor with the year, month, and day.

The month’s value is from 0 to 11, where 0 is for January, 1 for February, etc.

Then we can get the year, month, and day from the date.

We call getFullYear to get the 4 digit year.

And we call getMonth to get the month plus 1 to get a human-readable month.

Then we attach string 0 before it and call substr -2 to get the last 2 characters of the string.

And we call getDate to get the date and format it the same way with substr .

Finally, we join the year , month , and day together with join .

Therefore, dateStr is '20210201' .

Date.prototype.toISOString

We can call toISOString to get the date string from a JavaScript date object.

Then we can use string methods to extract the year, month, and date parts and remove the dashes from that part.

For instance, we can write:

const date = new Date(2021, 1, 1)
const dateStr = date.toISOString().slice(0, 10).replace(/-/g, "");
console.log(dateStr)

We call toISOString to get the date string in ISO8601 format.

Then we call slice with 0 and 10 to extract the first part, which has the year, month, and day.

And then we call replace to replace all the dashes with empty strings to remove them.

Therefore, we get the same result for dateStr .

Also, we can replace slice with substring :

const date = new Date(2021, 1, 1)
const dateStr = date.toISOString().substring(0, 10).replace(/-/g, "");
console.log(dateStr)

moment.js

We can also use the moment.js library to format a date easily.

For instance, we can write:

const date = new Date(2021, 1, 1)
const dateStr = moment(date).format('YYYYMMDD');
console.log(dateStr)

We pass in our date to the moment function to create a moment object withn the date.

Then we call format with the format string to format the item.

And so we get the same value for dateStr .

Conclusion

We can format a native JavaScript date into a string with native JavaScript date and string methods.

Or we can use moment.js to format a date.

Categories
JavaScript Answers

How to Format a Floating Point Number in JavaScript?

Math.round

We can use Math.round to round a number into the number of decimal places we want by multiplying the original number 10 to the power of the number of decimal places we want to round to.

Then we pass that number into Math.round , and we divide the rounded number by the same number we multiplied the original number with.

For instance, we can write:

const original = 123.456
const result = Math.round(original * 100) / 100;
console.log(result)

We multiply original by 100, which is 10 to the power of 2.

So we round to 2 decimal places.

And we divide by 100.

Then result is 123.46.

This also works if we also round to other numbers of decimal places.

For instance, we can write:

const original = 123.45678
const result = Math.round(original * 1000) / 1000;
console.log(result)

And result is 123.457.

Number.prototype.toFixed

We can call the toFixed method to return a string with the number rounded to the given number of decimal places.

For instance, we can write:

const original = 123.45678
const result = original.toFixed(3)
console.log(result)

Then result is ‘123.457’ .

3 is the number of decimal places to round to.

result is a string instead of number in the previous example.

This is the easier way to format a number to the number of decimal places we want.

Categories
JavaScript Answers

How to Check if a JavaScript String Contains a Substring in a Case Insensitive Manner?

String.prototype.toLowerCase and String.prototype.indexOf

We can convert both the string and the substring we’re checking for the lower case to check if a substring is in a JavaScript string is in a case-insensitive manner.

For instance, we can write:

const includes = 'ABCDE'.toLowerCase().indexOf("abc".toLowerCase()) !== -1  
console.log(includes)

We call toLowerCase on 'ABCDE' and 'abc' to convert them both to lower case.

And then we call indexOf to check if “abc”.toLowerCase() to if included in 'ABCDE' in a case-insensitive manner.

Since 'abc' is in 'ABCDE' when they’re compared in a case-insensitive manner, indexOf should return an index other than -1.

And so includes is true .

Case-Insensitive Regex Search

We can also do a case-insensitive regex search in our code.

For instance, we can write:

const includes = /abc/i.test('ABCDE')  
console.log(includes)

The i flag lets us search for a pattern in the string we pass into test in a case-insensitive manner.

And so includes is also true in this example.

Case-Insensitive Regex Search with RegExp Constructor

Alternatively, we can do a case-insensitive regex search with the RegExp constructor.

For instance, we can write:

const includes = new RegExp("abc", "i").test('ABCDE')  
console.log(includes)

to do the same as we did before.

String.prototype.toLowerCase and String.prototype.includes

We can also substitute the indexOf method in the first example with includes .

Using the includes method, we don’t have to compare against -1.

Instead, we get true if the substring is included in a string and false otherwise.

So we can write:

const included = 'ABCDE'.toLowerCase().includes("abc".toLowerCase())  
console.log(included)

We convert them both the string and substring to lower case as usual, but we use includes to check if the substring we pass into includes is included in 'ABCDE' .

And so we should get the same result as before.

String.prototype.toLocaleLowerCase and String.prototype.includes

If we’re checking a JavaScript substring with a string that has text other than English, we may want to use the toLocaleLowerCase method since it works with non-English locales.

For instance, we can write:

const included = 'ABCDE'.toLocaleLowerCase().includes("abc".toLocaleLowerCase())  
console.log(included)

And we get the same result as before.