Book of Coding


The different data types in JavaScript

In JavaScript, a distinction is made between different data types:

  • primitive data types: string, number, boolean, symbol
  • special data types: undefined, null
  • composite data type: object

undefined means that a variable has been declared but has not yet been assigned a value. null is an assignment value, it can be assigned to a variable as a representation without a value.

When declaring variables in JavaScript, the data type is not explicitly defined, which is referred to as loose typing. Other programming languages such as Java use so-called strong typing or strict typing, i.e. the data type must be explicitly specified when defining a variable. Loose typing can lead to unwanted problems when working with two or more variables of different data types. However, it is also possible in JavaScript to change the type of a variable during runtime using loose typing.


1. Numbers

Numbers are used in programming to perform calculations, describe quantities. To define value ranges or to count.


Definition of numbers

Numbers are represented in JavaScript by a numerical value. The value 7 also stands for the number seven. Comma numbers are noted with a dot 0.5. Negative values are preceded by a minus sign -7. Since ES2021 it is also possible to use underscores as separators, for better readability 1_000_000_000.

Examples:

Complete Code - Examples/Part_4/main.js...

 const number1 = 7;              // Definition of an integer
 const number2 = 0.5;            // Definition of a decimal number
 const number3 = -42;            // Definition of a negative integer
 const number4 = -0.6;           // Definition of a negative decimal number
 const number5 = 47_200;         // Separator for decimal representation
 const number6 = 1_000_000_000;  // Separator for decimal representation

 console.log(number1);       // 7
 console.log(number2);       // 0.5
 console.log(number3);       // -42
 console.log(number4);       // -0.6
 console.log(number5);       // 47200
 console.log(number6);       // 1000000000
                            


Number systems

Integers can be defined in JavaScript using different number systems. The notation differs in each case. There is the "standard" variant of decimal notation shown above (number system with base 10), the binary notation for defining binary numbers (number system with base 2), the octal notation for defining octal numbers (number system with base 8) and the hexadecimal notation for defining hexadecimal numbers (number system with base 16). These notations will not be used much at the beginning, but you should at least have heard of them before.

  • Binary numbers have the prefix 0b, followed by zeros and ones:
  • Complete Code - Examples/Part_5/main.js...
    
     const number1 = 0b00010101;             // Definition of a binary number (decimal value 21)
     // const number2 = 0b01000102;          // invalid binary number
     const number3 = 0b1010_0010_1010_0101;  // Separator for binary representation
    
     console.log(number1);       // 21
     console.log(number3);       // 41637 
                                            

  • Octary numbers always start with a 0, followed by a sequence of numbers between 0 and 7.
  • Complete Code - Examples/Part_6/main.js...
    
     const number1 = 040;            // Definition of an octal number (decimal value 32)
     // const number2 = 079;         // invalid octal number (value 79)
     const number3 = 021147;         // Definition of an octal number (decimal value 8807)
    
     console.log(number1);           // 32
     console.log(number3);           // 8807
                                            

  • Hexadecimal numbers always start with the character string 0x, followed by a sequence of hexadecimal values, i.e. the digits from 0-9 and the letters from A-F (or a-f).
  • Complete Code - Examples/Part_7/main.js...
    
     const number1 = 0xF;            // Definition of a hexadecimal number (decimal value 15)
     const number2 = 0xc;            // Definition of a hexadecimal number (decimal value 12)
     // const number3 = 0xH;         // invalid hexadecimal number (syntax error)
     const number4 = 0xAF_DC_B0;     // Separator for hexadecimal representation
    
     console.log(number1);       // 15
     console.log(number2);       // 12
     console.log(number4);       // 11525296
                                            


Value range of numbers

In JavaScript, the value range of numbers is limited, i.e. it is not possible to define infinitely large or infinitely small numbers, as the computer does not have an infinite amount of memory available. The smallest possible number that can be used is stored in the variable Number.MIN_VALUE (more precisely in the MIN_VALUE property of the Number object). The largest possible number, i.e. the maximum value of numbers, is stored in the variable Number.MAX_VALUE. In most runtime environments, the value of the smallest possible number is 5e-324 and the largest possible value is 1.7976931348623157e+308. Values outside the range cannot be displayed. If the result is outside the value range, the value Infinity (value above the value range) or Infinity (value below the value range) is used.

