4.14 Exercise: Proprieties of an Object
Here is a simple exercise: create a function showProperties that takes an object and prints every property whose value is a string. We'll test it on a small movie object:
const movie = {
title: 'Titanic',
releaseYear: 1997,
rating: 4.5,
director: 'James'
};
showProperties(movie);
// Expected: title Titanic and director James
// (releaseYear and rating are numbers — skipped)
Pause the video, try it on your own, then come back for the correction.
Solution with for...in and typeof
To iterate over the properties of an object, use the for...in loop. The loop variable receives the key at each iteration. To read the matching value, use bracket notation. To check its type, use typeof:
function showProperties(obj) {
for (const key in obj)
if (typeof obj[key] === 'string')
console.log(key, obj[key]);
}
for (const key in obj)walks every property name.obj[key]retrieves the matching value (bracket notation is required becausekeyis dynamic).- The
ifkeeps only string values.
Braces are omitted because each statement contains a single child instruction — the console.log belongs to the if, which belongs to the for. See you in the next demonstration.