+ 9
How we can use a variable outside its scope?
If I have a function : const a = () => { const min = 8 const x = min + 1 } And if it is necessary for me to use the variable min outside this function (like in some other function) then, is there a way to achieve it ??
9 odpowiedzi
+ 6
Declare in a higher scope.
var min;
const a = () =>{
min = 8;
}
const b = () =>{
console.log(min);
}
https://code.sololearn.com/Wz75I0Sfe53p/?ref=app
+ 5
😉
And the id attribute of html tags do this too
With the element with id, without document.getElementById, we can add styles etc on it.
+ 4
marjel101
You are right in that undeclared variable can be accessed regardless scope, the reason is that they will be added as a property to window. See Morpheus demo below for detailed explanation.
https://code.sololearn.com/WwhKQUoMbXHH/?ref=app
Nevertheless, it's not a good habit to use variable before declaring it, especially when team work is involved.
+ 3
Gordon
Thanks for the explanation and Morpheus’ code. I was excited when I discovered this feature because it solves problems with not being able to access variables when the window was not fully loaded. So now I always start my code with a window.onload and then declare the global variables in an init() function.
Anyway, thanks for sharing! I learn new things here each day 😊
+ 3
Gordon Trying to understand what you mean. Can you give an example, because I always use document.querySelector for this... 🤨
+ 3
https://code.sololearn.com/W11xO983uD7E/?ref=app
marjel101
Something like this, you can refer to the DOM by its id directly. Because that's also a window property.
But again this is an unsafe way: when you declare a variable with variable name same as the id, the scripts which were trying to access the DOM will be accessing the new variable instead, and error will occur.
So your way document.querySelector is correct.
+ 3
Gordon Oooow, like that! Thanks for taking the time to clarify!
I sure wished there was an option in SoloLearn to bookmark posts, because I would definetely bookmark this one! 🙏🙏
+ 2
You can also declare a variable without the keyword var in one function to use it in another. I use that a lot when setting variables to use in the rest of the code.
https://code.sololearn.com/WeD33z68815q/?ref=app