JavaScript · JS Tutorial · Lesson 37
JS Scope
Global, function and block scope.
Scope determines the accessibility (visibility) of variables. JavaScript has global scope, function scope and block scope.
Example
<p id="demo"></p>
<script>
let carName = "Volvo"; // global
function myFunction() {
let inside = "Saab"; // function scope
return carName + " is visible inside, and so is " + inside;
}
{
let blockVar = "only in this block";
}
document.getElementById("demo").innerHTML =
myFunction() + "<br>typeof inside outside: " + typeof inside + "<br>typeof blockVar outside: " + typeof blockVar;
</script>
Tip: Avoid global variables where possible — they can be overwritten by other scripts.
Keep reading “JS Scope”
Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.