Complete Code - Examples/Part_8/main.js...

 console.log(Number.MIN_VALUE);          // output: 5e-324
 console.log(Number.MAX_VALUE);          // output: 1.7976931348623157e+308
 console.log(Number.NEGATIVE_INFINITY);  // output: -Infinity
 console.log(Number.POSITIVE_INFINITY);  // output: Infinity
                                

Invalid numerical values

Calculations that do not result in a valid numerical value return the value NaN (Not a number).


2. Strings

In programming, strings are a sequence of characters, i.e. letters, numbers, special characters and control characters. Strings are always used when there is some form of text involved.


Definition of strings

Strings are defined with quotation marks at the beginning and end. Single and double quotation marks are possible. However, you should decide on a style and a mixed form leads to errors.


 const firstName = 'Rick';          // single quotation marks
 const lastName = "Sample";         // double quotation marks
 const age = "42";                  // not a number, but a character string
 //  const city = 'Boston";         // syntax error: mixed form
                                

Escaping characters within strings

If quotation marks are to be used within a string, there are various options:

Complete Code - Examples/Part_9/main.js...

 const message1 = 'Your name is "Rick Sample"';
 const message2 = "Your name is 'Rick Sample'";
 const message3 = 'Your name is \'Rick Sample\'';
 const message4 = "Your name is \"Rick Sample\"";
 console.log(message1); // output: Your name is "Rick Sample"
 console.log(message2); // output: Your name is 'Rick Sample'
 console.log(message3); // output: Your name is 'Rick Sample'
 console.log(message4); // output: Your name is "Rick Sample"
                                

In message3 and message4, a backslash character \ is used before the quotation marks. The technical term for this prefixing of the backslash character is called escaping. The corresponding quotation mark is escaped before the interpreter so that it ignores it when determining the end of the string.

Other characters are also escaped, namely the so-called control characters, i.e. line breaks and indentations etc.

An overview of the control characters:

charactermeaning
\n new line
\t indentation
\b backspace
\r carriage return
\f Form feed

Example:

Complete Code - Examples/Part_10/main.js...

 const message = 'Hello\nMr.\nSample';
 console.log(message);
                                

Preview

Template strings

It often happens that you want to insert calculated values or values stored in the variables at certain points within a string. To do this, you use string concatenation to assemble the individual parts into a string:

Complete Code - Examples/Part_11/main.js...

 const name = 'Rick Sample';
 const age = 42;
 const message = 'My name is ' + name + ', I am ' + age + ' years old.';
 console.log(message); // "My name is Rick Sample, I am 42 years old."   
                                

However, this variant quickly becomes confusing if many parts are to be included in a character string and it is also not really advisable for performance reasons. This is where template strings come into play. Template strings are not defined using single or double quotation marks, but using backticks const message = `Hello World`.

A placeholder can be defined within template strings using the notation ${}:

Example:

Complete Code - Examples/Part_12/main.js...

 const name = 'Rick Sample';
 const age = 42;
 const message = `My name is ${name}, I am ${age} years old.`;
 console.log(message);   // My name is Rick Sample, I am 42 years old.
                                

In addition to variable names, other expressions can also be used within the curly brackets, e.g. a function call or an expression for an addition:

Complete Code - Examples/Part_13/main.js...

 const name = 'Rick Sample';
 const age = 42;
 function getName() {
   return name;
 }
 const message = `My name is ${getName()}, I am twice the age of ${age/2}.`;
 console.log(message);
 // "My name is Rick Sample, I am twice the age of 21."  
                                

In the case of multi-line character strings, this character string is often split into several parts and then joined using the +- operator and distributed over several lines:

Complete Code - Examples/Part_14/main.js...

 const message = 'Dear Rick, \n\n' +
   'Thank you very much for your Christmas greetings.\n\n' +
   'Best regards, \nMorty';
 console.log(message);
 // output:
 //
 // Dear Rick,
 //
 // Thank you very much for your Christmas greetings.
 //
 // Best regards,
 // Morty 
                                

Thanks to template strings, it is no longer necessary to use the +- operator, as line breaks are permitted within template strings. In the next example, the previous example (Part_14) has been converted into a template string (with backticks):

