Scope determines the accessibility (visibility) of variables. Variables defined inside a function are not accessible (visible) from outside the function. In JavaScript we have two types of scope:
Local Scope:
Variables declared within a JavaScript function, become LOCAL to the function. So, local variables have Function scope: They can only be accessed from within the function. Local variables are created when a function starts, and deleted when the function is completed.
Example:
// Here we can't use stud variable.
function myFunction() {
var stud = "Adarsh";
// Here we can use stud variable.
}
Also, since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Example:
function myFunction1() {
var stud = "Adarsh";
// Rest Code.
}
function myFunction1() {
var stud = "Vicky";
// Rest Code.
}
Global Scope:
A variable declared outside a function, becomes GLOBAL. A global variable has global scope: All scripts and functions can access it.
Example:
var stud = "Adarsh";
// Here we can use stud variable.
function myFunction() {
// Here we can also use stud variable.
}
The lifetime of a JavaScript variable starts when it is declared. In a web browser, global variables are deleted when you close the browser window (or tab).
Note: If we assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. But now-a-days all modern browsers support running JavaScript in “Strict Mode”. In “Strict Mode”, undeclared variables are not automatically global.
Which of the follwing options is/are correct ?