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.
Explanation
- Line 1: We set up the function
checkBestStudentwith a single argumentsubject. - 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
subjectas a property name into the variablelookupwhich is an object. This is done using bracket notation. The result is assigned to the empty variablebestStudent. Whenever we call thecheckBestStudentfunction with the argument, it will lookup the subject as a property in the object then assigned the value to thebestStudentvariable. - Line 11: We log the value of the
bestStudentvariable to the console. - Line 15: We call the function with a subject name and then print the result on the console.