0

I'm trying to understand this code (check whether a string can be re-arranged to a palindrome) :

function canRearrangeToPalindrome(str){
    var letterCounts = {};
    var letter;
    var palindromeSum = 0;
    for (var i = 0; i < str.length; i++) {
        letter = str[i];
        letterCounts[letter] = letterCounts[letter] || 0;
        letterCounts[letter]++;
    }
    for (var letterCount in letterCounts) {
        palindromeSum += letterCounts[letterCount] % 2;
    }

    return palindromeSum < 2;
}

Could you explain line letterCounts[letter] = letterCounts[letter] || 0; It's outside of if statement, how can we use || ? Thank you!

Kenji Mukai
  • 599
  • 4
  • 8
Present practice
  • 601
  • 2
  • 15
  • 27
  • 1
    if there isn't a truthy value in letterCounts[letter] it will set it to 0 – Cruiser Oct 16 '17 at 15:34
  • Same as `letterCounts[letter] ? letterCounts[letter] : 0` – Iván Pérez Oct 16 '17 at 15:34
  • Here is a test script that you can run in the console: `test = [0, 1]; result = test[2] || 'This index does not exist.';` On the first line, we define `test` as an array with 2 indices. One the second line, we request the 3rd index of `test`, which doesn't exist. Since there is no value for `test[2]`, the operation returns 'This index does not exist'. – Philip Raath Oct 16 '17 at 15:42

2 Answers2

0

If the index at letter in letterCounts has a falsy value then set the value at that index to 0

Here is the MDN documentation for Falsy: https://developer.mozilla.org/en-US/docs/Glossary/Falsy

Tom O.
  • 5,730
  • 2
  • 21
  • 35
0

If letterCounts[letter] has a value it will assign that value otherwise it will assign 0.

Kenji Mukai
  • 599
  • 4
  • 8