Wednesday, December 21, 2016

Javascript-6-typeOf / Type Conversions

    Before we start off on Type operators, we need to know the dataTypes in javascript. 

JavaScript Data Types :

    In JavaScript there are 5 different data types that can contain values:
    There are 3 types of objects:
  • And 2 data types that cannot contain values:
    • null
    • undefined

NOTE: Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.

--------------------------------------------------

Type operators  (typeof   instanceof )

  • typeofReturns the datatype of a variable. Example :
Notes:
typeof "John"                 // Returns "string" 
typeof 3.14                   // Returns "number"
typeof NaN                    // Returns "number"
typeof false                  // Returns "boolean"
typeof [1,2,3,4]              // Returns "object"
typeof {name:'John', age:34 // Returns "object"
typeof new Date()             // Returns "object"
typeof function () {}         // Returns "function"
typeof myCar                  // Returns "undefined" *
typeof null                   // Returns "object"


2)
<html>
<body>
<p>The typeof operator returns the type of a variable or expression.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    var y = "5";
    var x = + y;
    document.getElementById("demo").innerHTML =
    typeof y + "<br>" + typeof x;
}
</script>
</body>
</html>

O/P: 
string
number

--------------------------------------------------

The constructor property returns the constructor function for all JavaScript variables.

Example:

1)
"John".constructor// Returns "function String(){[native code]}"
(3.14).constructor// Returns "function Number(){[native code]}"
false.constructor// Returns "function Boolean(){[native code]}"
[1,2,3,4].constructor// Returns "function Array(){[native code]}"
{name:'John', age:34}.constructor//Returns"function Object(){[native code]}"
new Date().constructor//Returns "function Date(){[native code]}"
function(){}.constructor//Returns "function Function(){[native code]}"

2) 
Custom functions to check if the object returned is an Array or Date Object:


<html>

<body>

<p>This "home made" function, when used on an array, returns true.</p>

Check if fruits is an array?<p id="demo"></p>

-------------------------------------</br>

Check if new Date() is a Date?<p id="demo2"></p>

<script>

var fruits = ["Banana", "Orange", "Apple", "Mango"];

document.getElementById("demo").innerHTML = isArray(fruits);

function isArray(x) {

    return x.constructor.toString().indexOf("Array") > -1;

}



var myDate = new Date();

document.getElementById("demo2").innerHTML = isDate(myDate);

function isDate(myDate) {

    return myDate.constructor.toString().indexOf("Date") > -1;

}

</script>
</body>
</html>

O/P:
Check if fruits is an array?
true
-------------------------------------
Check if new Date() is a Date?

true


--------------------------------------------------

Converting Numbers to Strings

Done in 2 ways:
1) Use the global method String()
String(x)         // returns a string from a number variable x
String(123)       // returns a string from a number literal 123 
String(100 + 23)  // returns a string from a number from an expression

2) Use the Number method toString()
x.toString()
(123).
toString()
(100 + 23).
toString()


Converting Booleans to Strings

Done in 2 ways:
1) Use the global method String()
String(false)        // returns "false"
String(true)         // returns "true"

2) Use the Boolean method toString()
false.toString()     // returns "false"
true.toString()      // returns "true"



Converting Dates to Strings

Done in 2 ways:
1) Use the global method String()
String(Date())      // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)"

2) Use the Boolean method toString()
Date().toString()   // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)"


Converting Strings to Numbers

(also refer conversion of variables to numbers at here)
Number("3.14")    // returns 3.14
Number(" ")       // returns 0 
Number("")        // returns 0
Number("99 88")   // returns NaN


Converting Booleans to Numbers

Number(false)     // returns 0
Number(true)      // returns 1


Converting Dates to Numbers

Done in 2 ways:
1) Use the global method Number()
d = new Date(); Number(d)          // returns 1404568027739

2) Use the date method getTime()
d = new Date(); d.getTime()        // returns 1404568027739




Converting Arrays to Strings

Say, var cars = ["Saab""Volvo""BMW"];

Done in 3 ways
1) cars.toString();//returns a string with all array elements seperated by comma

2)cars;//auto converts to String with same output as above

3)cars.join(" * ");//returns a string of all array elements seperated by "*"....O/p:Saab*Volvo*BMW


--------------------------------------------------

Automatic Type Conversion

5 + null    // returns 5         because null is converted to 0
"5" + null  // returns "5null"   because null is converted to "null"
"5" + 2     // returns 52        because 2 is converted to "2"
"5" - 2     // returns 3         because "5" is converted to 5
"5" * "2"   // returns 10   because "5" and "2" are converted to 5 and 2


Automatic String Conversion

document.getElementById("demo").innerHTML = myVar;

if myVar = {name:"Fjohn"}  // toString converts to "[object Object]"

if myVar = [1,2,3,4]       // toString converts to "1,2,3,4"
if myVar = new Date()      // toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200"

if myVar = 123             // toString converts to "123"
if myVar = true            // toString converts to "true"
if myVar = false           // toString converts to "false"



--------------------------------------------------























































-------------------------------------------------


Difference Between Undefined and Null

typeof undefined             // undefined
typeof null                  // object
null === undefined           // false
null == undefined            // true

-------------------------------------------------

  • instanceof : Returns true if an object is an instance of an object type. Example :
Recognise an Array: 3 ways to do this
since, typeof cars; // returns object 
    • Array.isArray(cars);// returns true
    • function isArray(x) {return x.constructor.toString().indexOf("Array")>-1;}
    • cars instanceof Array     // returns true
since, typeof cars; // returns object 
    • Array.isArray(cars);// returns true
    • function isArray(x) {return x.constructor.toString().indexOf("Array")>-1;}
    • cars instanceof Array     // returns true
-------------------------------------------------

No comments:

Post a Comment