Search code examples
javascriptfunctionvar

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?

like this

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 ?


Solution

  • Both are valid, you just have to be aware of the different scope the variables will be in. In the first example, the variables will be available outside of the function Multiply, they could be modified by other functions. In the second example, they are only available inside the Multiply function. When choosing where to declare your variables, you should ask yourself where you need to be able to use them, whether you are polluting the global scope, and how much of a performance hit are you taking when you declare them.