When does a variable need to be declared outside a function in JavaScript ?
Response by TechGuy
If you declare and initialized var inside a function then it will be initialized every time you call the function.
<button onclick="counterFunction()">Click me</button>
<script>
function counterFunction(){
var counter = 0;
document.getElementById("counterValue").innerHTML = counter++;
}
</script>
<p id="counterValue"></p>
Result on above example will be always 0 as the var was declared and initialized inside a function,
every time you call the function, it gets initialized (value become 0 in this example)
Correct approach will be :
<button onclick="counterFunction()">Click me</button>
<script>
var counter = 0;
function counterFunction(){
document.getElementById("counterValue").innerHTML = counter++;
}
</script>
<p id="counterValue"></p>