I am a very beginner JS "developer" (student) and I have run into a question I haven't been able to solve: why does the value of the repeated letters in my 'helperHash' increase when I am not using an else statement and why this same value DOESN't increase if I use an else statement? My code runs as expected but I am having problems understanding the logic behind this issue...
The code is supposed to return an array with the letters that have 1 or more repetitions in the given str.
function nonUniqueLetters(str){
var strToChars = str.split('');
var finalArr = [];
var helperHash = {};
for (let i = 0; i < strToChars.length; i += 1){
let char = str[i];
if (!helperHash[char]){
helperHash[char] = 0;
}
helperHash[char] += 1; //HERE! why doesn't this work if inside an else?
}
for (var key in helperHash){
if (helperHash[key] > 1){
finalArr.push(key);
}
}
return finalArr;
}
For helperHash[char]
…
The initial value is undefined
and !undefined
is true
so it sets the value to 0
.
The next time char
has the same value, helperHash[char]
is 0
and !0
is also true
so it sets the value to 0
(which it already is, so it makes no difference).
Instead of testing if the value is a false value, test if it is undefined, or if it exists at all.
if (typeof helperHash[char] === "undefined")
or
if (char in helperHash)
The reason is this if (!helperHash[char]){
and how integers are converted to booleans in Javascript.
You initialize every member of the hash to 0 which equals a boolean false, so the else is never hit because helperHash[char] === 0 === false
and thus !helperHash[char]
is true for all values initialized with 0
Logic error.
if (!helperHash[char]){
// Enters here only when helperHash[char] is not set (or 0, but it is never 0)
helperHash[char] = 0;
}
// Always increment
helperHash[char] += 1;
// There is no 0 in helperHash at this point
helperHash[char] += 1
in an else
branch doesn't work: if (!helperHash[char]){
// Enters here only when helperHash[char] is not set or 0
helperHash[char] = 0;
// Still 0, will take this branch again on the next occurrence of char
} else {
// Increment only if it was already 1 or more (this never happens)
helperHash[char] += 1;
}
// Here helperHash contains only 0 for all keys
if (!helperHash[char]){
// This is the first occurrence of char, let's count it
helperHash[char] = 1;
} else {
// This is a subsequent occurrence of char, let's count it too
helperHash[char] += 1;
}
// There is no 0 in helperHash at this point
Your if
condition:
!helperHash[char]
is always evaluating to true
( helperHash
never has characters in it that are "falsy"). So, an else
branch of that if
would never be hit.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.