Home > UI/UX Development > JavaScript > JavaScript Scope

JavaScript Scope

This post was most recently updated on July 31st, 2024

Hello everyone, in this post we will discuss about following points on JavaScript Scope

  • What is scope?
  • What is Global/Local Scope?
  • What is lexical scope?

What is scope?

In JavaScript, scope determines the accessibility (visibility). Scope refers to the current context of your code. Scopes can be globally or locally defined for both functions and variables.

What is Global/Local Scope?

In JavaScript there are two types of scope:

  • Local scope
  • Global scope

Local scope: Variables declared within a JavaScript function, become local to the function. Local variables have local scope. They can only be accessed within the function.

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed which means lifespan of local variables is only inside functions.

Global scope: A variable declared outside a function, becomes global. A global variable has global scope.

Since global variables are recognized inside all functions, global variables are created outside the function generally on top of the javascript file. Lifespan of global variables is within js file.

If you assign a value to a variable that has not been declared, it will automatically become a global variable.

What is lexical scope?

Whenever you declare a function within another function, the inner function has access to the scope of the outer function, this is called Lexical Scope or Closure.

Here variable bikeName declare inside scope B myFunction(), so scope is present inside myFunction() and myOtherFunction().

This Article is TAGGED in . BOOKMARK THE permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">