JavaScript - tutorial - 11 - data types

revision:


Content

data types methods of primitives numbers strings booleans arrays objects "typeof" operator undefined empty values null data types examples


data types

top

JavaScript variables can hold many data types: numbers, strings, objects, and more. When adding a number and a string, JavaScript will treat the number as a string.

Examples: data types



code:
                    <div class="spec">
                        <a id="data1"></a><br><br> 
                        <a id="data1a"></a> 
                    </div>
                    <script>
                        var x = 16 + "Volvo";
                        document.getElementById("data1").innerHTML = "number + string: " + x;
                        document.getElementById("data1a").innerHTML = "string + number: " + x;
                    </script>
                

JavaScript evaluates expressions from left to right. Different sequences can produce different results

Examples: expression evaluation





code:
                        <div class="spec">
                            <a id="data2"></a><br><br>
                            <a id="data2a"></a><br><br>
                        </div>
                        <script>
                            var x = 16 + 4 + "Volvo";
                            var y = "Volvo" + 16 + 4;
                            document.getElementById("data2").innerHTML = "number + number + string: " + x;
                            document.getElementById("data2a").innerHTML = "string + number + number: " + y;
                        </script>
                        </script>
                    

JavaScript has dynamic types, which means that the same variable can be used to hold different data types.


methods of primitives

top

Primitives, except "null" and "undefined", provide many helpful methods. Formally, these methods work via temporary objects, but JavaScript engines are well tuned to optimize that internally, so they are not expensive to call.

Examples: primitives







code:
                    <div  class="spec">
                        <a id="data3"></a><br><br>  
                        <a id="data3a"></a><br><br> 
                        <a id="data3b"></a><br><br>   
        
                    </div>
                    <script>
                        let john = {
                            name: "John",
                            sayHi: function() {
                            document.getElementById("data3").innerHTML = "variable - name: " + john.name;
                            }
                        };
                        john.sayHi();
        
                        let str = "Hello";
                        document.getElementById('data3a').innerHTML = " variable - uppercase: " + str.toUpperCase();
        
                        let str2 = "Hello";
                        str2.test = 5;
                        document.getElementById('data3b').innerHTML= "variable - number: " + str2.test;
        
                    </script>
                

numbers

top

JavaScript has only one type of numbers. Numbers can be written with or without decimals.

Extra large or extra small numbers can be written with scientific (exponential) notation. To write numbers with many zeroes: append "e" with the zeroes count to the number. Like: 123e6 is the same as 123 with 6 zeroes (123000000). A negative number after "e" causes the number to be divided by 1 with given zeroes. E.g. 123e-6 means 0.000123 (123 millionths).

Examples: big/small for different numeral systems








code:
                    <div class="spec">
                        <a id="data4"></a><br>
                        <a id="data4a"></a><br>
                        <a id="data4b"></a><br><br> 
                        <a id="data4c"></a><br>  
                        <a id="data4d"></a><br>  
                        <a id="data4e"></a><br>  
                    </div>
                    <script>
                        let billion = 1e9; 
                        document.getElementById('data4').innerHTML = "using e for large numbers: " + 7.3e9; 
                        document.getElementById('data4a').innerHTML = "using e for large numbers: " + 1e3; 
                        document.getElementById('data4b').innerHTML = "using e for large numbers: " + 1e6; 
        
                        let ms = 1e-6; 
                        document.getElementById('data4c').innerHTML = "using e for small: " + 3e-6; 
                        document.getElementById('data4d').innerHTML = "using e for small: " + 3e-2; 
                        document.getElementById('data4e').innerHTML = "using e for small: " + 3e-3;   
                    </script>
                

Numbers can be written directly in hex (0x), octal (0o) and binary (0b) systems.

Examples: directly written





code:
                    <div class="spec">
                        <a id="data5"></a><br>
                        <a id="data5a"></a><br>
                        <a id="data5b"></a><br>
                        <a id="data5c"></a><br>
                        <a id="data5d"></a>    
                    </div>
                    <script>
                        document.getElementById('data5').innerHTML = "hex: " + 0xff; 
                        document.getElementById('data5a').innerHTML = "hex: " + 0xFF; 
                        document.getElementById('data5b').innerHTML = "binary: " + 0b11111111 ; 
                        document.getElementById('data5c').innerHTML = "octal: " + 0o377 ; 
                        document.getElementById('data5d').innerHTML = "binary = octal: " + (0b11111111 == 0o377);       
                    </script>
                

