Scope of JavaScript Variable


Scope of JavaScript Variable

When referring to a variable's scope, we mean the area of your programme where it is defined. There are only two scopes for JavaScript variables.

  • Global Variables − In JavaScript, these variables are global variables because they have a global scope.
  • Local Variables − It will only be visible within the function in which it is defined. Function parameters are always local to the function in which they are defined and cannot be shared.

During the execution of a function, a local variable takes priority over a global variable with the same name. A global variable is effectively hidden if a local variable or function parameter has the same name as a global variable.

Example:

<html> <body> <h2>Knowledge2life</h2> <p id="demo1"></p> <p id="demo2"></p> <script> myFunction(); function myFunction() { let website = "Knowledge2life"; document.getElementById("demo1").innerHTML = typeof website + " " + website; } </script> </body> </html>

OUTPUT:

Knowledge2life

string Knowledge2life