loading...

Quick JavaScript tip #2: declare global variables from a function

oskarcodes profile image Oskar Codes Updated on ・1 min read

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"

Posted on by:

oskarcodes profile

Oskar Codes

@oskarcodes

I'm Oskar, a 15 years old amateur web and game developer. I like creating websites, and desktop apps using ElectronJS, and games using Unity and PICO-8!

Discussion

markdown guide