parseInt(str, base) parses the string "str" into an integer in numeral system with given base, 2 ≤ base ≤ 36.

num.toString(base) converts a number to a string in the numeral system with the given base.

For converting values - like 12pt and 100px - to a number: use parseInt/parseFloat for the "soft" conversion, which reads a number from a string and then returns the value they could read before the error.

Examples: parseInt()







code:
                    <div class="spec">
                        <a id="data6"></a><br>
                        <a id="data6a"></a><br>
                        <a id="data6b"></a><br>   
                        <a id="data6c"></a><br>   
                        <a id="data6d"></a><br>   
                        <a id="data6e"></a><br>   
                    </div>      
                    <script>
                        let num = 255; 
                        document.getElementById('data6').innerHTML = "number to string: " + num.toString(16); 
                        document.getElementById('data6a').innerHTML = "number to string: " + num.toString(2); 
                        document.getElementById('data6b').innerHTML = "number to string: " + num.toString(36);
                    
                        document.getElementById('data6c').innerHTML = "parseFloat: " + parseFloat('12.5em'); 
                        document.getElementById('data6d').innerHTML = "parseInt: " + parseInt('12.3'); 
                        document.getElementById('data6e').innerHTML ="parseFloat: " +  parseFloat('12.3.4'); 
                    </script>
                

for fractions: round using Math.floor, Math.ceil, Math.trunc, Math.round or num.toFixed(precision). Make sure to remember there's a loss of precision when working with fractions.

Examples: fractions





code:
                    <div class="spec">
                        <a id="data7"></a><br>
                        <a id="data7a"></a><br>
                        <a id="data7b"></a><br>
                        <a id="data7c"></a><br>
                        <a id="data7d"></a>    
                    </div>
                    <script>
                        let n = 123;
                        document.getElementById('data7').innerHTML = n;
                        document.getElementById('data7a').innerHTML = (1/0);
                        document.getElementById('data7b').innerHTML = 'not a number'/2;
        
                        let radius = 10;
                        const pi = 3.14;
                        document.getElementById('data7c').innerHTML = (radius, pi);
                        document.getElementById('data7d').innerHTML = (5/'hello');
                    </script>
                

strings

top

A string (or a text string) is a series of characters. Strings are written with quotes. You can use single or double quotes. You can use quotes inside a string, as long as they don't match the quotes surrounding the string.

Examples: strings









code:
                    <div class="spec">
                        <a id="data8"></a><br>
                        <a id="data8a"></a><br>
                        <a id="data8b"></a><br>
                        <a id="data8c"></a><br>
                        <a id="data8d"></a><br>
                        <a id="data8e"></a><br>
                        <a id="data8f"></a><br>
                        <a id="data8g"></a><br>
                    </div>
                    <script>
                        let str4 = "Hello"; document.getElementById('data8').innerHTML = str4;
                        let str5 = 'Single quotes are also OK'; document.getElementById('data8a').innerHTML = str5;
                        let phrase = `Can ember another ${str}`;document.getElementById('data8b').innerHTML = phrase;
                        let name2 = 'John';document.getElementById('data8c').innerHTML = (`Hello, ${name2}`);
                        document.getElementById('data8d').innerHTML =  `the result is ${1+2}`;
                        document.getElementById('data8e').innerHTML = "the result is ${1+2}";
                        document.getElementById('data8f').innerHTML = ('hello world!');
                        let email = "lwitters@gmail.com"; document.getElementById('data8g').innerHTML = email;
                    </script>
                

booleans

top

Booleans can only have two values: true or false. Booleans are often used in conditional testing.

Examples: booleans





code:
                    <div class="spec">
                        <a id="data9"></a><br>
                        <a id="data9a"></a><br>
                        <a id="data9b"></a><br>
                        <a id="data9c"></a><br>
                    </div>
                    <script>
                        let isGreater = 4>1;
                            document.getElementById('data9').innerHTML = isGreater;
                            document.getElementById('data9a').innerHTML = (true, false, 'true', 'false');
                        // methods can return booleans
                        let email1 = 'witterslouis@hotmail.com';
                        let names = ['mario', 'luigi', 'toad'];
                        let result6 = email1.includes('@');
                        let result7 = names.includes('luigi');
                            document.getElementById('data9b').innerHTML =  result6;
                            document.getElementById('data9c').innerHTML =  result7;
                    </script>
                

