How to use objects for lookup in JavaScript

Introduction

Objects are similar to arrays because they store data. Data can be stored in a structural way and can be represented as a real-world object.

Data stored in objects can be accessed through what is called properties, either using the dot notation" (object.propertyName)or the bracket notation (object["propertyName"]).

The switch and the if/else statement are popularly used for lookups in JavaScript but objects can be used in their stead.

Objects are most useful for lookups when we have tabular data and when we know that our data is limited to a certain range.

  • JavaScript
Console
Using Object for Lookup

Explanation

  • Line 1: We set up the function checkBestStudent with a single argument subject.
  • Line 2: We create an empty varible bestStudent.
  • Line 3: We create an object and assign it to a variable named lookup. It has 5 properties and values.
  • Line 10: We pass the function argument subject as a property name into the variable lookup which is an object. This is done using bracket notation. The result is assigned to the empty variable bestStudent. Whenever we call the checkBestStudent function with the argument, it will lookup the subject as a property in the object then assigned the value to the bestStudent variable.
  • Line 11: We log the value of the bestStudent variable to the console.
  • Line 15: We call the function with a subject name and then print the result on the console.

Free Resources