Friday, December 7, 2018

Function scopes and block scopes in JavaScript

In this tutorial we are going to discuss what is Function scopes and block scopes in JavaScript. In javascript Block scopes are different from function scopes and lets see the below example, then you will get more understanding on this.

Function scopes and block scopes in JavaScript

Function Scope :

A function scope is created for every function (and we can nest them too). Lets see the below simple function scope example.

Example -1 :
function add() {

  // function scope

Lets see the example for nested function.

Example -2 :
function add() {

  // local function scope

  function sum() {
    // nested local function scope


Block Scope :

Block scopes are what you get when you use if statements, for statements etc. Lets see the below example for block scope.

Using if statement
if (4 == '4') {
  // block scope for the if statement

Using for statement
for (var i=0; i<10; i++) {
  // block scope for the for statement

This is all about Function scopes and block scopes in JavaScript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment