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

DOM(Document Object Model) and BOM(Browser Object Model)

DOM(Document Object Model) The DOM is the Document Object Model, which deals with the document, the HTML elements themselves, It organize the elements of the document in tree structure (DOM tree) and in the DOM tree, all elements of the document are defined as objects (tree nodes) which have properties and methods.When a web page is loaded, the browser creates a DOM tree for all the objects (Html elements) of that page. e.g. document and all traversal you would do in it, events, etc. A Simple DOM Tree BOM(Browser Object Model) The BOM is the Browser Object Model, which deals with browser components aside from the document,like history, location, navigator and screen (as well as some others that vary by browser). The Browser Object Model (BOM) in JavaScript includes the properties and methods for JavaScript to interact with the web browser. BOM provides you with window object, for example, to show the width and height of the window. It also includes the window.scre

JavaScript type hoisting with variable function Expression

JavaScript type hoisting with variable function Expression Hoisting is JavaScript default behavior to moving declaration on the top. Variable can be used before its declaration. To understand this, first we need to understand of hoist meaning, hoist means “raise(something) by means of ropes & pulleys”. now we can relate hoisting with JavaScript. JavaScript interpreter moves all declaration on the top at runtime. It is best practice to declare all variable at the top of their respective scopes. , JavaScript is loosely syntax language so it will not throw any error at runtime if the variable used before its declaration. But JavaScript does not allow variable used before its declaration in “use strict” mode. Example 1 In this example, we can see in a normal scenario, when y has declared & then used. in this case, it will give output 10 as excepted. <p id= "demo" ></p> <script> var y; //Declare y y = 10 ;

Life cycle hook

In Angular, every component has a life-cycle, a number of different stages it goes through. Creates the component Renders the component Creates and renders the component children Checks when the component data-bound properties change, and  Destroys the component before removing it from the DOM ngOnChanges this method is called  once  on component’s creation and then  every time changes  are detected in one of the component’s  input  properties. export class MyComponent implements OnChanges { ngOnChanges(changes: SimpleChanges) { // Insert Logic Here! } }   ngOnInit Invoked when given component has been initialized. This hook is only called  once  after the first  ngOnChanges export class MyComponent implements OnInit { ngOnInit() { // Insert Logic Here! } }     ngDoCheck Invoked when the change detector of the given component is invoked. It allows us to implement our own change detection algorithm for the given component. export class MyComponent implements D