Basic JavaScript - Using Objects for Lookups

Tell us what’s happening:
Hello everyone, please could I get help in understanding the need for looking up objects with variables?
In the code below, this access the ‘title’ property of the object Article.
Why would you bother writing

const value = “title”;
const valueLookup = article[value];

can’t you just write const valueLookup = article[“title”] ?

what is the reason for using this variable lookup?
Your code so far

const article = {
  "title": "How to create objects in JavaScript",
  "link": "https://www.freecodecamp.org/news/a-complete-guide-to-creating-objects-in-javascript-b0e2450655e8/",
  "author": "Kaashan Hussain",
  "language": "JavaScript",
  "tags": "TECHNOLOGY",
  "createdAt": "NOVEMBER 28, 2018"
};

const articleAuthor = article["author"];
const articleLink = article["link"];

const value = "title";
const valueLookup = article[value];
// Setup
function phoneticLookup(val) {
  let result = "";

  // Only change code below this line
  switch(val) {
    case "alpha":
      result = "Adams";
      break;
    case "bravo":
      result = "Boston";
      break;
    case "charlie":
      result = "Chicago";
      break;
    case "delta":
      result = "Denver";
      break;
    case "echo":
      result = "Easy";
      break;
    case "foxtrot":
      result = "Frank";
  }

  // Only change code above this line
  return result;
}

phoneticLookup("charlie");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Using Objects for Lookups

Link to the challenge:

You’re right, there’s almost no circumstance where you’d want to write this. In this case it’s simply to illustrate how the bracket notation works with variables.

However, in the phoneticLookup function you need to complete, the key is passed to you as an argument for the val parameter. You have no idea what its value will be. This means you must use bracket notation.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.