Skip to main content

JavaScript | Type Conversion

 JavaScript | Type Conversion

JavaScript is loosely typed language and most of the time operators automatically convert a value to the right type but there are also cases when we need to explicitly do type conversions.
While JavaScript provides numerous ways to convert data from one type to another but there are two most common data conversions :

  • Implicit Conversion
  • explicit conversion

  • Implicit Conversion

When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a "right" type. This is known as implicit conversion.it is call Automatic type conversion


Example 1: Implicit Conversion to String
    // numeric string used with + gives string type
    let sum;

    sum = '3' + 2;
    console.log(sum) // "32"

    sum = '3' + true;
    console.log(sum); // "3true"

    sum = '3' + undefined;
    console.log(sum); // "3undefined"

    sum = '3' + null;
    console.log(sum); // "3null"

Note: When a number is added to a string, JavaScript converts the number to a string before concatenation.

Example 2: Implicit Conversion to Number
    // numeric string used with +, - , / , * results number type

    let result;

    result= '4' - '2';
    console.log(result); // 2

    result = '4' - 2;    console.log(result); // 2

    result = '4' * 2;
    console.log(result); // 8

    result = '4' / 2;
    console.log(result); // 2

Example 3: Non-numeric string results NaN
    // non-numeric string used with +, - , / , * results to NaN

    let result;

    result = 'hello' - 'world';
    console.log(result); // NaN

    result = '4' - 'hello';
    console.log(result); // NaN

Example 4: Implicit Boolean Conversion to Number
    // if boolean is used, true is 1, false is 0

    let result;

    result = '3' - true;
    console.log(result); // 3

    result = 5 + true;
    console.log(result); // 6

    result = 3 + false;
    console.log(result); // 3

Note: JavaScript considers 0 as false and all non-zero number as true. And, if true is converted to a number, the result is always 1.


Example 5: null Conversion to Number
    // null is 0 when used with a number
    let result;

    result = 4 + null;
    console.log(result); // 4

    result = 4 - null;
    console.log(result); // 4

Example 6: undefined used with number, boolean or null

    // Arithmetic operation of undefined with a number, boolean or null gives NaN

    let result;

    result = 4 + undefined;
    console.log(result); // NaN

    result = 4 - undefined;
    console.log(result); // NaN

    result = true + undefined;
    console.log(result); // NaN

    result = null + undefined;
    console.log(result); // NaN


 Explicit Conversion

we can also convert one data type to another as per our needs. The type conversion that we do manually is known as explicit type conversion. In JavaScript, explicit type conversions are done using the built-in methods.
String()Number()Boolean(), and Object() functions can be used to convert data from one type to another

1. Convert to Number Explicitly

To convert numeric strings and boolean values to numbers, you can use Number(). For example,

let result;

// string to number
result = Number('314');
console.log(result); // 314

// boolean to number
result = Number(true);
console.log(result); // 1

result = Number(false);
console.log(result); // 0

In JavaScript, empty strings and null values return 0. For example,

let result;
result = Number(null);
console.log(result);  // 0

let result = Number(' ')
console.log(result);  // 0

If a string is an invalid number, the result will be NaN. For example,
let result;
result = Number('hello');
console.log(result); // NaN

result = Number(undefined);
console.log(result); // NaN

result = Number(NaN);
console.log(result); // NaN


2. Convert to String Explicitly

To convert other data types to strings, you can use either String() or toString(). For example,

//number to string
let result;
result = String(212);
console.log(result);  // "212"

result = String(2 + 6);
console.log(result); // "8"

//other data types to string
result = String(null);
console.log(result); // "null"

result = String(undefined);
console.log(result); // "undefined"

result = String(NaN);
console.log(result); // "NaN"

result = String(true);
console.log(result); // "true"

result = String(false);
console.log(result); // "false"

// using toString()
result = (324).toString();
console.log(result); // "324"

result = true.toString();
console.log(result); // "true"


3. Convert to Boolean Explicitly

To convert other data types to a boolean, you can use Boolean().

In JavaScript, undefinednull0NaN'' converts to false. For example,

let result;
result = Boolean('');
console.log(result); // false

result = Boolean(0);
console.log(result); // false

result = Boolean(undefined);
console.log(result); // false

result = Boolean(null);
console.log(result); // false

result = Boolean(NaN);
console.log(result); // false

All other values give true. For example,

result = Boolean(324);
console.log(result); // true

result = Boolean('hello');
console.log(result); // true

result = Boolean(' ');
console.log(result); // true

Comments

Popular

HTML Basic

HTML (Hypertext Markup Language) Basic What is HTML ? HTML invented by Tim Berners-Lee in 1990. HTML stands for hypertext markup language. Web browsers receive HTML documents from a web server or from local storage and render the documents into multimedia web pages .We can create web page with different elements like audio, video, image, tables, link, list & text etc, with CSS & JavaScript. version of HTML There are 6 version of HTML HTML Version Year HTML 1991 HTML 2.0 1995 HTML 3.2 1997 HTML 4.01 1999 XHTML 2000 HTML 5 2014 (Latest version) Latest version of HTML Latest version of html is HTML 5.0 , in latest version of html provided new tags for multimedia support. Now we are creating web page  index.html  How we can create Web page <!DOCTYPE html> < html > < head > < title > This is my First Web Page </ title > </ head > < body > < h1 > My First heading ...

Building Block of Angular

The main building blocks for Angular are modules, components, templates, metadata, data binding, directives, services, and dependency injection. Below mentioned are the main building blocks of an Angular application: - Modules  group components logically within the project. Angular basically is a modular framework where every block of functionality is encapsulated within a module and exposed outside within the project as a service. There are two types of modules one is encapsulating block of function within a single component and the other is encapsulating block of function within single or group of components by providing exposure in a unified manner via an interface. Components  help in controlling UI block and also it provides data and logic. It represents a unique "View" and "View Model" in MVVM pattern or exactly like what Controllers do in Angular 1. The "V...

this keyword in javascript

Welcome file this keyword is used to point at the current object in the code. For instance: If the code is presently at an object created by the help of the ‘new’ keyword, then ‘this’ keyword will point to the object being created. It has different values depending on where it is used: In a method, this refers to the owner object . Alone, this refers to the global object . In strict mode this refer to the global object . In a function, this refers to the global object . In a function, in strict mode, this is undefined . In an object method , this refers to the current object. In the example, this refers to the employee object. this Alone when this keyword is used alone, not written inside a function or object then it will refer to global object. & In browser window global object will be [object window] In a browser window the Global object is [object Window] : var x = this; this in a Function (Default) ...