user7716943
user7716943

Reputation: 495

Function won't work if called outside

Function doesn't work and I get undefined if I call console.log(window.Test) outside of the function..

Works when I call inside the function in this code below--

var num = 0;
function clientseed() {

var a = "test";
num++;

window.Test = a + "-" + num;

console.log(window.Test)
}

But not with the one below --- even though im using window. which is for defining global variable but I get undefined result.. if I click the button 3 times and go to console and enter console.log(window.Test) it shows undefined also

var num = 0;
function clientseed() {

var a = "test";
num++;

window.Test = a + "-" + num;

}

console.log(window.Test)

Html

<button onclick="clientseed()">Test</button>

Upvotes: 1

Views: 70

Answers (2)

David Biga
David Biga

Reputation: 2801

window.Test is undefined. You are out of scope, this means that you are defining a global variable within a function that has not yet been called. Test does not exist yet. This is why when you call console.log(window.Test) you get undefined.

Something you could do is move the console.log to be triggered after setting the variable Test

E.g.

function clientseed() {
   // window.Test gets defined 
}

console.log(window.Test); // outputs undefined because clientseed() was never executed which sets the definition for Test

When you click your button, it triggers clientseed() to be called. You than go through each command within that function, towards the end you set window.Test = a + "-" + num;. NOW the variable Test exist in the scope of window. When clientseed() is called, it does not execute console.log(window.Test) again. the reason be, it is out of scope of that function. That function only clientseed() only cares about itself and what is worried about executing what is contained within the {}.

So, if you look in your console after clicking the button 3 times, you will notice undefined only shows up once. This is exactly to that point above. When the page loads it will call console.log(window.Test). It won't execute clientseed() until you execute it. Because of that, Test in window does not exist.

I hope this offers some clarity.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122026

even though im using window. which is for defining global variable but I get undefined result..

You are using window, that is fine but, even before you declaring the variable, your log statement got executed.

Case 1 (top code snippet) :

Button click {

 // declared the variable
 // printed.

}

Case 2 :

Button click {

 // declared the variable

}

// printed.  -- well the button not yet clicked. I don't know what is the variable you are asking me to print.

Upvotes: 1

Related Questions