0
    function strChck(str) {
  //str in each char how many repeated
  let charmap = {};
  for (char of str.replace(/[^\w]/g, '').toLowerCase()) {
    console.log(charmap[char]);
    charmap[char] = charmap[char] + 1 || 1;
  }
  return charmap;
}

Hi guys I want to understand that code for > charmap[char] = charmap[char] + 1 || 1;

how the code made object value like {m:4} as m charcter is repeated in string for 4 times ? > can't understand the value how it be nummber and be increased , my brain said it should be m+1 ?

7usien
  • 83
  • 7
  • What do you mean by _β€œit should be m+1”_? _What_ should be m+1? What is m+1 supposed to be? – Sebastian Simon Jan 15 '23 at 21:33
  • 2
    The trick here is that if `charmap[char]` is not set it will return `undefined`. `undefined + 1` is `NaN` which is falsy, therefore `NaN || 1` is `1`. So `charmap[char]` will either be initialized with `1` when `charmap[char]` is *not* already set or its value will be increased by `1`. Since the code iterates over every character in the string this essentially counts the occurrences of every character. – Felix Kling Jan 15 '23 at 21:33

0 Answers0