cast any value to a Boolean

In JavaScript, you can cast anything to a boolean value, because everything in JavaScript is either "truthy" or "falsy". To convert anything to boolean, use the double exclamation "!!". It is possible to use a Double NOT (!!) operator in series to explicitly force the conversion of any value to the corresponding boolean primitive.

base

                    const expression = 'string or number'
                

longhand

                    const isTrue = Boolean(expression) // output: true
                

shorthand

                    !!true    // true
                    !!2       // true
                    !![]      // true
                    !!"Test"  // true

                    !!false   // false
                    !!0       // false
                    !!""      // false

                    const isTrue = !!expression;        // output: true
                

get a random boolean (true/false)

Using the Math.random() method, this function will return a boolean (true or false). Math.random will create a random number between 0 and 1, after which we check if it is higher or lower than 0.5. That means it's a 50%/50% chance to get either true or false.

Example - code

                const randomBoolean = () => Math.random() >= 0.5;
                console.log(randomBoolean()); 
                // Result: a 50/50 change on returning true of false
            
                var random_boolean = Math.random() < 0.5;
                console.log(Math.random() < 0.5);  
                //50% probability of getting true
            
                let randomBoolean = Math.random()  < .5;      
                console.log(randomBoolean());
                //50% probability of getting true
            

toggle boolean

Toggling a boolean value can be solved in a lot of different ways. Instead of using if-statements to determine what value to set the boolean to, you could instead use the function to flip the current value using the ! “not” operator.

Example - code

            // bool is stored somewhere in the upperscope
            const toggleBool = () => (bool = !bool);
        
            booly = !(booly != false)
        
            bool === tool ? bool : tool
        

arrays

top

JavaScript arrays are written with square brackets. Array items are separated by commas. Array indexes are zero-based, which means the first item is [0], second is [1], etc.

Examples: arrays

code:
                    <div class="spec">
                        <a id="data10"></a>      
                    </div>
                    <script>
                        var cars = ["Saab","Volvo","BMW"];
                        document.getElementById("data10").innerHTML = cars[0];
                    </script>
                

objects

top

JavaScript objects are written with curly braces {}. Object properties are written as "name:value" pairs, separated by commas.

Examples: objects





















code:
                    <div class="spec">
                        <a id="data11"></a><br><br>   
                        <a id="data11a"></a><br><br> 
                        <a id="data11b"></a><br><br> 
                        <a id="data11c"></a><br><br> 
                        <a id="data11d"></a><br><br> 
                        <a id="data11e"></a><br><br> 
                        <a id="data11f"></a><br><br> 
                        <a id="data11g"></a><br><br> 
                        <a id="data11h"></a><br><br> 
                        <a id="data11i"></a><br><br> 
                    </div>
                    <script>
                        var person = {
                            firstName : "John",
                            lastName  : "Doe",
                            age : 50,
                            eyeColor : "blue"
                        };
                        document.getElementById("data11").innerHTML = person.firstName + " is " + person.age + " years old.";
                        document.getElementById('data11a').innerHTML = 'Hello ';
                        document.getElementById('data11b').innerHTML = ' World!';
                        document.getElementById('data11c').innerHTML = 'Hello';
                        document.getElementById('data11d').innerHTML = 'World';
                        document.getElementById('data11e').innerHTML = 'Hello, World!';
                        document.getElementById('data11f').innerHTML = 'Hello' //automatic semicolon
                        document.getElementById('data11g').innerHTML = 'World'//automatic semicolon
                        document.getElementById('data11h').innerHTML = 'Hello, World!'//automatic semicolon
                        document.getElementById('data11i').innerHTML = ( 3 +
                            1
                            +2    );
                    </script>
                

BigInt is a built-in object that provides a way to represent whole numbers larger than 253 - 1, which is the largest number JavaScript can reliably represent with the Number primitive.

Examples: BigInt

