If statement in array map

In this code:

str.map(function(char) {
    if (char.isPropertyOf(pairs)) {
     char = pairs[char]
  } )

Why cant you put in if statement in array map?

Nothing wrong with putting an if statement inside the map’s function. However, you have misplaced the closing parentheses and you are missing a return statement inside the function. What are trying to accomplish using map?

1 Like
arr.map(function(char) {
    if (pairs.hasOwnProperty(char)) {
     char = pairs[char]
  } } )

I am trying to convert char to pairs[char] if char is in object pairs

But why are you using map? You should be returning a value inside the map function. The map method returns a new array of values. What does arr look like before using the map method and what are you expecting the new array returned by the map method to look like?


I figured it out, thanks!!

Are you using the array returned by the map method later in your code? If not, you should be using forEach instead of map.

What did you figure out? Can you answer my last question?

I did

return arr.map(function(char) {
    if (pairs.hasOwnProperty(char)) {
     return char = pairs[char]
   else {
   return char = char
   } )

Something like that. Ya I am returning the array right away and not using it later, that was one of the issues

I recommend for ... of instead of forEach as it works better in some scenarios. Like, async code. You can find details in the link below.

Here’s the same thing in one line using ternary operator (one-line if-else).
arr.map(char => pairs.hasOwnProperty(char) ? pairs[char] : char)

Also, char = char assigns char to itself, I’m not sure this is what you wanted…
return char = pairs[char] will assign pairs[char] to char but that char variable will be destroyed when you exit the function, so char = part is redundant, you can simply use pairs[char]
Full code would be return pairs[char].

Hope it helps!

1 Like

I do not see how this comment relates to this specific case.