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

378
Visualizações
If script is running more than once, how to deal with error variable already defined?

I have a chrome extension with script as below. This script runs when user invokes the extension and it fills input field with some dummy value.

const firstNameSelector = ".input-first-name";

document.querySelector(firstNameSelector).value = "John";

It is working as expected. But if user is invoking the extension, more than once, it is failing with the error:

Identifier 'firstNameSelector' has already been declared.

So, I changed the code as below:

const firstNameSelector = firstNameSelector || ".input-first-name";

document.querySelector(firstNameSelector).value = "John";

Now it is failing with this error:

Cannot access 'firstNameSelector' before initialization.

How do I solve this situation? I feel like this is a simple problem but I am confused as how to solve this.

EDIT: I could get around this by updating script as below but is there a way where I don't need to sacrifice variable declaration and keep code tidy and clean?

document.querySelector('.input-first-name').value = "John";
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is mainly an scope problem. In js you cannot access to a variable before its declaration if the variable is declared in the same scope, that's why you got the error:

Cannot access 'firstNameSelector' before initialization.

Since you don't need the variable firstNameSelector to be global, you can enclose the fragment of code that cause the error...

Identifier 'firstNameSelector' has already been declared.

... in a separate scope, like this:

console.log(typeof firstNameSelector)

{
  const firstNameSelector = ".input-first-name";

  document.querySelector(firstNameSelector).value = "John";
}
<input class="input-first-name">

Here the curly brackets create a different scope so that the code will always be executed, and you can invoke multiple times the script without declaration errors.

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