revision:
In JavaScript there are 5 different data types that can contain values (string, number, boolean, object, and function.), 6 types of objects (object, date, array, string, number, and boolean), and 2 data types that cannot contain values (null and undefined).
Examples
<div class="spec"> <a id="id1"></a><br><br> <a id="id2"></a><br><br> <a id="id3"></a><br><br> <a id="id4"></a><br><br> <a id="id5"></a><br><br> <a id="id6"></a><br><br> <a id="id7"></a><br><br> <a id="id8"></a><br> </div> <script> let score = '100'; score = Number(score); document.getElementById('id1').innerHTML = "number: " + (score + 1); document.getElementById('id2').innerHTML = "typeof number: " + (typeof score); let result1 = Number('hello'); let result2 = String(50); let result3 = Boolean(100); let result4 = Boolean(0); let result5 = Boolean('0'); let result6 = Boolean(''); document.getElementById('id3').innerHTML = "typeof number converted into string: " + (result1, typeof result1); document.getElementById('id4').innerHTML = "typeof string: " + (result2, typeof result2); document.getElementById('id5').innerHTML = "typeof Boolean: " + (result3, typeof result3); document.getElementById('id6').innerHTML = "typeof Boolean: " + (result4, typeof result4); document.getElementById('id7').innerHTML = "typeof Boolean: " + (result5, typeof result5); document.getElementById('id8').innerHTML = "typeof Boolean: " + (result6, typeof result6); </script>
JavaScript variables can be converted to a new variable and another data type: 1/ by using a JavaScript function, and 2/ automatically by JavaScript itself.
The "typeof" operator can be used to find the data type of a JavaScript variable.
Note that:
The data type of NaN is number
The data type of an array is object
The data type of a date is object
The data type of null is object
The data type of an undefined variable is undefined
The data type of a variable that has not been assigned a value is also undefined
The "constructor" property returns the constructor function for all JavaScript variables.
Examples
<div class="spec"> <a id="id9"></a> </div> <script> document.getElementById("id9").innerHTML = "john".constructor + " ," +'<br>' + (3.14).constructor + " ," +'<br>' + false.constructor + " ," +'<br>' + [1,2,3,4].constructor + ' ,' + "<br>" + {name:'john', age:34}.constructor + " ," +'<br>' + new Date().constructor + " ," + '<br>' + function () {}.constructor; </script>
You can check the constructor property to find out if an object is an Array (contains the word "Array").
This "home made" isArray() function returns true when used on an array.
Examples
<div class="spec"> <a id="id10"></a> </div> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("id10").innerHTML = isArray(fruits); function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; } </script>
Or even simpler, you can check if the object is an Array function.
Examples
<div class="spec"> <a id="id11"></a> </div> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("id11").innerHTML = isArray(fruits); function isArray(myArray) { return myArray.constructor === Array; } </script>
The global method String() can convert numbers to strings. It can be used on any type of numbers, literals, variables, or expressions.
The conversion to string is usually obvious for primitive values.
Examples
<div class="spec"> <a id="id12"></a><br> <a id="id13"></a><br> <a id="id14"></a><br> </div> <script> var x = 123; document.getElementById("id12").innerHTML = "conversions to string: " + String(x) + " , " + String(123) + " , " + String(100 + 23); let value = true; document.getElementById('id13').innerHTML = "type of value: " + (typeof value); let value1 = String(value); document.getElementById('id14').innerHTML = "type of value: " + (typeof value1); </script>
The Number method toString() does the same.
Examples
: <div class="spec"> <a id="id15"></a> </div> <script> var x = 123; document.getElementById("id15").innerHTML = "conversion to string: " + x.toString() + " , " + (123).toString() + " , " + (100 + 23).toString(); </script>
The global method String() can convert booleans to strings. The Boolean method toString() does the same.
The global method String() can convert dates to strings. The Date method toString() does the same.
Numeric conversions occur in math operations and can also be performed with Number(value).
The global method Number() can convert strings to numbers. Strings containing numbers (like "3.14") convert to numbers (like 3.14). Empty strings (like "")convert to 0. Anything else converts to NaN (Not a Number).
Examples
<div> <p id="id16"></p> </div> <script> document.getElementById("id16").innerHTML = Number("3.14") + "<br>" + Number(Math.PI) + "<br>" + Number(" ") + "<br>" + Number("") + "<br>" + Number("99 88") + "<br>" + Number("John") + "<br>"; </script>
The global method Number() can also convert booleans to numbers and can be used to convert dates to numbers.
Examples
<div class="spec"> <a id="id17"></a><br> <a id="id18"></a><br> <a id="id19"></a><br> <a id="id20"></a><br> <a id="id21"></a><br> <a id="id22"></a><br> <a id="id23"></a><br> <a id="id24"></a> </div> <script> document.getElementById('id17').innerHTML = "converting strings to numbers: " + ( "6" / "2" ); let str = '123'; document.getElementById('id18').innerHTML = "string - type of: " + (typeof str); let num = Number(str); document.getElementById('id19').innerHTML = "string to number - type of: " + (typeof num); let age = Number('an arbitrary number instead of a number'); document.getElementById('id20').innerHTML = "string :" + age; document.getElementById('id21').innerHTML = "string to number: " + (Number("123")); document.getElementById('id22').innerHTML = "string to number: " + (Number("125z")); document.getElementById('id23').innerHTML = "boolean: " + (true); document.getElementById('id24').innerHTML = "boolean: " + (false); </script>
You can convert a string to a number by writing a + operator before the string.
longhand
const num1 = parseInt("100"); const num2 = parseFloat("100.01"); let total = parseInt('45'); let average = parseFloat('421.6');
shorthand
const num1 = +"100"; // converts to int data type const num2 = +"100.01"; // converts to float data type let total = +'45'; let average = +'421.6';
Occurs in logical operations and can be performed with Boolean(value).
Examples
<div class="spec"> <a id="id25"></a><br> <a id="id26"></a><br> <a id="id27"></a><br> <a id="id28"></a><br> <a id="id29"></a><br> <a id="id30"></a> </div> <script> document.getElementById('id25').innerHTML = "Boolean - 1 : " + (Boolean(1)); document.getElementById('id26').innerHTML = "Boolean - 0 : " + (Boolean(0)); document.getElementById('id27').innerHTML = "Boolean - string : " + (Boolean('hello')); document.getElementById('id28').innerHTML = "Boolean - empty string : " + (Boolean('')); document.getElementById('id29').innerHTML = "Boolean - string number : " + (Boolean("0")); document.getElementById('id30').innerHTML = "Boolean - empty string: " + (Boolean(" ")); </script>
Examples
let value = true; alert(typeof value); // boolean value = String(value); // now value is a string "true" alert(typeof value); // string
alert( "6" / "2" ); // 3, strings are converted to numbers let str = "123"; alert(typeof str); // string let num = Number(str); // becomes a number 123 alert(typeof num); // number let age = Number("an arbitrary string instead of a number"); alert(age); // NaN, conversion failed alert( Number(" 123 ") ); // 123 alert( Number("123z") ); // NaN (error reading a number at "z") alert( Number(true) ); // 1 alert( Number(false) ); // 0
alert( Boolean(1) ); // true alert( Boolean(0) ); // false alert( Boolean("hello") ); // true alert( Boolean("") ); // false alert( Boolean("0") ); // true alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
// output alert(obj); // using object as a property key anotherObj[obj] = 123; // explicit conversion let num = Number(obj); // maths (except binary plus) let n = +obj; // unary plus let delta = date1 - date2; // less/greater comparison let greater = user1 > user2; // binary plus uses the "default" hint let total = obj1 + obj2; // obj == number uses the "default" hint if (user == 1) { ... };
obj[Symbol.toPrimitive] = function(hint) { // here goes the code to convert this object to a primitive // it must return a primitive value // hint = one of "string", "number", "default" }; let user = { name: "John", money: 1000, [Symbol.toPrimitive](hint) { alert(`hint: ${hint}`); return hint == "string" ? `{name: "${this.name}"}` : this.money; } }; // conversions demo: alert(user); // hint: string -> {name: "John"} alert(+user); // hint: number -> 1000 alert(user + 500); // hint: default -> 1500
let user = {name: "John"}; alert(user); // [object Object] alert(user.valueOf() === user); // true let user = { name: "John", money: 1000, // for hint="string" toString() { return `{name: "${this.name}"}`; }, // for hint="number" or "default" valueOf() { return this.money; } }; alert(user); // toString -> {name: "John"} alert(+user); // valueOf -> 1000 alert(user + 500); // valueOf -> 1500