In JavaScript, variables declared using var
are local if declared from within a function, or otherwise global. That means that a variable declared inside a function can only be accessed from within that function.
Here's an example:
var x = "Hello World";
function myFunc() {
var y = "Hi";
console.log(x); // "Hello World"
console.log(y); // "Hi"
}
console.log(x); // "Hello World"
console.log(y); // Uncaught ReferenceError: y is not defined
But once in a while, you'll find yourself having to declare a global variable from a function. How can that be achieved? Let's start by understanding how global variables work.
When you declare a global variable in JavaScript, it actually creates a property of the window object. Here's an example:
var x = "Hello World";
console.log(x); // "Hello World"
console.log(window.x); // "Hello World"
This means that to declare a global variable from a function, you can manually set it as a property of the window object, like so:
function myFunc() {
window.x = "Hello World";
}
console.log(x); // "Hello World"
Top comments (0)