Is JavaScript a Typed Language?

Is JavaScript a Typed Language?

Ferenc Almasi β€’ Last updated 2020 November 01 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

JavaScript is weakly typed in its nature. This enables us to use implicit type conversion. Take the following for example:

Copied to clipboard! Playground
// This will return "12" as 1 will be converted into a string
1 + "2"
typeof (1 + "2") // Will return "string"

// This will return 12 as "12" will be converted into a number
"12" * 1
typeof ("12" * 1) // Will return "number"
type-conversion.js

Even though we did not specify we wanted to convert the string/number into the other format, JavaScript did it for us implicitly. This is type conversion in action.

So how do you convert different types?

Number

To convert string or any other value to number, use the built-in Number function:

Copied to clipboard!
// Converting data to number
Number('123');
Number(true)  // Returns NaN
number.js

Alternatively, you can also use parseInt(), but always make sure you pass the radix as a second parameter. Otherwise, you may happen to get unexpected results. You can also check if something is a number using isInteger:

Copied to clipboard!
Number.isInteger('123'); // returns false
Number.isInteger(123)    // returns true
isNumber.js

String

To convert data into a string, use the built-in String function:

Copied to clipboard!
String('123'); // returns "123"
String(true);  // returns "true"
String(NaN);   // returns "NaN"
string.js

Boolean

Lastly, if you want to conver something into a boolean, use the built-in Boolean function.

Copied to clipboard! Playground
Boolean(0);     // returns false
Boolean('');    // returns false
Boolean(NaN);   // returns false

Boolean(1);     // returns true
Boolean(123);   // returns true
Boolean('true') // returns true
boolean.js

You can also simply double negate a variable to get it converted into a true / false value:

Copied to clipboard!
!!0   // returns false
!!1   // returns true
!!NaN // returns false
double-negate.js

In summary, you can use these three built in methods to convert different types of data:

  • Number()
  • String()
  • Boolean()
Types in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.