Welcome to our comprehensive guide on JavaScript Type Conversion! Let's dive into the world of JavaScript and learn how to convert data types like a pro.
Before we delve into type conversion, let's first understand the basic data types in JavaScript:
Infinity, NaN, and undefined.true or false.Converting a number to a string is often required when we need to concatenate numbers with strings or when working with user input.
toString() methodThe toString() method converts a number into a string.
let num = 123;
let strNum = num.toString(); // "123"String() constructorAnother way to convert a number into a string is by using the String() constructor.
let num = 456;
let strNum = String(num); // "456"Converting a string to a number is essential when we perform mathematical operations on strings or when dealing with user input.
parseFloat() functionparseFloat() function converts a string into a floating-point number.
let str = "3.14159";
let num = parseFloat(str); // 3.14159parseInt() functionparseInt() function converts a string into an integer. It can optionally take a second parameter, the base of the number system, which specifies the base of the number in the string.
let str = "1011";
let num = parseInt(str); // 1011 (base 10)
let base2Num = parseInt(str, 2); // 17 (base 2)Booleans are converted to numbers in JavaScript, with true being 1 and false being 0.
let bool = true;
let num = Number(bool); // 1
let bool2 = false;
let num2 = Number(bool2); // 0JavaScript follows certain implicit type conversion rules:
true. Everything else converts to false.toString() method.Which of the following values will be converted to `false` by JavaScript?
Let's practice type conversion in a practical scenario:
let userInput = prompt("Enter a number or a word");
let number = Number(userInput);
if (Number.isNaN(number)) {
console.log(`Invalid input: ${userInput}`);
} else {
console.log(`Number: ${number}`);
}In this example, we take user input, convert it to a number, and check if it is a valid number. If it is not a number, we let the user know.
That's it for today! By understanding JavaScript type conversion, you're one step closer to mastering JavaScript. Keep practicing, and you'll soon be able to tackle complex projects with ease. 🚀