Categories
JavaScript Tips

Useful JavaScript Tips — Casting and Internationalization

Spread the love

Like any kind of apps, JavaScript apps also have to be written well. Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Converting String to Number

The Number function can be used to convert strings to numbers.

For instance, if we write:

Number('1')

Then we get 1.

Strings are trimmed before they’re converted to numbers, so Number(“ 1 “) returns the same result.

Any empty string results in 0.

Also, Number works with decimals. So Number(“1.2”) returns 1.2.

Converting Booleans to a Number

Booleans can also be converted to numbers.

For instance, we can write:

Number(true)

then it returns 1.

If we write:

Number(false)

it returns 0.

Converting Dates to a Number

We can pass a Date instance to a number. Passing a Date instance to Number would return a UNIX timestamp.

For instance, we can write:

Number(new Date(2020, 0, 1))

and it returns 1577865600000.

Converting Special Values to Number

We can pass in special values to Number to convert it to a number.

For instance, we can write:

Number(null)

then it returns 0.

Number(undefined) returns NaN , and Number(NaN) returns NaN .

Converting to Booleans

The Boolean converts any values to a boolean.

Any falsy values will return false . Otherwise, it return true .

For instance, the following all returns false :

Boolean(false)
Boolean(0)
Boolean(NaN)
Boolean("")
Boolean(null)
Boolean(undefined)

All other values returns true .

instanceof Operator

The instanceof operator lets us check value to see if it’s an instance of a constructor,

For instance, we can write:

class Animal {}
class Dog extends Animal {}

Then the following will return true :

const dog = new Dog()
dog instanceof Animal
dog instanceof Dog

It’ll return true for a subclass instance if the right operand is the parent class or subclass.

new Operator

We can use the new operator to create a new object from a constructor.

For instance, we can write:

const date = new Date();

We can also create our own constructor and use the new operator with it:

function Dog(breed, color) {
  this.breed = breed;
  this.color= color;
}

Then we can write:

const dog = new Dog('poodle', 'white');

typeof Operator

We can use the typeof operator to check the type of a value.

For instance, we can write:

typeof 1

and we get 'number' .

typeof '1'

returns 'string' .

typeof { name: 'james' }
typeof [1, 2, 3]

return 'object' .

typeof true

returns 'boolean' .

typeof undefined

returns 'undefined' .

typeof (() => {})

returns 'function' and

typeof Symbol()

returns 'symbol' .

Internationalization

JavaScript’s standard library has its own internationalization API.

The Intl.Collator object gives us access to language-sensitive comparison features.

Intl.DateTimeFormat lets us format dates in a language-sensitive manner.

Intl.NumberFormat lets us format numbers in a language-sensitive manner.

Intl.PluralRules lets us format plurals in a language-sensitive manner.

Intl.RelativeTimeFormat lets us access language-sensitive time formatting features.

Then Intl.getcanonicalLocales lets us check if a locale is valid.

It takes a string or an array of strings.

For instance, we can write:

Intl.getCanonicalLocales('en')

or:

Intl.getCanonicalLocales(['en-us', 'en-gb'])

They both return true since they’re valid locale strings.

On the other hand, if we have:

Intl.getCanonicalLocales('en_gb')

that’ll return false since it’s not a valid locale.

Intl.Collator

The Intl.Collator is a constructor that we can pass in a locale to and then do comparisons based on that locale.

For instance, we can write:

const collator = new Intl.Collator('en-gb')
collator.compare('a', 'c')

Then we get -1, so the strings are in ascending order.

On the other hand, if we have:

collator.compare('d', 'c')

Then 1 is returned, so they are in descending order.

Intl.DateTimeFormat

The Intl.DateTimeFormat constructor lets us access language-sensitive date and time formatting features.

For instance, we can use it as follows:

const date = new Date();
const formatter = new Intl.DateTimeFormat('fr-ca');
const formatted = formatter.format(date);

In the example above, we have the Intl.DateTimeFormat constructor.

We just pass in a locale string into the constructor.

Then we call the format method to call date on it to format the date.

So formatted will be “2020–05–12” .

We can also call the formatToParts function to return an object with the formatted date parts.

For instance, we can write:

const date = new Date();
const formatter = new Intl.DateTimeFormat('fr-ca');
const parts = formatter.formatToParts(date);

Then we get:

[
  {
    "type": "year",
    "value": "2020"
  },
  {
    "type": "literal",
    "value": "-"
  },
  {
    "type": "month",
    "value": "05"
  },
  {
    "type": "literal",
    "value": "-"
  },
  {
    "type": "day",
    "value": "12"
  }
]

as the value of parts .

Conclusion

JavaScript’s standard library has many useful internationalization features.

Also, there are many functions to convert data types.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *