Define a Global Variable in a JavaScript Function

Define a global variable in a JavaScript function

As the others have said, you can use var at global scope (outside of all functions and modules) to declare a global variable:

<script>
var yourGlobalVariable;
function foo() {
// ...
}
</script>

(Note that that's only true at global scope. If that code were in a module — <script type="module">...</script> — it wouldn't be at global scope, so that wouldn't create a global.)

Alternatively:

In modern environments, you can assign to a property on the object that globalThis refers to (globalThis was added in ES2020):

<script>
function foo() {
globalThis.yourGlobalVariable = ...;
}
</script>

On browsers, you can do the same thing with the global called window:

<script>
function foo() {
window.yourGlobalVariable = ...;
}
</script>

...because in browsers, all global variables global variables declared with var are properties of the window object. (In the latest specification, ECMAScript 2015, the new let, const, and class statements at global scope create globals that aren't properties of the global object; a new concept in ES2015.)

(There's also the horror of implicit globals, but don't do it on purpose and do your best to avoid doing it by accident, perhaps by using ES5's "use strict".)

All that said: I'd avoid global variables if you possibly can (and you almost certainly can). As I mentioned, they end up being properties of window, and window is already plenty crowded enough what with all elements with an id (and many with just a name) being dumped in it (and regardless that upcoming specification, IE dumps just about anything with a name on there).

Instead, in modern environments, use modules:

<script type="module">
let yourVariable = 42;
// ...
</script>

The top level code in a module is at module scope, not global scope, so that creates a variable that all of the code in that module can see, but that isn't global.

In obsolete environments without module support, wrap your code in a scoping function and use variables local to that scoping function, and make your other functions closures within it:

<script>
(function() { // Begin scoping function
var yourGlobalVariable; // Global to your code, invisible outside the scoping function
function foo() {
// ...
}
})(); // End scoping function
</script>

Creating global variables inside function - why does this work?

Afaik, variables declared inside a function are local variables (using var keyword or not).

Variables declared inside a function are local, but you are not declaring any variables. What you have is what's known as an "implicit global" and it only works in "sloppy mode".

From MDN:

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.

In strict mode, your code produces an error:

"use strict";

function func1() {

x = 5;

}

function func2() {

document.write(x);

}

func1();

func2();

Can't access global variables inside a function (Javascript)

that is because you are fetching the value before the user enters anything, because the input data is fetched once script starts running

How to declare a global variable in JavaScript

If you have to generate global variables in production code (which should be avoided) always declare them explicitly:

window.globalVar = "This is global!";

While it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name), doing so generates an implicit global, which is a bad thing to do and would generate an error in strict mode.

How do I change the value of a global variable inside of a function

Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.

You can override this behaviour by declaring it locally using var, but if you don't use var, then a variable name used in a function will be global if that variable has been declared globally.

That's why it's considered best practice to always declare your variables explicitly with var. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.

Is it possible to make global Variable in JAVASCRIPT?

Within the global scope (aka "window"), variables are global.

Check this out:

//this is global because it is in the global scope (the window)
var foo = 'stuff';
//because it is global (window) you can also access it like this:
console.log(window.foo); //'stuff'

Now you can access foo anywhere. It's worth noting that globals aren't best practice - so check out Object Oriented Programming (SOLID principles).

If you are within another scope (like a function) and don't use the var keyword to create a variable, the variable will be global:

function someFunction() {
someVariable = 'stuff'; //this created a global variable! (or references an existing one)
//you could also assign it to window:
window.someVariable = 'stuff';
//both are the same thing!
}

Inline js (onclick in your html) is not a good practice. Instead, you can follow the good practice and use javascript to register the click event:

//get reference to button
var myBtn = document.getElementById('myBtn');

//add click function
myBtn.addEventListener('click', function(event) {
myFunction();
});

function myFunction() {
console.log(foo); //'stuff'
}

Here's a demo of all of this: http://jsbin.com/OmUBECaw/1/edit

Just note that you'll need to get the element references after they are loaded into the dom. It's best practice to include your scripts just before the end of the body rather than in the head, like this:

  <!-- scripts here! -->
<script></script>
</body>

If you must keep the scripts in the head, then you'll need to put your javascript code in a function to run onload of the window:

window.addEventListener('load', function() {
//code here!
});

javascript - setting global variables inside a function

Javascript is pass-by-value. (Objects, arrays, and other non-primitives are passed by value-of-reference.) That means that the value of the variable (or reference) is passed to the function, but the function parameter does not become an alias for the actual argument. Thus, you cannot change a variable outside a function without referencing it (as you do in your last example).

See this answer in another thread for more information.



Related Topics



Leave a reply



Submit