Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

226
Visualizações
Why can't I reassign this variable inside an if statement using Javascript?

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!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The issue here is your for loop:

    for (let char in str) {
      if (char === "-") {
        isDash = true
      }
    }

The for-in loop loops over indices or keys, not values (you can test this by doing console.log(char); in the loop). Instead, use a for-of loop.

about 4 years ago · Juan Pablo Isaza Relatório

0

The issue is that you're using the for...in statement, which loops over enumerable property names of an object.

for (let char in str) {
      if (char === "-") {
        isDash = true
      }
    }

You can use for...of statement to iterate over Strings and use const if you are not going to reassign the variable inside the block.

This way:

for (const char of str) {
  if (char === "-") {
    isDash = true
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I'm fairly certain the reason for this is your use of 'let' instead of 'var'. (To be honest I hadn't seen it used before this post...).

See this article: https://www.google.com/amp/s/www.geeksforgeeks.org/difference-between-var-and-let-in-javascript/amp/

And if this fixes your issue, have a read up further on the difference s between the two.

I personally would always just use var .

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda