Now that we know basic syntax we can talk about more advanced variable types, arrays and methods. We learned in my previous post about Basic Syntax that numbers, strings and booleans are types of variables in JavaScript. However, we also have arrays and objects.
Arrays:
const cars = ['Tesla', 'Ford', 'Honda', 'Jeep'];
- list like variables
- the length and the type of elements inside an array are not fixed
- elements inside of arrays can consist of any type of variable that we have already discussed
- arrays are denoted using an open and closing square bracket []
- the elements inside of an array are separated by a comma
- elements inside of an array can be accessed using bracket notation (cars[1])
- the numbering of elements inside of an array begins at 0
Objects:
const car = {
make: 'Tesla',
model: 'Model X',
price: 71,200,
color: 'red'
};
- list of key / value pairs
- key / value pairs can consist of any elements, even functions
- objects are denoted using opening and closing curly brackets {}
- key / value pairs are denoted by stating the key then having a colon followed by the value (make: 'tesla')
- each key / value pair is separated by a comma
- key / value pairs in an object can be accessed using either dot notation (car.name) or bracket notation (car[name]), but dot notation is the standard
Now we can make it even trickier and have an array of objects. These are formatted by creating an array and each item in the array is an object made of key / value pairs.
const cars = [
{
make: 'Tesla',
model: 'Model X',
price: 71,200,
color: 'red'
},
{
make: 'Tesla',
model: 'Model S',
price: 65,000,
color: 'silver'
},
{
make: 'Tesla',
model: 'Model 3',
price: 34,200,
color: 'black'
}
];
The same properties from above still apply to an array of objects, but the way we access key / value pairs does change. To access the key / value pairs we must use dot and bracket notation. If we wanted to access the price of the Tesla Model S we would type cars[1].model. We have to use bracket notation to access the correct object in the array and dot notation to access the key / value pair inside of the second object.
These are the basics of arrays and objects! Next time we will look at array and object methods.
Until next time :)
Top comments (0)