+ 1

Should I declare a variable inside a function or outside?

I'm really bad a javascript please don't get me wrong if you find this question dumb; if I have two variables, should I have declared them inside or outside the function? var Num = document.querySelector("#Fnumber"); var Num2 = document.querySelector("#Secnumber"); function Multiply(){ alert(Num.value + Num2.value) } //or declaring variable inside a function like this ? function Multiply(){ var Num = document.querySelector("#Fnumber").value; var Num2 = document.querySelector("#Secnumber").value; alert(Num + Num2) }``` //and am I pasting the value Property correct on both examples ?

5th May 2019, 5:31 PM
Glory222
Glory222 - avatar
1 ответ
+ 1
First you need to understand the scope of a variable. If you want to use one variable for only one specific thing and it won't be used in other function etc, you declare it in the function. Else, if you're going to use the variable in any part of the code declare it outside because it'll be a global and any function will be able to use it
5th May 2019, 6:27 PM
Juan David Padilla Diaz
Juan David Padilla Diaz - avatar