Javascript Scopes

Neha Sharma
3 min readJul 6, 2018

--

Javascript is the most dynamic scripting language. This dynamic nature of Javascript make it confusing too. One of the pillar of javascript language is — scopes. If you are coming from any programming language background you might be amazed by how different javascript Scope works as compare to other programming language

Before ES6 , there was no Block level scope in Javascript. Javascript had only functional scope. But with ES6’s let we got the block-level scope.

Type of scopes in Javascript:

  1. Global
  2. Local
  3. Block

These scope are applicable on the variables , methods and functions in Javascript.

#Global Scope

Anything you declare outside the curly brackets in the Javascript program is Global. When we say it is global, it means you can access the variable :

  • Anywhere in the program
  • Also available at window level [window.<varname>]]
  • Can be access by window.<varname>

Avoid declaring the variables globally. As it pollute the window level scope and memory or global scope.

If you miss writing var while declaring the variables , they will become global variables. Hence, whenever you are declaring new variables write var with them.

# Local scope

Anything you declare within the curly brackets it become local to that method or function.

In the above code scope of name is only within f(). If you try to access it outside the f() you will get an error.

#Block Scope

Before ES6, there was no block scope in Javascript. This missing part used to make Javascript very different from the other programming language. As , Javascript (before ES6) had only functional scope. It means, that you can access the variables outside the blocks also [#7 — fname is declared within the block of if, yet we are able to access it outside the block. Because the scope of the variables is functional here.]

Javascript — Functional scope

In ES6, new way of declaring variables introduced — let. It helps JS programmers to define the block level scopes.

When you start programming and writing complex code, these scopes when get merged with each other create unexpected results.

In next blog we are going to learn about such cases.

--

--

Neha Sharma
Neha Sharma

Written by Neha Sharma

Tech Lead; Brain behind JSLovers, Tech Speaker; ❤ Calligraphy and Chai. https://twitter.com/hellonehha; My Dev Journey: https://www.instagram.com/devgirllife/

No responses yet