Variables declared globally (outside of any function) have global scope.
Global variables can be accessed from anywhere in a JavaScript program.
When declared outside a block, variables using var, let, and const behave similarly, as they all have global scope.
They all possess global scope.
var x = 2; // Global scope |
let x = 2; // Global scope |
const x = 2; // Global scope |
In JavaScript, objects and functions are considered types of variables as well.
Scope defines the visibility and accessibility of variables, objects, and functions within different parts of the code. |
If you assign a value to a variable that hasn’t been declared, it will automatically become a GLOBAL variable.
In this example, the carName variable will be declared globally, even if the assignment occurs inside a function.
myFunction(); // code here can use carName function myFunction() { carName = “Volvo”; } |