Complete Code - Examples/Part_15/main.js...

 'use strict';
 const message = `Dear Rick,
 Thank you very much for your Christmas greetings.
 Best regards,
 Morty`;
 console.log(message);
 // output: 
 //
 // Dear Rick,
 // Thank you very much for your Christmas greetings.
 // Best regards,
 // Morty
                                

3. Boolean values

Booleans are relatively simple compared to numerical values and strings, as only one of two values can be assumed, namely true or false. Boolean values play a central role in JavaScript when it comes to defining branches within a program.


 const = isLoggedIn = true;
 const = isAdmin = false;
                            

If a Boolean value is represented with an integer type, 0 usually means false and everything not equal to zero (-1 or 1 is often used) means true.


4. Objects

You could store all the data that a program requires in countless variables. However, this can become confusing, which is why it is common practice to combine related variables and functions in objects, which creates an overview and increases the reusability of the code. Variables in objects are called properties (object properties) or attributes and functions are called methods (object methods). The properties provide information about the object in which they are contained, e.g. the name or age of a person or the items in the shopping trolley. Object methods stand for tasks that are related to the object in which they are defined.


Definition of objects

The easiest way to create objects in JavaScript is using the so-called object literal notation. The object is simply enclosed in curly brackets and the object property and object method are listed within these curly brackets, separated by a comma:

Complete Code - Examples/Part_16/main.js...

 const item = {
   model: 'Nike air max one',
   price: 149.90,
   category: 'Shoes',
   itemNr: '1-234-567-89',
   printDescription: function() {
      console.log(`${this.modell}: ${this.price}`);
   }
 }
                                

This object item contains four properties model, price, category, itemNr and the method printDescription. Objects are key-value pairs: keys and values are separated from each other by a colon. The current object is addressed via the keyword this, i.e. the object property model is accessed with this.model. There are other ways to create objects: via the constructor function, via the Object.create() method or via the instantiation of an ES2015 class.


5. Special data types

There are two special data types in JavaScript: null and undefined. Both data types have one thing in common, they each have only one value, namely null and undefined. If a variable is to be declared, but no value has yet been assigned to this variable, i.e. it has not yet been initialized, the variable has the value undefined:

Complete Code - Examples/Part_17/main.js...

 let name;
 console.log(name);      // output: undefined
 name = 'Rick Sample';
 console.log(name);      // output: Rick Sample
                            

The data type null represents an empty object:

Complete Code - Examples/Part_18/main.js...

 const dog = {
   name: 'Snuffles'
 }
 const person = {
   firstName: 'Rick',
   lastName: 'Sample',
   pet: dog
 }
 console.log(person.pet); // output: Object {name: "Snuffles"}
 person.pet = null;
 console.log(person.pet); // output: null
                            

Two objects dog and person were created here, and then the dog object was assigned to the pet property of the person object. Access to person.pet therefore outputs the object dog, the property person.pet therefore points to the object dog. If you then set the person.pet property to null, you "resolve the dog object". So to express that an object variable is not loaded, you use the value null.


undefined vs. null

The value undefined is not intended to be manually assigned to a variable, the value null is. The value undefined expresses that a variable has not yet been initialized, the value null represents an empty object pointer.


6. Symbols

Symbols are another type of primitive data type introduced with ES2015, with which it is possible to define unique and unchangeable values. Symbols can be created using the Symbol() function, whereby a description of the symbol in the form of a string can optionally be passed as a parameter:

Complete Code - Examples/Part_19/main.js...

 const symbol1 = Symbol();
 const symbol2 = Symbol('exampleDescription');
 const symbol3 = Symbol();
 const symbol4 = Symbol('exampleDescription');
 console.log(symbol1);               // output: Symbol()
 console.log(symbol2);               // output: Symbol(exampleDescription)
 console.log(symbol3);               // output: Symbol()
 console.log(symbol4);               // output: Symbol(exampleDescription)
 console.log(symbol1 === symbol3);   // output: false
 console.log(symbol2 === symbol4);   // output: false
                        

Regardless of whether a symbol is created with or without a description, or whether the description of two symbols is the same, two symbols are always different. A comparison of two symbols therefore results in the value false. In practice, this data type does not occur so frequently, but it is important to know that symbols are unique and unchangeable. If you take a closer look at the subject of objects and object properties, you may come across this again.


Related links:


A short introduction to JavaScript arrays

