Data Types and Num Type Conversion


Data Types and Num Type Conversion

 In JavaScript, there are several data types, including:


Number - used to represent numeric values

String - used to represent text values

Boolean - used to represent true/false values

Null - used to represent the intentional absence of any object value

Undefined - used to represent the absence of a defined value

Object - used to represent a collection of related data and functionality

Symbol - used to represent a unique identifier


Type Conversions

To convert one data type to another, you can use type conversion. In JavaScript, there are two types of type conversion: explicit and implicit.


Explicit type conversion involves converting a value from one type to another using built-in functions. Here are some examples:


Number to String: String(42)

String to Number: Number("42")

Boolean to String: String(true)

String to Boolean: Boolean("true")

Implicit type conversion, also known as type coercion, happens automatically when JavaScript expects a certain data type but receives a different one. For example:


Adding a number and a string: 5 + "5" will result in the string "55"

Comparing a number and a string: 5 == "5" will return true.


Example

<!DOCTYPE html>

<html>

  <head>

    <meta charset="UTF-8">

    <title>Data Types and Type Conversion</title>

  </head>

  <body>

    <p>Open the console to see the output</p>

    <script>

      // Define variables with different data types

      let num = 42;

      let str = "hello";

      let bool = true;

      let obj = { name: "John", age: 30 };

      let sym = Symbol("id");


      // Use console.log to print the variables and their types

      console.log(num, typeof num);

      console.log(str, typeof str);

      console.log(bool, typeof bool);

      console.log(obj, typeof obj);

      console.log(sym, typeof sym);


      // Use explicit type conversion to convert data types

      let numStr = String(num);

      let strNum = Number(str);

      let boolStr = String(bool);

      let strBool = Boolean(str);

      console.log(numStr, typeof numStr);

      console.log(strNum, typeof strNum);

      console.log(boolStr, typeof boolStr);

      console.log(strBool, typeof strBool);


      // Use implicit type conversion to concatenate a number and a string

      let result = num + str;

      console.log(result, typeof result);


      // Use strict equality to compare a number and a string

      console.log(num === str);

    </script>

  </body>

</html>


Post a Comment

Previous Post Next Post