Javascript data types

What kind of values can we assign to a variable?

Well, there are multiple possibilities:

  • What we call “primitive data types”: for example a number, a string, etc. ex: 
    var x = 3; var name = “Buffa”;
  • Objects (everything that is not a  “primitive data type” is an object): 
    var michel = {firstName:’Michel’, lastName:’Buffa’};
    • There is a set of “predefined objects” in JavaScript (arrays, functions, etc). We will come back on these later in the course.

JavaScript has a small set of primitive data types

  1. number: 1,2,105,3.14 …
  2. string: ‘a’, “one”, ‘two’ , ‘World Wide Web’ …
  3. boolean: true / false
  4. undefined: absent or unknown value
  5. null: special keyword, meaning no value or empty. The difference from undefined is that when a variable is null, it is still defined.

These are the simplest forms of data we can use in programming.

Anything that is not listed above is an object (JavaScript objects are covered later in Week 3). 

You said JavaScript does not have types for variables?

No! I said that JavaScript is weakly typed; you do not declare the type of variable. In some other languages (Java language syntax, for instance) instead of var x=2; or let name=”Buffa”; you would write int x=2; or String name = “Buffa”;, with the datatype explicit in the variable declaration.

Knowing the type of a JavaScript variable: the typeof operator

The next section of the course talks about “operators” but there is one that is better introduced in this section: the typeof operator, that is useful for knowing the type of a variable depending in its value (possible values: number, string, boolean, undefined, object, or function)

Numbers

+, – , /*% (modulo)

And there are also unary operators:

++, — (the opposite of a number)

++ and  operators increment or decrement the value of a variable. They can be both prefixed or suffixed, which have different effects:

  • Suffixed ++ adds one to the value of the variable, then returns the old value.
  • Prefixed ++ also adds one to the value, but returns the new value. Both of these must be used with variables.

JS operators en expressions

Number operators

Strings
Om een string te verklaren/declaren gebruik je single ‘stringName’ of dubbele aanhalingstekens “StringName”. Het maakt in principe niet uit welke je gebruikt. Wees wel consistent want als je ze doorelkaar gebruikt krijg je een foutmelding;
#Aangeraden wordt de enkele ‘

  • Het kost minder tijd want voor de dubbele aanhalingstekens moet je ook de Shift ingedrukt houden
  • Dubbele aanhalingstekens worden ook gebruikt in HTML
  • Het is makkelijker te lezen
Snapshot of a devtool console: do not mix simple and double quotes

String operators

Objects

  • They are declared using “{” and “}”, such as in var p = {givenName:’Michel’, familyName: ‘Buffa’}, givenNameand familyName are called “properties” and Michel and Buffa are their respective values.
  • We are using the “.” operator to access their properties or methods. Example : daysOfTheWeek.length (arrays are objects too – special ones, but objects), or document.body or window.innerWidth (try typing that in the devtool console). There are plenty of predefined objects in JavaScript (window, document, navigator, etc.). We have also used console.log(…), and indeed console is a predefined JavaScript object. With the object var p = {givenName:’Michel’, familyName: ‘Buffa’}, we can access the properties the same way, with: p.givenName and p.familyName.

    In je browser (zie F12 console) zijn al bepaalde objecten voorgedifinieerd. Een paar voorbeelden;
  • navigator /
    window.vendor > Geeft het merk van je browser weer (bv. Chrome)
  • document / document.bodyLaat de body van je pagina zien
  • window / window.innerWidth > geeft de waarden van de grootte van je browser weer.

Arrays

Definition: arrays are containers with indexes 

Arrays are a special datatype. You declare arrays using brackets, like this:

  1. var daysOfWeek = [];

You can fill them at declaration time:

  1. var daysOfWeek = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Sunday’];
  2. var gradesInMaths = [12, 7, 14, 18, 9, 11];

Elements in an array can be accessed using indexes

Each element in an array has an index. The first element’s index is 0, the second element’s index is 1 etc.

To access an element, you use the array variable and “[” followed by the index value followed by “]”, as shown in these examples:

  1. > var daysOfWeek = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Sunday’];
  2. undefined
  3. > daysOfWeek[0]
  4. “Monday”
  5. > daysOfWeek[1]
  6. “Tuesday”
  7. > daysOfWeek[2]
  8. “Wednesday”
  9. > daysOfWeek.length
  10. 7

Use the length property of an array to know its length

  1. > var daysOfWeek = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’,’Friday’, ‘Saturday’, ‘Sunday’];
  2. undefined
  3. > daysOfWeek.length
  4. 7

Indeed, there are seven days in a week and the daysOfWeek array has seven elements, indexed from 0 to daysOfWeek.length -1

This way of enumerating all elements (from 0 to the length of the array -1) is very, very common, and will prove to be very useful when you learn how to iterate on an array’s elements (Week 2).

You can add elements to an array using a new index

If you want to add a new element at the end of an array, use the index equal to the length of the array

  1. > var daysOfWeek = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’];
  2. undefined
  3. > daysOfWeek.length
  4. 6
  5. > daysOfWeek[6]
  6. undefined
  7. // NO ELEMENT AT INDEX 6 in an array of 6 elements, first index is 0 // last 6-1 = 5
  8. > daysOfWeek[6] = ‘Sunday’
  9. “Sunday”
  10. > daysOfWeek.length
  11. 7
  12. // Sunday, the 7th day of week is at index 6 !

Arrays are JavaScript objects!

Well, this is not so important for the moment, but look:

  1. > var a = [];
  2. typeof a;
  3. “object”
  4. > var a = [1,2,3];
  5. > a
  6. [1, 2, 3]
  7. > a[0]
  8. 1
  9. > a[1]
  10. 2

And indeed, when you write daysOfWeek.length, you are using the array as an object, and you are using the length property of array objects.

Add an element at the end of an array using the push method

Since arrays are objects, we can do much more with them – in particular, they have more properties and more methods than the push method. You will learn more about this in a later lesson (Arrays part 2), but for the moment, let’s focus on the most useful features…

  1. > var daysOfWeek = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’];
  2. undefined
  3. > daysOfWeek.length
  4. 6
  5. > daysOfWeek.push(‘Sunday’);
  6. 7
  7. > daysOfWeek
  8. [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”]
  9. > daysOfWeek.length
  10. 7

Arrays and Strings

Strings are arrays of characters! 

Consequence:

  1. They are objects too! 
  2. They have a length property,
  3. Each individual character can be accessed using an index.

Examples:

  1. > var s = ‘one’;
  2. > s[0]
  3. “o”
  4. > s[1];
  5. “n”
  6. > s[2];
  7. “e”
  8. > s.length;
  9. 3

Functions

Een functie gebruik je om een de code te Groeperen. Zodra je het een naam geeft kan je de code later oproepen. Functions geven altijd een ‘waarde‘ terug;

Functions with a variable number of parameters

An array named “arguments” is created automatically in each function, it contains all the call parameters of the function:

Declaring a function

  1. function sum(a, b) {
  2.     var c = a + b;
  3.     return c;
  4. }

Calling a function

  1. var result = sum(1, 2);
  2. //result is equal to 3
  3. console.log(result)
  4. > 3