Converting Data Types in JavaScript..30daysofjavascript ==>Day10

Olajide Blessing Niniola
3 min readMar 29, 2021

In JavaScript and most of the time, values are being converted to their right type in operations and functions. But sometimes there is a need to explicitly convert a value to the expected type. First, let’s talk about data types, I know we are already familiar with this but let us have a recap.

In JavaScript there are 5 different data types that can contain values:

  • string
  • number
  • boolean
  • object
  • function

There are 6 types of objects:

  • Object
  • Date
  • Array
  • String
  • Number
  • Boolean

And 2 data types that cannot contain values:

  • null
  • undefined

The typeof Operator

The typeof operator to find the data type of a JavaScript variable. You might wonder what kind of data type is typeof, the typeof operator is not a variable rather it is an operator. Operators ( + — * / ) do not have any data type. But, the typeof operator always returns a string (containing the type of the operand).

typeof operation

NB : typeof cannot be used to determine if a JavaScript object is an array (or a date).

Now back to type conversion,

String Conversions

Numbers, booleans and even dates can be converted to string using the global String() method or object toString() method.

string conversion

Number Conversions

The global method Number() can convert strings to numbers. Strings containing numbers (like “1.25”) convert to numbers (like 1.25). Empty strings automatically convert to 0 and anything else converts to NaN (Not a Number). True and false is converted to 1 and 0.

Number conversion

Boolean Conversion

Boolean conversion is quite simple, empty values such as empty string, 0, NaN, undefined and null gives the result false while other values give the result true. This conversion is performed using the global method Boolean().

Boolean conversion

Below is a JavaScript Type Conversion Table. Please note that values in quotes indicate string values and red values indicate values (some) programmers might not expect.

Type Conversion full list. Source: w3schools

What is this about?

30daysofjavascript is a series of writing on how I learn to code in JavaScript. These episodes are as simplified as possible and for beginners like me, I hope you find JavaScript less confusing throughout this episode. Thank you as always see you in the next episode.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response