Introduction and Overview

Welcome to another exciting leap into JavaScript! Today's journey takes us through type conversions - a process that is essential when handling diverse data types in JavaScript. The objective? To understand the 'how' and 'why' of type conversions. Onward to exploration!

Unfolding the Mysteries of Type Conversion

In JavaScript, type conversion is the process of altering a value's data type. This elegant dance of transformation is beautifully illustrated below, where JavaScript converts a number into a string before performing an operation:

let star = '10'; // Starship 10
let galaxy = 5; // 5 galaxies
let universe = star + galaxy; // Concatenating a string and a number
console.log(universe);  // Outputs: '105'

This operation resulted in the string '105' instead of the anticipated number 15, demonstrating JavaScript's automatic type conversion.

The Constellations of Conversion: Implicit & Explicit

JavaScript's type conversions fall into two categories: implicit and explicit. Implicit conversion happens automatically, while explicit conversion employs built-in JavaScript methods. Observe:

let star = '10'; // Starship 10
let galaxy = 5; // 5 galaxies
let universe = Number(star) + galaxy; // Explicitly converting string '10' to number
console.log(universe);  // Outputs: 15

Here, Number() is used to convert the string star to a number, resulting in 15.

Taking Command: Explicit Type Conversion in JavaScript

JavaScript offers several methods for explicit type conversion, including Number(), String(), and Boolean(). It is prudent to identify a value's current data type before conversion, which is facilitated by the typeof operator.

Conversion between numbers and strings is as easy as pie in JavaScript with the String() and Number() functions. Observe:

let star = '10';
console.log(typeof star);  // Outputs: 'string'

let galaxy = Number(star); // galaxy now holds the numeric value 10
console.log(typeof galaxy);  // Outputs: 'number'
console.log(galaxy); // Outputs: '10'

let numStars = 1234;
console.log(typeof numStars); // Outputs: 'number'

let numStarsText = String(numStars);
console.log(typeof numStarsText); // Outputs: 'string'
console.log(numStarsText); // Outputs: '1234'
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal