JavaScript uses function scope, meaning each function creates its own scope.
Variables defined inside a function are not accessible from outside that function.
When declared within a function, variables using var, let, and const all have function scope and behave similarly.
function myFunction() { var carName = “Volvo”; // Function Scope } |
function myFunction() { let carName = “Volvo”; // Function Scope } |
function myFunction() { const carName = “Volvo”; // Function Scope } |
A variable declared outside of a function becomes Global.
let carName = “Volvo”; // code here can use carName function myFunction() { // code here can also use carName } |
A global variable has global scope, meaning it can be accessed by all scripts and functions on a web page. |