For Loops and Objects
A for loop cannot work on an object directly, since an object is not iterable.
const car = {
speed: 100,
color: "blue"
}
for(prop of car) {
console.log(prop)
}
Running the above code snippet will throw the following error:
Uncaught TypeError: car is not iterable
Contrary to objects, arrays are iterable.
const colors = ['red','orange','yellow']
for (var color of colors) {
console.log(color);
}
This time, the output is as follows:
red
orange
yellow
Luckily, you can use the fact that a for of loop can be run on arrays to loop over objects.
Built-in methods
The Object.keys() method
The Object.keys() method receives an object as its parameter. Remember, this object is the object you want to loop over. It’s still too early to explain how you’ll loop over the object itself; for now, focus on the returned array of properties when you call the Object.keys() method.
const car = {
speed: 200,
color: "red"
}
console.log(Object.keys(car)); // ['speed','color']
The Object.values() method
For iterating the values:
const car3 = {
speed: 300,
color: "yellow"
}
console.log(Object.values(car3)); // [300, 'yellow']
The Object.entries() method
Finally, there’s another useful method, Object.entries(), which returns an array listing both the keys and the values.
const car4 = {
}
console.log(Object.entries(car4));
What gets returned from the invocation of the Object.entries() method is the following:
[ ['speed', 400], ['color', 'magenta'] ]
To loop over any object’s own property keys and values:
var clothingItem = {
price: 50,
color: 'beige',
material: 'cotton',
season: 'autumn'
}
for( const key of Object.keys(clothingItem) ) {
console.log(key, ":", clothingItem[key])
}
This produces the output below:
price : 50
color : beige
material : cotton
season : autumn
const car = {
engine: true,
steering: true,
speed: "slow"
}
const sportsCar = Object.create(car);
sportsCar.speed = "fast";
console.log("The sportsCar object: ", sportsCar);
console.log('for-in is unreliable...');
for (prop in sportsCar) {
console.log(prop);
}
console.log('for-in iterates over object and its prototype');
console.log('for-of is reliable');
for (prop of Object.keys(sportsCar)) {
console.log(prop + ": " + sportsCar[prop]);
}
console.log('for-of iterates own properties only');
for in and for of
for in and for of are ways to loop through objects and arrays.
for in loops through property names of an object.
for (variable in object) {
// execute code here
}
const posts = {
'id': 1,
'title': 'Post Title',
'body': 'Post Body'
}
for (let post in posts) {
console.log(posts[post]);
} // 1, Post Title, Post Body
for of
for (variable of iterable) {
// execute code here
}
const numbers = [1, 3, 5, 7, 9];
for (let number of numbers) {
console.log(number); //1, 3, 5, 7, 9
}
Simpler version of the car code above:
const car = {
engine: true;
}
const sportsCar = Object.create(car);
sportsCar.speed = "fast";
console.log("The sportsCar object: ", sportsCar);
for (prop in sportsCar) {
console.log(prop);
}
for (prop of Object.keys(sportsCar)) {
console.log(prop + ": " + sportsCar[prop]);
}
Template literals examples
Template literals are an alternative way of working with strings, which was introduced in the ES6 addition to the JavaScript language.
Differences between a template and regular string
There are several ways in which a template string is different from a regular string.
- First, it allows for variable interpolation:
let greet = "Hello"; let place = "World"; console.log(`${greet} ${place} !`) //display both variables using template literals - Additionally, the reason why it’s possible to interpolate variables in template literals is because this syntax actually allows for expression evaluation.
//it's possible to perform arithmetic operation inside a template literal expression console.log(`${1 + 1 + 1 + 1 + 1} stars!`)