Reputation: 114
It is possible to global a variable inside a function, if not, how can I access a var in function b from function a.
var money;
var moneyInput = document.getElementById('input');
function check(){
if (moneyInput.value == "") {
money = 100;
}
function hit() {
document.write(money) // will this money var be 100 or undefined?
}
Upvotes: 0
Views: 87
Reputation: 3206
Just declare that variable outside function and then use it inside of that function.
P.S Please, post some code that you tried already.
let a = 5;
let b = 0; // Declare global variable
function printAB(_b) {
b = _b; // Set new value through this function
console.log(a, b);
}
function printBC() {
let c = 7;
console.log(b, c); // Get b variable
}
printBC(); // 0, 7 // b = 0
printAB(2); // 5, 2
printBC(); // 2, 7 // b = 2
With code you provided, answer is simple. Variable money
can be equal 100
or be undefined
, that depends if function hit
will be called before function check
.
Upvotes: 2
Reputation: 370
/* 1 */
var a = 'sample text';
function one() {
a = 'modified text';
}
function two() {
console.log(a);
}
one();
two();
/* 2 */
function one(callback) {
var a = 'sample text callback';
callback(a);
}
function two() {
one(function(a) {
console.log(a);
});
}
two();
/* 3 */
var one = new Promise(function(resolve, reject) {
var a = 'sample text promise';
resolve(a);
});
function two() {
one.then(function(a) {
console.log(a);
});
}
two();
/* 4 */
var myGlobals = {};
function one() {
myGlobals.a = 'sample text';
}
function two() {
console.log(myGlobals.a);
}
one();
two();
Upvotes: 1
Reputation: 2333
Declaring the variable on the outer scope and using it inside should solve your problem. However if you insist on creating a variable on the global scope you can do the following;
window.VAR_NAME = 'foo';
By doing so you are actually creating a global variable VAR_NAME
and it now has the value foo.
Upvotes: 1
Reputation: 138257
You can assign a value to the global object ( window in browsers):
function a(){
window.test="test";
}
function b(){
console.log(test);
}
a(),b();
Upvotes: 1
Reputation: 2428
Assign a variable without using var
, let
, or const
var foo = 'bar';
function fn() {
console.log(foo);
bar = 'xyz';
}
fn()
console.log(bar)
Repl: https://repl.it/languages/javascript
Upvotes: 1
Reputation: 67
You should declare the variable outside of the function scope:
var myGlobalVar = "foo";
function a(){
var myLocalVar = 'bar';
alert(myGlobalVar); //shows foo
alert(myLocalVar); //shows bar
}
function b(){
var myLocalVar = 'baz';
alert(myGlobalVar); //shows foo too
alert(myLocalVar); //shows baz
}
Upvotes: 1
Reputation: 9782
If you assign a value to an undeclared variable in a function it will be created as a global variable.
Upvotes: 1