I have the following code which sets the color variable and then constructs the table data background color based on that variable . no issues with it .. BUT .. when I try to reassign another color value the same variable its not taking effect. with the conole.log option i can see that the condition value is correctly detected as "OFF" but I am not understanding why the variable is not taking the value of 'red'
let themeOptions = {
color_variable: '#00FF00'
}
get(child(dbref, "Sensor"))
.then((snapshot) => {
snapshot.forEach((child) => {
let table = document.querySelector('table');
if (child.val().Status == "OFF") {
console.log(child.val().Status); // it prints the value "OFF"
let themeOptions = {
color_variable: 'red'
}
}
let template = `
<tr>
<td bgcolor="${themeOptions.color_variable}">${"pump" child.val().PumpID}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().StartTime}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().Duration}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().GalsPumped}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().Cycle}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().Status}</td>
</tr>`;
table.innerHTML = template;
})
});
CodePudding user response:
When you declare a variable with let
or const
, its scope is the closest enclosing block. This means your reassigned themeOptions
is not in scope when you assign to template
outside the if
block.
If you want to redefine the global variable, remove the let
declaration. But it would probably be more appropriate to just assign to the specific property.
if (child.val().Status == "OFF") {
console.log(child.val().Status); // it prints the value "OFF"
themeOptions.color_variable = "red";
}
CodePudding user response:
It is not possible to redefine a variable already declared
// Wrong
let themeOptions = {
color_variable: '#00FF00'
}
let themeOptions = {
color_variable: 'red'
}
Instead, just modify the property you want to update:
/* Correct */
let themeOptions = {
color_variable: '#00FF00'
}
themeOptions.color_variable = 'red';