Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

368
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda