Convert HTML Entities (OR operator in MAP)

Hey all. Anytime i use a hint, I like to understand exactly how the solution works instead of just copying and pasting. I always go for the advanced solutions because I want to understand map, reduce and filter better. Now, in this case… I can’t for the life of me figure out why they use the OR (||) operator in the map function in this code. Can somebody explain to me whats going on there? I know it makes the problem work I just cant understand how. Thanks in advance.

function convertHTML(str) {
htmlEntities={
‘&’:’&’,
‘<’:’<’,
‘>’:’>’,
‘"’:’"’,
‘’’:"’"
};

  return str.split('').map(entity => **htmlEntities[entity] || entity**).join('');
}
convertHTML("Dolce & Gabbana");

Link to the challenge:

Sure. There are a few things going on here, and they can seem confusing.

First, let’s expand that fat arrow function, so it’s a little more readable.

.map(function(entity){ 
  return htmlEntities[entity] || entity 
} );

Yeah, that clarifies EVERYTHING! No, not really. But it’s a start. You know it’s returning something, anyway.

So what’s with the logical or operator? Well, if the first value is logical false or null (which happens if there is no member of htmlEntities with the index entity), then it simply returns entity itself.

So, to expand that even more:

.map(function(entity){
  // If the given htmlEntity exists...
  if (htmlEntities[entity]){
    return htmlEntities[entity]
  } else {
    return entity;
  }
}

But the beauty of that fat arrow is, it is WAY more succinct. :wink:

2 Likes

Thanks a lot man. Great explanation. Yeah it makes more sense when you break it down like that. I’m still trying to wrap my head around map, filter,reduce and when to use and not to use return so it threw me off.

For now, if you find it easier, simply don’t use the arrow functions. There’s no reason to, other than maintaining context.

There’s no reason you couldn’t:

let filteredArray = foo.filter(function(item){
  if(item.someValue >= someLimit){
    return false;
  } else {
    return true;
  }
}

That would be exactly the same as:

let filteredArray = foo.filter(item => item.someValue >= someLimit);

… but the first is much easier to read. As you become more comfortable with .map, .filter and .reduce, you may want to revisit and refactor your code to use fat arrows, but for the time being, they’re adding a layer of complexity and possibly keeping you from a fuller understanding.

1 Like

This is similar to:

let a = [2, 4, 6, 7, 3, 84, 43, 23, 34,  68, 53, 45, 98];
let b = a.map(num => num>40 || num);
console.log(b)

which outputs:

[2, 4, 6, 7, 3, true, true, 23, 34, true, true, true, true]

In words, in a.map() if the variable “num” is greater than 40, it returns true; else it returns the “num”.