JavaScript (ES5) Data Types
Tags: javascript, beginners
Published: 2018-11-27 13:52:41

## Declaring Variables

Before we get into the data types, lets take a look at declaring variables. A variable is a container for something - more specifically, a container for one of the data types. A variable declaration is composed of 2 or 3 parts - the `var` keyword, the name of the variable, and the value (this is optional) which is assigned to the variable with the equals sign. JavaScript is a loosely typed language, which means you don't have to declare the data type when creating a variable - the `var` keyword is used regardless of the data type.

Here are a couple examples of creating variables:

```js
var firstName = "John";
var age = 42;
var notInitialized;
```

The first two variables have a value assigned to them at the point the variables are created. This is called initialization. The third variable only creates a variable with a name of `notInitialized` but doesn't assign a value to it. The variable is available for use in the code, but until it is given a value, it's value is `undefined` - more on this later.

## Data Types

Data types handle how things are stored. In JavaScript, there are 6 data types:

- String
- Number
- Boolean
- Null
- Undefined
- Object

### String

A string is a collection of text. It could be a single character, a line of text, a paragraph, and so on. To assign a string to a variable, wrap the text in quotes, either single or double. In JavaScript, there's no real difference between single and double quotes. The only time it matters is if you're using a quote within the string. In that case, you can use the other type of quote as the wrapper or escape the quote in the string (`\"` or `\'` - backslash is the escape character). Here are a few examples.

```js
var fullName = 'John Doe';
var stringNumber = '13';
var firstLetter = 'a';
var unescapedContraction = "it's";
var escapedContraction = 'it\'s';
```

### Number

A Number is exactly what it sounds like - a number. In JavaScript, a number data type is considered a double-precision floating-point 64-bit number. For more technical details, check out [Mozilla's documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type).

Numbers can be integers or decimals, positive or negative. Here are some examples of number variables.

```js
var answer = 42;
var pi = 3.1415926;
var nothing = 0;
var negative = -18748942305;
```

An important note regarding numbers is when you assign a value, _do not_ wrap the number in quotes. If you do, it will be assigned as a string instead, which could have some unexpected consequences (especially when adding numbers). For example:

```js
var numString = '7';
var num = 82;
num + numString; // "827"
```

The plus sign is both a mathematical addition operator and a string concatenation operator. In this case, because one of the variables is a string, JavaScript interprets it as a concatenation operator instead of addition.

### Boolean

A boolean is either true or false - that's it. These are often used as flags for something.

```js
var hasPets = true;
var isPlaying = false;
```

Like numbers, don't use quotes when assigning a boolean value. Otherwise, it will be treated as a string.

### Null

A variable assigned a null value says that the variable exists, but it explicitly has no value or type. In JavaScript, null has to be explicitly set to a variable.

```js
var nullValue = null;
```

### Undefined

A variable with an undefined value means the variable exists, but it has not been assigned a value or type. This is different than null. Null explicitly assigns no value while undefined doesn't assign anything and is the default state for any uninitialized variables.

```js
var notInitialized;
console.log(notInitialized); // undefined
console.log(typeof notInitialized); // undefined
```

_Note: `typeof` is a built in JavaScript function that lets you check the data type of something. It returns the name of the data type. As a point of interest, `typeof null` returns `object` - this was a bug with the very first version of JavaScript, that has never been fixed for the sake of maintaining backwards compatibility with legacy code._

### Object

An object is a collection of properties and their values, or key/value pairs. You can think of objects like dictionaries. A dictionary is a collection of words (properties) and their definitions (values). Setting up an object is a bit different than other data types. The object itself is created using opening and closing curly braces. Inside the object, properties are created without the `var` keyword (just name them), and instead of setting values using an equals sign, values are set with a colon. Multiple properties are separated by commas.

A property's value can be any of the data types, including another object. Here are a couple examples, one empty object and one with multiple data types included.

```js
var emptyObject = {};
var person = {
  firstName: 'Jane',
  lastName: 'Doe',
  age: 27,
  hasPassport: true,
  kidsNames: ['Jackie', 'Joe', 'Julie'],
  pets: {
    numberOfDogs: 2,
    numberOfCats: 1
  }
};
```

To get a value from an object, access the properties using dot notation (i.e. object.property).

```js
console.log(person.firstName); // Jane
console.log(person.age); // 27
console.log(person.hasPassport); // true
console.log(person.pets.numberOfDogs); // 2
```

### Array

An array is a special type of object (calling `typeof` on an array returns `object`), which is why it isn't listed as a data type, but it's different enough from an object that it warrants its own section. It's more like a data container that holds a list of something. Like an object, an array can contain all different types of data. The main difference is an array is a numerically indexed list instead of a list of properties and values. When working with an array, you only give it values. An array is created using square brackets.

```js
var emptyArray = [];
var animals = ['cat', 'dog', 'owl', 'horse', 'lion'];
var mixedArray = ['John', 31, false, ['Jake', 'Jerry'], {cars: 2}];
```

To access the values in an array, use bracket notation (array[indexNumber]). Arrays are zero-indexed, meaning the first element of an array has an index of 0. Arrays have a property called `length` that returns the number of elements in an array. The length property is especially useful when accessing the last element of an array or looping through the array. Here are some examples of accessing array elements using the `mixedArray` example above.

```js
console.log(mixedArray[0]); // John
console.log(mixedArray[2]); // false
console.log(mixedArray[4].cars); // 2
console.log(mixedArray.length); // 5
console.log(mixedArray[mixedArray.length - 1]); // {cars: 2}
console.log(mixedArray[3][1]); // Jerry
```

Since arrays are zero indexed, the first element is 0 and the last element will be `array.length - 1`. In this example, mixedArray has 5 elements (a string, a number, a boolean, an array, and an object), so mixedArray.length returns 5. If you try to access mixedArray[5], you would be trying to access the sixth element of the array - this is why you need to subtract one from the length if you're trying to access the last element directly.

In the last log statement, you'll see two sets of brackets. An array inside an array is called a multi-dimensional array. For each level of depth in the array, another bracket and index is needed. In this case, `mixedArray[3]` gives us access to the ['Jake', 'Jerry'] array. Attaching the second bracket and element number (`mixedArray[3][1]`) gives us access to the value at that inner array's index of 1 - `Jerry`.