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";
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.