JavaScript Data Types

Intro

JavaScript offers a few primitive data types:

JavaScript also provides two compound data types: Objects and Arrays.

var myObj = {iAmAwesome: true};
console.log(myObj.iAmAwesome) // true

This only works if the key is a string with no spaces, dashes (-), or other special characters in it - basically, the string has to be just like a variable. If it is any other data type, you have to use square brackets after the variable to access it:

var myObj = {"this is my key": true, "this-is-my-key":true, "this_is'nt_my_key"};
myObj.this is my key // Throws an error
myObj.this-is-my-key // Throws an error
myObj.this_is'nt_my_key // Throws an error
myObj["this_is'nt_my_key"] // Works!

As mentioned, you can use objects as values in your object. You can access nested values with periods:

var myObj = {transportation: {car: 1, bus: 5, bike: 3}}
console.log(myObj.transportation.car) // Outputs 1

// Be careful not to look for values that don't exist:
console.log(myObj.music.rock) // Error: undefined is not an object

// This doesn't work because you first try to access myObj.music, which is undefined. You cannot then access myObj.music.rock because myObj.music doesn't exist in the first place!
var myArray = [1,2,3];
console.log(myArray[1]) // 2

Arrays have a property called .length which tells you the number of items the array has.

Arrays have methods which allow you to read and manipulate the data inside of them:

var myArray = [1,2,3];
myArray.push('🏆');
console.log(myArray) // [1,2,3,"🏆"]
var lastItem = myArray.pop() // lastItem now equals "🏆"
console.log(myArray) // [1,2,3]
var firstItem = myArray.shift() // firstItem now equals 1;
console.log(myArray) // [2,3]
myArray.unshift('🍩');
console.log(myArray) // ['🍩',2,3]
var myArray = ["a","b","c"];
var index = myArray.indexOf("c"); // 2, since the index starts at 0
myArray[index] // "c" - the item at index 2 of the array;

There’s one more type you need to know:

function sayHi() {
  console.log('Hi');
}
sayHi.personName = "Alex";
sayHi.personName // returns 'Alex'

You can also put Functions inside of Arrays, Objects, and even use functions as arguments of another function!

function add(a, b){
  return a + b;
}
function multiply(a, b) {
  return a * b;
}
function operate(a, b, func) {
  return func(a, b);
}
operate(5, 6, add) // Returns 11
operate(5, 6, multiply) // Returns 30

JavaScript also provides a number of operators for comparing and combining different data types. Those operators are listed in the suggested learning below.

Suggested Learning

Requirements

Extra Learning

This list is by no means complete. Feel free to add an issue or put in a pull request to update it.