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 image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay