+ 2

How to access a variable inside setInterval function in global

Trying to access the number variable outside the function and i get error,help me fix want to console.log those random numbers as they change code: setInterval(function(){ number = Math.floor((Math.random()*10)); }, 1000); console.log(number); https://code.sololearn.com/WyD6tnhAKXjX/?ref=app

30th Nov 2021, 6:57 PM
K4MOGELO SITHOLE
K4MOGELO SITHOLE - avatar
21 ответ
+ 4
You cannot access local variable globally. Why you need to access outside the function?
30th Nov 2021, 7:03 PM
A͢J
A͢J - avatar
+ 1
J4D3N setInterval(function(){ window.number = Math.floor((Math.random()*10)); }, 1000);
30th Nov 2021, 7:16 PM
Artur
Artur - avatar
+ 1
But it's bad practice. There absolutely no reason to do that. And I've never met a single case when I needed to do that.
30th Nov 2021, 7:19 PM
Artur
Artur - avatar
+ 1
J4D3N Not in console. You can define 'window.number' variable inside your function and it's the same if you define 'number' variable in your main code flow aka global. Then you can access that variable. But if it is a local variable inside a function you can not access it from outer scope. And the only way (I know) to do that is as I did in the code above.
30th Nov 2021, 7:25 PM
Artur
Artur - avatar
+ 1
But remember that such properties are not variables! So function.number = 0 //property let number = 0//variable These too things are completely different.
30th Nov 2021, 7:29 PM
Artur
Artur - avatar
+ 1
I rewrote your code a bit. Just to give some food for thought. Notice how I declared only 1 global scope variable "start", and everything else is processed by functions. You may ask: "Why it is important?". Well, It is important because you don't pollute the global scope, and doing so you will avoid many mistakes in future. I used some advanced stuff here tho, such as ES6 destructuring, closure. But the code is really simple and hopefully, you'll get the idea. https://code.sololearn.com/Wg6pwOgt3kJk/?ref=app
30th Nov 2021, 11:59 PM
Artur
Artur - avatar
+ 1
السلام عليكم ورحمة الله
1st Dec 2021, 8:01 AM
عباس زكريا اسحق
عباس زكريا اسحق - avatar
+ 1
عباس زكريا اسحق وعليكم السلام ورحمة الله وبركاته
1st Dec 2021, 10:41 AM
Artur
Artur - avatar
0
Just define that variable in global scope. Or you could define it internally as 'window.number = ...'
30th Nov 2021, 7:03 PM
Artur
Artur - avatar
0
But if you really want to access a variable that is local to function then you need to add property to that function
30th Nov 2021, 7:17 PM
Artur
Artur - avatar