I am experiencing some weird behaviour that I think is scope related, but I can't explain why it's happening.
So this is the problematic piece of code. I'm trying to Camel Case some words and differentiate between text separated by dashes and underscores. Ignore the fact that the algorithm isn't completely correct yet, that's not the point. This is the stage I noticed the problem.
function toCamelCase(str){
let isDash = false
for (let char in str) {
if (char === "-") {
isDash = true
}
}
if (isDash) {
return str.split("-").map(word => word[0].toUpperCase() + word.slice(1, word.length + 1)).join("")
} else {
return str.split("_").map(word => word[0].toUpperCase() + word.slice(1, word.length + 1)).join("")
}
}
let result = "why-false"
console.log(toCamelCase(result))
So isDash determines which type of separator does the text contain. I can obviously use an arrow function instead of this approach, and it would work perfectly. Something like this:
let isDash = () => {
for (let char in str) {
if (char === "-") {
return true
}
But I can't understand why doesn't the previous example work as well. I've read about scope and it should be possible to reassign to that variable if it was defined at a higher level. Even if I defined isDash outside the function, it still didn't work. It's value always remains the initial one: false. Why isn't the if statement changing its value to true?
let x = [1, 4, 5, 7]
let txt = 0
let working = "no"
for (let i in x) {
txt += x[i]
if (txt > 4) {
working = "yes"
}
}
console.log(working)
As you can see, if I write something similar to demonstrate if it's possible to use the variable in a nested if statement, it works fine and working will log yes. What am I missing here? I would really appreciate some help, this really is a dead end to me and I wouldn't have asked for help if I could've figured it out myself. Big thanks to anyone that can explain this stuff to me!