Why does Javascript variables have to be declared before being called while CSS variables doesn't?

For example if I have this code :

let test = "JS variables: If I'm not declared before being called, I won't work.";
document.getElementById("js").innerHTML = test;
#css {
  --test: "CSS variables: I will work even if I'm declared after being called.";
}

#css::after {
  content: var(--test);
}
<p id="css"></p>
<p id="js"></p>

It will work perfectly for both JS and CSS whereas if I have this code it will still work fine with css while producing an error in JS :

document.getElementById("js").innerHTML = test;
let test = "JS variables: If I'm not declared before being called, I won't work.";
 #css::after {
  content: var(--test);
}

#css {
  --test: "CSS variables: I will work even if I'm declared after being called.";
}
<p id="css"></p>
<p id="js"></p>

Thank you in advance for your help !

138 thoughts on “Why does Javascript variables have to be declared before being called while CSS variables doesn't?”