Arrays are nothing more than lists. Arrays can contain not just one, but several values. For example, in a shopping list, an array would be used for the representation, the individual entries, i.e. the items in the shopping cart, would then be the names (identification numbers). The easiest way to create an array in JavaScript is the so-called array literal notation. To define the beginning and end of an array, square brackets are used [ ]. The individual entries (or values or elements) in the square brackets are separated by commas.

Example:

Complete Code - Arrays/Part_1/main.js...

 const shoppingCart = [      // start of the array definition
   'Bread',                  // first entry
   'Apples',                 // second entry
   'Milk',                   // third entry
   'Chocolate'               // fourth entry
 ];                          // End of the array definition
                  

A variable with the name shoppingCart is created here, to which such an array is assigned as a value. This array has four entries, namely the strings Bread, Apples, Milk and Chocolate.

The individual entries can also be in one line when defining an array:


 const shoppingCart = ['Bread', 'Apples', 'Milk', 'Chocolate'];     
                  

Arrays grow dynamically, i.e. when an array is created, the number of entries can be changed at any time. Arrays can also contain entries of different types, i.e. numbers as well as strings, Boolean values, objects or other arrays:

Complete Code - Arrays/Part_2/main.js...

 const values = [    // an array ...
   'Rick Sample',    // ... with a character string ...
   62,               // ... a number ...
   true              // ... and a boolean value
 ];
                  

The internal structure of an array

Arrays have an index-based structure in which each element in an array is stored at a specific index (position). The numbering of this index starts at 0, i.e. the first element in the array is at index 0, the second at index 1 and so on until the last element at index n-1, where n stands for the length of the array:


 const shoppingCart = [      
   'Bread',                  // Index 0
   'Apples',                 // Index 1
   'Milk',                   // Index 2
   'Chocolate'               // Index 3
 ];                              
                      

The index-based structure is interesting during development in that the individual elements of an array can be specifically accessed via the indices. To do this, the index of the element to be accessed is simply placed in square brackets after the name of the respective array:

Complete Code - Arrays/Part_3/main.js...

const item1 = shoppingCart[0]; // first item
const item2 = shoppingCart[1]; // second item
const item3 = shoppingCart[2]; // third item
const item4 = shoppingCart[3]; // fourth item
console.log(item1); // 'Bread'
console.log(item2); // 'Apples'
console.log(item3); // 'Milk'
console.log(item4); // 'Chocolate'
                      

Multidimensional arrays

It is also possible to add other arrays to an array. In addition, it is then possible to create multidimensional arrays (i.e. arrays of arrays). This can be useful if different data sets of the same data are to be stored in an array:

Complete Code - Arrays/Part_4/main.js...

 const shoppingCart = [ // start of the outer array
   [ // first entry
     'Bread',    // item, first element in the first array
     1.30,       // price, second element in the first array
     1           // number of items, third element in the first array
   ],
   [ // second entry
     'Apples',   // item, first element in the second array
     0.20,       // price, second element in the second array
     4           // number of items, third element in the second array
   ],
   [ // third entry
     'Milk',     // item, first element in the third array
     1.10,       // price, second element in the third array
     1           // number of items, third element in the third array
   ],
   [ // fourth entry
     'Chocolate',    // item, first element in the fourth array
     1.60,           // price, second element in the fourth array
     5               // number of items, third element in the fourth array
   ]
 ]; // end of the outer array
                      

In principle, three-dimensional arrays are also possible (i.e. arrays that contain arrays that also contain arrays) or multi-dimensional arrays.

Access to the individual values in a multidimensional array also works via the index, whereby you need several entries depending on which array in which dimension you want to access:

Complete Code - Arrays/Part_5/main.js...

 console.log(shoppingCart[0][0]); // output: Bread
 console.log(shoppingCart[0][1]); // output: 1.30
 console.log(shoppingCart[0][2]); // output: 1  
 console.log(shoppingCart[1][0]); // output: Apples
 console.log(shoppingCart[1][1]); // output: 0.20
 console.log(shoppingCart[1][2]); // output: 4
 console.log(shoppingCart[2][0]); // output: Milk
 console.log(shoppingCart[2][1]); // output: 1.10
 console.log(shoppingCart[2][2]); // output: 1
 console.log(shoppingCart[3][0]); // output: Chocolate
 console.log(shoppingCart[3][1]); // output: 1.60
 console.log(shoppingCart[3][2]); // output: 5
                      


Related links: