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 because key is dynamic).
  • The if keeps 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.

Summary

This JavaScript exercise teaches how to create a function that displays only string-type properties from an object using a for...in loop and the typeof operator. The lesson demonstrates iterating through object keys, checking property types, and filtering results by accessing values with bracket notation.

Key points

  • Use for...in loop to iterate through all object property keys
  • Apply typeof operator to check the data type of each property value
  • Display only properties where typeof returns 'string'
  • Access property values using bracket notation: object[key]
  • Omit curly braces when an if-block contains a single statement
  • Filter object data dynamically based on type conditions

FAQ

How do you iterate through all properties of an object in JavaScript?

Use a for...in loop with the syntax: for (let key in object). Each iteration assigns the property name to the loop variable.

How do you check if an object property is a string?

Use the typeof operator combined with an if condition: if (typeof object[key] === 'string') to filter and identify string properties.

What is the difference between bracket notation and dot notation for accessing object properties?

Bracket notation object[key] is required when the property name is stored in a variable; dot notation object.key only works with literal property names.