Variables – scope and hoisting
We already know how variables are declared in JavaScript using the var
keyword. Any variable that is declared using the var
keyword is termed a hoisted variable, and the term hoisting is the JavaScript default behavior of moving declarations to the top. When JavaScript is compiled by the JavaScript engine, all the variables that are declared using the var
keyword are placed at the top within its scope. This means that if the variable is declared within a function block, it will be placed at the top of the function; otherwise, if it's declared outside any function and at the root of the script, it will become globally available. Let's have a look at this example to clarify our understanding.
Let's suppose the following code is the simple program that returns the GMT of the country name passed in the function's parameter:
function getCountryGMT(countryName) { if (countryName == "Pakistan") { var gmt = "+5.00"...