Type Conversion

13 0 0
                                        

1. alert - returns undefined type.

2. prompt - returns string type.

3. confirm - returns boolean type.

4. Mathematical operations automatically convert the values to numbers.

Type casting - you explicitly convert the type to another type by enclosing the value to parenthesis and prefix it with the new type.

===============

let yourPrompt = prompt("Enter a number", 100);

function doublePrompt(){

     return Number(yourPrompt) * 2;

}

===============

HTML

document.write(doublePrompt())

Result:

200

Note: If you did not change the initial value and just press ok, the Number(yourPrompt) here will convert the string 100 to a Number type. Then the result will be multiplied by 2 before it will be returned by the function.

=================

let yourAlert = alert("30"/"2");

=================

HTML

document.write(yourAlert)

Result:

undefined

Note: In the modal window, alert will convert each string to a Number and will process and will show the answer 15 but then the alert does not return the result 15 to the variable. Instead it gives an undefined type to the variable yourAlert.


You don't have to memorize the answer for type conversion. It is enough that you know that you can explicitly convert or some can implicitly convert. All you need to do is to always check the value of the variable to determine its type and value.

Number(false) = 0

String(false) = "false"

Javascript ProgrammingWhere stories live. Discover now