code:
                    <div class="spec">
                        <a id="data12"></a>         
                    </div>
                    <script>
                    const BigInt = 12345678901234567890123456789012n;
                    document.getElementById('data12').innerHTML = BigInt;
                    </script>
                

"typeof" operator

top

The typeof operator returns the type of a variable or an expression.

Examples: typeof

code:
                    <div class="spec">
                        <a id="data13"></a>         
                    </div>
                    <script>
                        document.getElementById("data13").innerHTML = 
                        typeof 0 + " ," + 
                        typeof 314 + " , " +
                        typeof 3.14 + " , " +
                        typeof (3) + " , " +
                        typeof (3 + 4);
                    </script>
                

undefined

top

In JavaScript, a variable without a value, has the value "undefined". The type is also "undefined". Any variable can be emptied, by setting the value to "undefined". The type will also be "undefined".

Examples: undefined



code:
                    <div class="spec">
                        <a id="data14"></a><br>
                        <a id="data14a"></a><br>
                        <a id="data14b"></a>          
                    </div>
                    <script>
                        let xy;
                            document.getElementById('data14').innerHTML = xy;
                        let xy1 = 123;
                            document.getElementById('data14a').innerHTML = xy1;
                        xy2 = undefined;
                            document.getElementById('data14b').innerHTML = xy2;
                    </script>
                

empty values

top

An empty value has nothing to do with "undefined". An empty string has both a legal value and a type.


null

top

In JavaScript null is "nothing". It is supposed to be something that doesn't exist. You can empty an object by setting it to null.

examples: null


code:
                    <div class="spec">
                        <a id="data15"></a><br>
                        <a id="data15a"></a>         
                    </div>
                    <script>
                        let life = null;
                            document.getElementById('data15').innerHTML = (life);
                        let age1 = null;
                            document.getElementById('data15a').innerHTML = (age1, age1 + 3, `the age is ${age1}`);
                    </script>
                

Data types examples

top

Github - bigint examples

examples
bigint-asintn:
                    const max = 2n ** (64n - 1n) - 1n;
                    function check64bit(number) {
                    (number > max) ?
                        console.log('Number doesn\'t fit in signed 64-bit integer!') :
                        console.log(BigInt.asIntN(64, number));
                    }
                    check64bit(2n ** 64n);
                    // expected output: "Number doesn't fit in signed 64-bit integer!"
                    check64bit(2n ** 32n);
                    // expected output: 4294967296n
                
bigint-asuintn:
                    const max = 2n ** 64n - 1n;
                    function check64bit(number) {
                    (number > max) ?
                        console.log('Number doesn\'t fit in unsigned 64-bit integer!') :
                        console.log(BigInt.asUintN(64, number));
                    }
                    check64bit(2n ** 64n);
                    // expected output: "Number doesn't fit in unsigned 64-bit integer!"
                        check64bit(2n ** 32n);
                    // expected output: 4294967296n
                
