Introduction to Javascript Arrays
An array, as with arrays in other programming languages, is a special variable, which can hold more than one value and which has members for performing common array operations.
Here’s a quick example of an array:
const cars = ["Saab", "Volvo", "BMW"];
Creating an array:
There are a couple of ways to declare an array. However, they pretty much do the same thing.
// Using an array literal
// Which is the easiest way to create a JavaScript Array
const cars = ["Saab", "Volvo", "BMW"];
// Or by using the JavaScript Keyword new
const cars = new Array("Saab", "Volvo", "BMW");
Both of these examples do exactly the same thing. There is not really a need to use new Array(). So for simplicity, readability and execution speed, just use the array literal method.
Accessing an array element:
You access an array element by referring to its index number. Like so:
const cars = ["Saab", "Volvo", "BMW"];
//Getting the first element of the array into the variable car
let car = cars[0];
// If we want to access the BMW element then
let bmw_car = cars[2]
You can simply change the value of an array element, like so:
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
// so the array will now be: ["Opel", "Volvo", "BMW"]
Array indexes start with 0. So [0] is the first element and [1] is the second element.
Note: Arrays are a special type of objects. So the typeof
operator in JavaScript returns "object" for arrays.
However, JavaScript arrays are best described as arrays.
Array properties & methods:
When it comes to arrays, there are a couple of really useful methods, like:
- array_name.length
- array_name.sort()
- array_name.push(item)
- array_name.pop()
- array_name.splice(value)
- array_name.shift()
- array_name.join(separator)
- …
Examples:
cars.length // This returns the number of elements
cars.sort() // This sorts the array
const fruits = ['Apple', 'Banana', 'Strawberry', 'Mango','Cherry'];
console.log(fruits.length); // -> returns 5
fruits.push('Orange'); // adds a new item to the end of the array
// -> ['Apple', 'Banana', 'Strawberry', 'Mango','Cherry','Orange']
fruits.pop(); // removes the last item of the array
// -> ['Apple', 'Banana', 'Strawberry', 'Mango','Cherry']
fruits.splice(2);
// truncates the array array down to just its first 2 items.
// -> ['Apple', 'Banana']
fruits.shift(); // removes the first item from the array
// -> ['Banana']
// Creating a string from an array
const cars = ["Volvo", "BMW"];
const carsString = cars.join(', ');
console.log(carString); // -> "Volvo, BMW"
Looping over Array Elements:
One way of looping through an array, is by using the for
loop. For example:
const cars = ["Opel", "Saab", "Volvo", "BMW"];
for (let i = 0; i < cars.length; i++){
console.log(cars[i]);
}
// Opel
// Saab
// Volvo
// BMW
Here’s a quick video about JavaScript arrays that you can go through:
Introduction to Javascript Objects
In real life, a car is an object that has properties like weight and color, and methods like start and stop. All cars have the same properties, but the property values differ from car to car. And they all have the same methods, but the methods are performed at different times.
And the same concept goes for JavaScript objects, which are variables that can contain many values.
For exmaple:
const car = {type:"Fiat", model:"500", color:"white"};
The values are written as name:value pairs (separated by a colon).
It is a common practice to declare objects with the const keyword.
Object creation:
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
// which is, by the way, the same as writing:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
// as spaces and line breaks are not important while defining an object.
Accessing an object’s properties:
There are a coupel of ways that you can access an object’s property:
// By using the objectName.propertyName syntax:
person.lastName;
// Or by using the objectName["propertyName"] syntax:
person["lastName"];
Looping over objects:
- Using the for…in statement:
The most straightforward way to loop through an object’s properties is by using the for...in
statement. Like so:
const user = {
name: 'John Doe',
email: 'john.doe@example.com',
age: 25,
dob: '08/02/1989',
active: true
};
for (const key in user) {
console.log(`${key}: ${user[key]}`);
}
// This will return the following results:
// name: John Doe
// email: john.doe@example.com
// age: 25
// dob: 08/02/1989
// active: true
- Using the Object.keys() method:
Another way to loop over objects is the Object.keys() method which takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys), after which, you can use any array looping method, such as forEach()
, to iterate through the array and retrieve the value of each property. Like so:
const courses = {
java: 10,
javascript: 55,
nodejs: 5,
php: 15
};
// convert object to key's array
const keys = Object.keys(courses);
console.log(keys);
// [ 'java', 'javascript', 'nodejs', 'php' ]
// iterate over object
keys.forEach((key, index) => {
console.log(`${key}: ${courses[key]}`);
});
// This will return the following results:
// java: 10
// javascript: 55
// nodejs: 5
// php: 15
- Using the Object.values() method:
The Object.values() method works opposite to that of Object.key(). It returns the values of all properties in the object as an array which you can then loop through by using any of the array looping methods. Like so:
const animals = {
tiger: 1,
cat: 2,
monkey: 3,
elephant: 4
};
// iterate over object values
Object.values(animals).forEach(val => console.log(val));
// This will then return the following results:
// 1
// 2
// 3
// 4
- Using the Object.entries() method:
The Object.entries() method can be used for traversing an array. It outputs an array of arrays, with each inner array having two elements (the first being the property and the second being the value), which you can then loop through. Like so:
const animals = {
tiger: 1,
cat: 2,
monkey: 3,
elephant: 4
};
const entries = Object.entries(animals);
console.log(entries);
// This will return the following results:
// [ [ 'tiger', 1 ],
// [ 'cat', 2 ],
// [ 'monkey', 3 ],
// [ 'elephant', 4 ] ]
// Which we can then loop through using the `for...of` loop:
for (const [key, value] of Object.entries(animals)) {
console.log(`${key}: ${value}`);
}
// or with the `forEach()` method
Object.entries(animals).forEach(([key, value]) => {
console.log(`${key}: ${value}`)
});
Updating values in objects:
When it comes to updating object values in JavaScript, there are a lot of ways that you can approach this.
For example, if you have a simple object, like so:
const user = {
name: 'John Doe',
email: 'john.doe@example.com',
age: 25,
dob: '08/02/1989',
active: true
};
// updating the user's name is as simple as:
user.name = 'new name';
//And of course, the same goes for the other properties
However, if for some reason you want to update all the values in an object, you can do so by:
1- Using the Object.keys()
method to get an array of the object’s keys.
2- Iterating over the array using the forEach()
method and update each value.
3- And after the last iteration, all the values in the object will be updated.
Like so:
const obj = {
country: 'Chile',
city: 'Santiago',
address: 'Example',
};
Object.keys(obj).forEach(key => {
obj[key] = '';
});
console.log(obj);
// This will return the following results: {country: '', city: '', address: ''}
The difference between Arrays and Objects in JavaScript, is that arrays use numbered indexes, whilst, objects use named indexes.