Welcome to TechQura.com

Helping users, developers and technologists to write and find solutions
Techqura.com > Coding > JavaScript > Q. When does a variable need to be declared outside a function in JavaScript ?
Techqura.com

When does a variable need to be declared outside a function in JavaScript ?

Asked by : Tom Clarke on 23/02/2021
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>