bigint-tolocalestring:
                    const bigint = 123456789123456789n;
                    // German uses period for thousands
                    console.log(bigint.toLocaleString('de-DE'));
                    // expected output: "123.456.789.123.456.789"
                    // request a currency format
                    console.log(bigint.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
                    // expected output: "123.456.789.123.456.789,00 €"
                
bigint-tostring:
                    console.log(1024n.toString());
                    // expected output: "1024"
                    console.log(1024n.toString(2));
                    // expected output: "10000000000"
                    console.log(1024n.toString(16));
                    // expected output: "400"
                
bigint-valueof:
                    console.log(typeof Object(1n));
                    // expected output: "object"
                    console.log(typeof Object(1n).valueOf());
                    // expected output: "bigint"
                

Github - boolean examples

boolean-constructor:
                    const flag = new Boolean();
                    console.log(flag);
                    // expected output: false
                
boolean-tostring:
                    const flag1 = new Boolean(true);
                    console.log(flag1.toString());
                    // expected output: "true"
                    const flag2 = new Boolean(1);
                    console.log(flag2.toString());
                    // expected output: "true"
                
boolean-valueof:
                    const x = new Boolean();
                    console.log(x.valueOf());
                    // expected output: false
                    const y = new Boolean('Mozilla');
                    console.log(y.valueOf());
                    // expected output: true
                

Github - number examples

examples
number-epsilon:
                const result = Math.abs(0.2 - 0.3 + 0.1);
                console.log(result);
                // expected output: 2.7755575615628914e-17
                console.log(result < Number.EPSILON);
                // expected output: true
            
number-isfinite:
                console.log(Number.isFinite(1 / 0));
                // expected output: false
                console.log(Number.isFinite(10 / 5));
                // expected output: true
                console.log(Number.isFinite(0 / 0));
                // expected output: false
            
number-isinteger:
                function fits(x, y) {
                    if (Number.isInteger(y / x)) {
                    return 'Fits!';
                    }
                    return 'Does NOT fit!';
                }
                console.log(fits(5, 10));
                // expected output: "Fits!"
                console.log(fits(5, 11));
                // expected output: "Does NOT fit!"
            
number-isnan:
                function typeOfNaN(x) {
                    if (Number.isNaN(x)) {
                    return 'Number NaN';
                    }
                    if (isNaN(x)) {
                    return 'NaN';
                    }
                }
                console.log(typeOfNaN('100F'));
                // expected output: "NaN"
                console.log(typeOfNaN(NaN));
                // expected output: "Number NaN"
            
number-issafeinteger:
                function warn(x) {
                    if (Number.isSafeInteger(x)) {
                    return 'Precision safe.';
                    }
                    return 'Precision may be lost!';
                }
                console.log(warn(Math.pow(2, 53)));
                // expected output: "Precision may be lost!"
                console.log(warn(Math.pow(2, 53) - 1));
                // expected output: "Precision safe."
            
number-max-safe-integer:
                const x = Number.MAX_SAFE_INTEGER + 1;
                const y = Number.MAX_SAFE_INTEGER + 2;
                console.log(Number.MAX_SAFE_INTEGER);
                // expected output: 9007199254740991
                console.log(x);
                // expected output: 9007199254740992
                console.log(x === y);
                // expected output: true
            
number-max-value
                function multiply(x, y) {
                    if (x * y > Number.MAX_VALUE) {
                    return ('Process as Infinity');
                    }
                    return (x * y);
                }
                console.log(multiply(1.7976931348623157e+308, 1));
                // expected output: 1.7976931348623157e+308
                console.log(multiply(1.7976931348623157e+308, 2));
                // expected output: "Process as Infinity"
            
number-min-safe-integer:
                const x = Number.MIN_SAFE_INTEGER - 1;
                const y = Number.MIN_SAFE_INTEGER - 2;
                console.log(Number.MIN_SAFE_INTEGER);
                // expected output: -9007199254740991
                console.log(x);
                // expected output: -9007199254740992
                console.log(x === y);
                // expected output: true
            
number-min-value:
                function multiply(x, y) {
                    if (x * y < Number.MIN_VALUE) {
                    return 'Process as -Infinity';
                    }
                    return (x * y);
                }
                console.log(multiply(5e-324, 1));
                // expected output: 5e-324
                console.log(multiply(-1.7976931348623157e+308, 2));
                // expected output: Process as -Infinity
            
number-nan:
                function clean(x) {
                    if (x === Number.NaN) {
                    // can never be true
                    return null;
                    }
                    if (isNaN(x)) {
                    return 0;
                    }
                }
                console.log(clean(Number.NaN));
                // expected output: 0
            
number-negative-infinity:
                function checkNumber(smallNumber) {
                    if (smallNumber === Number.NEGATIVE_INFINITY) {
                    return 'Process number as -Infinity';
                    }
                    return smallNumber;
                }
                console.log(checkNumber(-Number.MAX_VALUE));
                // expected output: -1.7976931348623157e+308
                console.log(checkNumber(-Number.MAX_VALUE * 2));
            // expected output: "Process number as -Infinity"
            
number-parsefloat:
                function circumference(r) {
                    if (Number.isNaN(Number.parseFloat(r))) {
                    return 0;
                    }
                    return parseFloat(r) * 2.0 * Math.PI ;
                }
                console.log(circumference('4.567abcdefgh'));
                // expected output: 28.695307297889173
                console.log(circumference('abcdefgh'));
                // expected output: 0
            
number-parseint:
                function roughScale(x, base) {
                    const parsed = Number.parseInt(x, base);
                    if (Number.isNaN(parsed)) {
                    return 0;
                    }
                    return parsed * 100;
                }
                console.log(roughScale(' 0xF', 16));
                // expected output: 1500
                console.log(roughScale('321', 2));
                // expected output: 0
            
number-positive-infinity:
                function checkNumber(bigNumber) {
                    if (bigNumber === Number.POSITIVE_INFINITY) {
                    return 'Process number as Infinity';
                    }
                    return bigNumber;
                }
                console.log(checkNumber(Number.MAX_VALUE));
                // expected output: 1.7976931348623157e+308
                console.log(checkNumber(Number.MAX_VALUE * 2));
                // expected output: Process number as Infinity
            
number-toexponential:
                function expo(x, f) {
                    return Number.parseFloat(x).toExponential(f);
                }
                console.log(expo(123456, 2));
                // expected output: "1.23e+5"
                console.log(expo('123456'));
                // expected output: "1.23456e+5"
                console.log(expo('oink'));
                // expected output: "NaN"
            
number-tofixed:
                function financial(x) {
                    return Number.parseFloat(x).toFixed(2);
                }
                console.log(financial(123.456));
                // expected output: "123.46"
                console.log(financial(0.004));
                // expected output: "0.00"
                console.log(financial('1.23e+5'));
                // expected output: "123000.00"
            
number-tolocalestring:
                function eArabic(x){
                    return x.toLocaleString('ar-EG');
                }
                console.log(eArabic(123456.789));
                // expected output: "١٢٣٬٤٥٦٫٧٨٩"
                console.log(eArabic('123456.789'));
                // expected output: "123456.789"
                console.log(eArabic(NaN));
                // expected output: "ليس رقم"
            
number-toprecision:
                function precise(x) {
                    return Number.parseFloat(x).toPrecision(4);
                }
                console.log(precise(123.456));
                // expected output: "123.5"
                console.log(precise(0.004));
                // expected output: "0.004000"
                console.log(precise('1.23e+5'));
                // expected output: "1.230e+5"
            
number-tostring:
                function hexColour(c) {
                    if (c < 256) {
                    return Math.abs(c).toString(16);
                    }
                    return 0;
                }
                console.log(hexColour(233));
                // expected output: "e9"
                console.log(hexColour('11'));
                // expected output: "b"
            
number-valueof
                const numObj = new Number(42);
                console.log(typeof numObj);
                // expected output: "object"
                const num = numObj.valueOf();
                console.log(num);
                // expected output: 42
                console.log(typeof num);
                // expected output: "number"
            

JavaScript.info - examples

examples
any type in a variable:
                    // no error
                    let message = "hello";
                    message = 123456;
                
                
number:
                    let n = 123;
                    n = 12.345;
                    
                    alert( 1 / 0 ); // Infinity

                    alert( Infinity ); // Infinity

                    alert( "not a number" / 2 ); // NaN, such division is erroneous

                    alert( NaN + 1 ); // NaN
                    alert( 3 * NaN ); // NaN
                    alert( "not a number" / 2 - 1 ); // NaN
                
BigInt:
                    // the "n" at the end means it's a BigInt
                    const bigInt = 1234567890123456789012345678901234567890n;
                
string:
                    let str = "Hello";
                    let str2 = 'Single quotes are ok too';
                    let phrase = `can embed another ${str}`;

                    let name = "John";
                    // embed a variable
                    alert( `Hello, ${name}!` ); // Hello, John!
                    // embed an expression
                    alert( `the result is ${1 + 2}` ); // the result is 3
                
boolean (logical type):
                    let nameFieldChecked = true; // yes, name field is checked
                    let ageFieldChecked = false; // no, age field is not checked

                    let isGreater = 4 > 1;
                    alert( isGreater ); // true (the comparison result is "yes")
                
"null" value:
                    let age = null;
                
"undefined" value:
                    let age;
                    alert(age); // shows "undefined"
                    
                    let age = 100;
                    // change the value to undefined
                    age = undefined;
                    alert(age); // "undefined"
                
typeof operator
                    typeof undefined // "undefined"
                    typeof 0 // "number"
                    typeof 10n // "bigint"
                    typeof true // "boolean"
                    typeof "foo" // "string"
                    typeof Symbol("id") // "symbol"
                    typeof Math // "object"  (1)
                    typeof null // "object"  (2)
                    typeof alert // "function"  (3)