You can use if statement or ternary operator to use JavaScript variable in HTML. Ternary expressions will always return the first value if true, the second value if not.
var B = (A ==="red") ? "hot":"cool";
Great for one-off if/else statements, but if you get into more nested conditions, be sure to use the traditional if/else blocks for readability.
Use JavaScript variable in HTML if the condition
Simple example code.
<!DOCTYPE html>
<html>
<head>
<script>
var color = "red";
var B = (color ==="red") ? "hot":"cool";
</script>
</head>
<body>
<script>
document.write(B)
</script>
</body>
</html>
Output:
Using if condition
Initialize your variables first, then compare using the if statement and assign new values where necessary.
<script>
var color = "red";
var b;
if(color=="red"){
b="hot";
}
else{
b="cold";
}
</script>
Do comment if you have any doubts or suggestions on this JS variable with the condition code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version