HTML Entities Solution 3

Tell us what’s happening:
I passed this using my own code, but I try to look at the solutions once I pass a challenge so that I can learn other possible ways of writing the code. I still don’t fully understand very well. Would someone help me understand how .map(entity => htmlEntities[entity] || entity) is replacing the given symbol with its HTML entity?

I know that map loops over each item in the array that it is called on, but I’m lost at what is happening passed the arrow function.

I included the full text of solution 3 below for context.

Greatly appreciated :slight_smile:

Solution 3 code

function convertHTML(str) {
  // Use Object Lookup to declare as many HTML entities as needed.
  const htmlEntities = {
    "&": "&",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&apos;"
  //Use map function to return a filtered str with all entities changed automatically.
  return str
    .map(entity => htmlEntities[entity] || entity)

// test here
convertHTML("Dolce & Gabbana");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36.

Challenge: Convert HTML Entities

Link to the challenge:

this snippet is not included in the solution you posted

but I think there is maybe an object which have symbols and code connected in key-value pairs

htmlEntities[entity] || entity uses short circuit evaluation: if the first term is truthy, than that one is what the whole expression evaluates to, if it’s falsy, the expression evaluates to the second term

in this case, the first term is truthy if entity is a property of the object and has value of a string, and falsy if it not a property of the object and results in undefined

1 Like

I think I must have accidentally cut and paste the code instead of copy and paste.

return str
    .map(entity => htmlEntities[entity] || entity)

So map() is taking each value in the array created by split() and if that value is not a key in the htmlEntities object it simply returns the value in the array the new array it(map) creates. If it does correspond with a key in htmlEntities then it returns the value of that key as a value in the new array. Did I get that right? I hadn’t seen short circuiting before and had never considered using an OR statement in map()

it seems so

1 Like