Convert HTML Entities (OR operator in MAP)

Convert HTML Entities (OR operator in MAP)
0

#1

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:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities


#2

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:


#3

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.


#4

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.