Below is a trivialized version of a solution I came across while trying to implement a version of the Jquery CSS function.
function CSS(prop, value) {
...
if (value === undefined) {
// No matching elements.
if (element == null) {
return undefined;
}
const value = element.style[prop]; // <-- Why is this allowed?
return value === "" ? undefined : value;
}
...
}
I noticed that the function param value
was being redeclared and automatically raised an eyebrow to the solution. I threw it in a code sandbox and it worked. I checked the docs and found exactly what I expected:
“Redeclaring the same variable within the same function or block scope using let is not allowed in JavaScript.”
Now this specified let
but even chaging to that still works.
If I bring the declaration out of the if statement, I get the duplicate error I’d expect so this clearly has to do with the block scope of the if statement. However, because it inherits the function scope outside of that which includes a variable of the same name a redeclartion should be illegal still, no?
What am I missing?
1
This works because let and const do allow you to redeclare variables/constants in nested blocks of code. They are treated like different variables so as soon as you exit that if statement, value
will refer to the function parameter again with whatever value it had. The redeclared variable will go out of scope.
Look at this modified version of your code:
function CSS(prop, value) {
const element = document.getElementById('#someElement');
// assigning i here
let i = 1;
if(value === undefined) {
// this works
let i = 2;
if (element == null) {
return undefined;
}
const value = element.style[prop];
return value === "" ? undefined : value;
} else {
// this still works
const i = 3;
}
// i === 1 here
console.log(i);
}
Note how i
is equal to 1 at the end since the only time it was set (in that scope) was before the if statement.
Obviously, this is odd behaviour and it makes for code that’s difficult to read, so you should avoid it.
2