DEV Community

Oskar Codes
Oskar Codes

Posted on • Edited on

3 2

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

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 
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up