Easy

Pokemon Rating Display

Prompt

Given an object representing Pokemon ratings and a Pokemon name, write a function makeDivWithText that looks up the rating for that Pokemon and returns a <div> element with the text: "[POKEMON NAME] is rated a [POKEMON'S RATING]".

Playground

Hint 1

Use document.createElement('div') to create a new div element in memory.

Hint 2

Template literals make it easy to build the text string. Use bracket notation (obj[name]) to access the rating, since the key is stored in a variable.

Solution

Explanation

The core idea here is using the DOM API to create elements on the fly. Instead of writing HTML by hand, JavaScript lets you build elements in code and fill them with whatever content you need.

The function takes two things: an object full of Pokemon ratings, and the name of a specific Pokemon. The first thing it does is create a brand-new <div> element using document.createElement('div'). At this point, the div exists in memory but isn't on the page yet.

Next, we set the div's innerHTML using a template literal. This is where the data lookup happens:

div.innerHTML = `${name} is rated a ${obj[name]}`;

We use bracket notation here (obj[name]) because the key is stored in a variable. If you tried obj.name, JavaScript would look for a literal property called "name" on the object, which isn't what we want. This is a common trip-up in interviews, so make sure you're comfortable with when to use dot notation versus bracket notation.

Finally, we return the div so the caller can do whatever they want with it: append it to the page, inspect it, or pass it along.

Why bracket notation?

When you need to access an object property using a variable, you must use bracket notation (obj[name]). Dot notation (obj.name) would look for a literal property called "name" on the object. This distinction comes up surprisingly often in interview questions.