user7104874
user7104874

Reputation: 1381

Unable to access global variable in javascript

As per me, every variable declared in javascript above functions treat as global. But in my case, i unable to access that variable show undefined. Here is jsfiddle

code:

__getUserByRmId('sun1')
var firstCallFlag = 1;
function __getUserByRmId(rmId) {
    console.log(firstCallFlag); 
}

Upvotes: 1

Views: 2433

Answers (5)

Anurag
Anurag

Reputation: 743

var firstCallFlag = 1;
function __getUserByRmId(rmId) {
    console.log(firstCallFlag); 
}
__getUserByRmId('sun1');

Its beacuse you have to define the variable "firstCallFlag " first and then call the function __getUserByRmId('sun1');....variable hoisting in javascript

Upvotes: 1

Piyush
Piyush

Reputation: 1162

This is because the variable is defined after the function is called.

You can do this. It will work.

var firstCallFlag = 1;
__getUserByRmId('sun1')

function __getUserByRmId(rmId) {
    console.log(firstCallFlag); 
}

By the way, hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope. So, something like this should work.

 firstCallFlag =1 ;
__getUserByRmId('sun1')

function __getUserByRmId(rmId) {
    console.log(firstCallFlag); 
}
var firstCallFlag;

However, JavaScript Initializations are Not Hoisted. Thus, the code like below will consider the variable firstCallFlag undefined.

__getUserByRmId('sun1')

function __getUserByRmId(rmId) {
    console.log(firstCallFlag); 
}
var firstCallFlag = 1; 

Upvotes: 3

Suren Srapyan
Suren Srapyan

Reputation: 68635

There is a term function and variable hoisting. When you create a function like that and a variable with var, they moved to the top of of all. But the functions are hoisted first before variables. So when you call the function, it sees the function , but doesn't see the variable.

Engine parses your code to this and executes line by line. So it doesn't see the variable.

function __getUserByRmId(rmId) {
    console.log(firstCallFlag); 
}

__getUserByRmId('sun1')

var firstCallFlag = 1;

You need to call your function after the variable declaration

var firstCallFlag = 1;

__getUserByRmId('sun1');

function __getUserByRmId(rmId) {
    console.log(firstCallFlag); 
}        

Upvotes: 3

Mithun Shreevatsa
Mithun Shreevatsa

Reputation: 3599

If you still want to work with the same pattern of approach without declaring the variable on top of function call, then you should have a timeout call like this:

_getUserByRmId('sun1');

var firstCallFlag = 1;

function __getUserByRmId(rmId) {
   setTimeout(function(){
      console.log(firstCallFlag); 
   },1);        
}

Upvotes: 1

Shubham
Shubham

Reputation: 1793

Call the function after declaring the variable. Function will hoist first and then the variables.

var firstCallFlag = 1;
function __getUserByRmId(rmId) {
    console.log(firstCallFlag); 
}
__getUserByRmId('sun1');

Upvotes: 2

Related Questions