Prep Day Two Prep Day Three Prep Day Four
In the variables section, we learned about three simple data types in JavaScript: Strings, Numbers, and Booleans. These types of data are simple because:
- They have a definite size when stored in memory
- They cannot store or collect other values besides themselves.
For instance, let's say I want to create a variable age that stores the Number value of 24. It would be impossible to add in a string inside the number value of 24.
The following code would generate an error in JavaScript
var age = 24 “Is my age”;var error = 2 “then comes” 4;The following code would generate an error in JavaScript because Strings cannot be stored within Numbers or Booleans and vice-versa because they are simple data types.
However, there exists a way to store multiple types and values of data within one value. These values are referred to as collections in JavaScript and they consist of two data types: Arrays and Objects.
Collections are a very important construct because they allow us to group values together so they can be passed and used as one. We’ll discuss the difference between Arrays and Objects and their usage below.
An Array is a zero indexed list. A collection that allows us to store a list of values of any data type, and store them as one variable. Below, we provide examples of how to create a literal Array in JavaScript.
/* Empty Array literal */
var arrayLiteral = [];
/* Array literal with one element, the Number 1 */
var arrayWithElement = [1];
/* Array literal with three elements, Numbers 1, 2, 3
var arrayWith3Elements = [1, 2, 3];
/* Array literal with elements of different data types */
var arrayWithMultipleDataTypes = ['John', 'Max', 'Aaron', 'Maggie', true, 748]
/* Array literal stored to variable 'myArray' */
var myArray = [25, 30, 45, 40];
/* Array literal stored to variable 'kitchenSink' that has elements each of a different data type */
var kitchenSink = [ 11, 'Ali', false, [1, 2] ];As shown above, to create a literal Array in JavaScript, you'll begin with square brackets []. Inside those square brackets, you'll begin to list your data, separated by commas. You can insert as many values as you'd like! Lastly, you'll assign your Array a variable, and give it a name that relates to the values stored within.
Arrays are Complex
Arrays are a complex data type because they can hold or collect other values, including other Arrays. In JavaScript, we refer to an Array as a collection because it collects other values.
Now you've learned how to create a literal Array in JavaScript,
But what exactly does "zero indexed" mean?
Values in an Array, referred to as elements, are stored in a particular order. This order is maintained by assigning each element in an Array a Number, which is referred to as the element's index.
Arrays begin indexing at 0. The first element in an Array will always have the index 0, the second 1, the third 2, and so on and so forth. You can use these indexes to access elements within the Array.
Let's consider the array userAges below.
var userAges = [15, 24, 23, 22, 45, 35, 21];The first element, 15, has the index 0. The second element, 24, has the index 1. This pattern will continue until the last element in the Array, which in this case is the 7th element, 21, with the index 6.
Let's say in our program we wanted to access certain elements within our Array without using the whole value. For instance, say we just needed the first element in the userAges Array, and didn't, at the moment, need the others.
For instances like this, you'd use bracket notation in order to access each particular item inside an Array.
var userAges = [22, 24, 27, 30]
userAges[0]; /* Accesses first element in 'userAges' Array → 22 */
userAges[1]; /* Accesses second element in 'userAges' Array → 24 */
userAges[2]; /* Accesses third element in 'userAges' Array → 27*/
userAges[userAges.length - 1]; /* Will always access the last element in the 'userAges' Array → 30 */To access an element using bracket notation, you begin with the Array name, followed by brackets, which inside have the index of the element you'd like to access.
The first element of any Array of any size will always have the index [0], and the last element the index of arrayName.length - 1.
Similarly to its use on strings, .length used on an Array will give us back the number of elements in an Array. This number will also represent the index of the last element in that Array - but there is just one problem. Arrays begin indexing at 0, while .length begins counting at 1. This is why we need to subtract one from the length to get the number of the index of the last Array element.
Like an Array, an Object is another type of JavaScript collection. However, unlike an Array, values inside an Object are not ordered, nor do they have an index.
An Object is a collection of key-value pairs. Like the index of an Array, which represents the position of an element in an Array, you can think of the key as the position of a value in an Object. Below, we'll provide examples of how to create Object literals in JavaScript.
var emptyObject = {} /* Empty Object Literal */
var objectWithOneKeyVal = { name: ‘Selina’ } /* Object with one key / value pair where the key is ‘name’ and the value is ‘Selina’ */
var objectWith2KeyValPairs = {name: ‘Selina’, age: 2, } /* Object literal with two key / value pairs */
var myCat = { /* Object literal stored to variable ‘myCat’ with multiple key-value pairs of different types */
name: 'Selina',
age: 2,
address: '748 Camp St',
isHuman: false,
} As shown above, to create an object literal in JavaScript, you'll begin with curly braces {}.
Inside those braces, you'll begin to list your properties, separated by commas. Each property will consist of a key - value pair, where the key acts like a label for the value you would like to store. You can insert as many properties as you'd like! Lastly, you'll assign your object a variable, and give it a name that relates to the properties stored within.
Objects are Complex Similar to Arrays, Objects are complex data types because they can hold or collect other values, including other Objects. In JavaScript, we abstractly refer to an Object as a collection because it collects other values.
We can refer to Objects as associative Arrays because there is, and should be, an association between the key and the value stored at that key. For example:
var user = {
nameFirst: 'Maddy',
nameLast: 'LeChat'
}Above, there is an association between the key nameFirst and the value it points to, which is Maddy. You would not put the last name, LeChat at the key nameFirst because there is no association between nameFirst and someone's last name. The index of a value in an Array, on the other hand, really has no association with the value to which it points. It only refers to the order in which it exists inside the Array.
There are two ways we can access the values of our properties in our Object: dot notation and bracket notation. Consider the Object below:
var user = {
firstName: 'Selina',
lastName: 'LeChat',
age: 15,
isAdult: false,
}Let's say I wanted to access the values from our object using dot notation. We’d use the following syntax to do so:
user.firstName;
user.lastName;
user.age;
user.isAdult;To use dot notation, we begin with the name of the object, followed by a period or ‘dot’, then the key of the value you want to access. Similarly, you can use bracket notation to access object values, like so:
user['firstName'];
user['lastName'];
user['age'];
user['isAdult'];Similar to dot notation, in order to access elements using bracket notation, you begin with the name of the Object, followed by brackets []. Inside the brackets, you'll enter the key of the value you want to access, surrounded by quotes ' '.
Wait a minute... isn't bracket notation for Arrays?
We can use bracket notation to access Object elements because Object keys are actually Strings! Therefore, we can use keys in bracket notation by giving the key as a String.
We can also store keys in variables as Strings, like shown:
var key = 'firstName';
console.log(user[key]) // prints 'Selina' JavaScript gives us the ability to create properties for our Objects after we've created them. We can simply use either dot or bracket notation to create new properties like this:
var dog = {
Name: 'Fido',
Age: 7,
}
dog.breed = 'Shiba Inu'; // adds the property 'breed' with a value of 'Shiba inu' to the dog Object
dog['gender'] = 'male'; // adds the property 'gender' with a value of 'male' to the dog ObjectThe following hints and resources should aid you in your completion of the code exercises.
Store Multiple Values in an Array
- Refer to this website: freeCodeCamp store Multiple Values help
Nest One Array within Another Array
- Refer to this website: JavaScript Nested Array
Access Array Data with Indexes
- Refer to this article: Accessing Arrays Contents
- Refer to this video: Youtube - Access Array Data
- Arrays are one-dimensional; that means they store only one row of data.
- You can make an array multidimensional by putting arrays inside arrays! Like so:
var arr = [["Two-dimensional", 2], ["Two rows", 12]];
//This array has two dimensions.Accessing Object Properties Dot Notation
- Refer to this website: Codeburst - Dot Notation
- Syntax for bracket notation is objectName[key]
Using .splice()
- Refer to the syntax section on this site: .splice() method
Using .split()
- Refer to this website: .split() method
Accessing Nested Objects
- Refer to this website: Accessing Nested Objects
- Refer to this website: How to Access Nested Objects in JavaScript Dynamically
- Make sure you use double quotes inside of the brackets when using bracket notation
Bracket Notation with Objects
- Refer to this website: Object Bracket Notation
Object Access with Variables
- Refer to this website: How to Dynamically Access Object Property Using Variable in JavaScript
Using Objects for Lookup
- Refer to this website: W3Schools - Object definition
- Your solution should be an object.
Object.keys
- Refer to this website: Object.keys() method
- Refer to this website: Return
Creating Object Method with Dot Notation
- Refer to this website: Object Basics
- Refer to this website: Object Syntax in JavaScript