Menu
Coddy logo textTech

Type Conversion - Part 2

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 31 of 77.

Boolean Conversion

// Converting to Boolean
console.log(Boolean(1));      // Outputs: true
console.log(Boolean(0));      // Outputs: false
console.log(Boolean(""));     // Outputs: false
console.log(Boolean("hello")); // Outputs: true

String Conversion

// Converting to String
let num = 42;
let bool = true;
let str1 = String(num);   // Converts number to string
let str2 = String(bool);  // Converts boolean to string

console.log(str1);  // Outputs: "42"
console.log(str2);  // Outputs: "true"
challenge icon

Challenge

Easy

In this challenge, you'll practice converting between different data types in JavaScript, focusing on Boolean and String conversions.

You are given several variables with different values. Your task is to replace each null placeholder in the starter code with the correct conversion call:

  1. Convert the string '42' to a boolean using Boolean()
  2. Convert the number 0 to a boolean using Boolean()
  3. Convert the number 7 to a boolean using Boolean()
  4. Convert the empty string '' to a boolean using Boolean()
  5. Convert the boolean true to a string using String()
  6. Convert the number 123 to a string using String()

For example, to convert stringValue to a boolean, replace null with Boolean(stringValue) so the line reads:
console.log("Boolean('42'): ", Boolean(stringValue));

Each null is simply a placeholder — it is not a concept you need to learn. Your job is to replace every null with the appropriate conversion call using the variable provided.

Cheat sheet

Use Boolean() to convert values to boolean:

Boolean(1);        // true
Boolean(0);        // false
Boolean("");       // false
Boolean("hello");  // true

Use String() to convert values to string:

String(42);    // "42"
String(true);  // "true"

Try it yourself

// Values to convert
const stringValue = '42';
const zeroNumber = 0;
const positiveNumber = 7;
const emptyString = '';
const boolValue = true;
const numValue = 123;

// TODO: Replace null with the correct Boolean() conversion of stringValue
console.log("Boolean('42'): ", null);

// TODO: Replace null with the correct Boolean() conversion of zeroNumber
console.log("Boolean(0): ", null);

// TODO: Replace null with the correct Boolean() conversion of positiveNumber
console.log("Boolean(7): ", null);

// TODO: Replace null with the correct Boolean() conversion of emptyString
console.log("Boolean(''): ", null);

// TODO: Replace null with the correct String() conversion of boolValue
console.log("String(true): ", null);

// TODO: Replace null with the correct String() conversion of numValue
console.log("String(123): ", null);
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals