-1

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?

j08691
  • 204,283
  • 31
  • 260
  • 272
Jonas
  • 67
  • 1
  • 1
  • 6
  • 3
    not sure why it would log anything when you click the div – epascarello Nov 09 '16 at 20:25
  • Would'nt the function recieve the paramater and set i to the paramater? – Jonas Nov 09 '16 at 20:27
  • Is your console.log firing before you click on the div? – Jeffpowrs Nov 09 '16 at 20:27
  • You code does not log `undefined` (instead it outputs `0`, immediately on page load). – apsillers Nov 09 '16 at 20:28
  • Javascript variables do not persist through the lifecycle of the program like that. They will if say you are using Angular and are using $scope variables. But, you will not be able to set a global variable and then access it on subsequent calls. – Luke Becker Nov 09 '16 at 20:29
  • "But, you will not be able to set a global variable and then access it on subsequent calls." — Yes you can! What you can't do is access a value *before* you set it. – Quentin Nov 09 '16 at 20:29
  • @LukeBecker That is not correct at all. If you define a global variable, you can access it in any later function. – TheValyreanGroup Nov 09 '16 at 20:33

1 Answers1

2

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335