Jonas Jonas - 1 year ago 88
Javascript Question

Cant get access to variable inside function

I am trying to access a variable inside a function.
Here is my code:

HTML

<div id="box1" class="box" onclick="set(1)"></div>


JavaScript

let i = 0;

function set(number){
i = number;
}

console.log(i);


Console Log Output: [When i click my div]

undefined


Any suggestions?

Answer Source

Console Log Output: [When i click my div]

No.

The only time you call console.log it will output 0 and that is the log output before you click the div.

If you want to get the output when you click the div then the console.log statement must be inside the event handler function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download