What is a block statement in JavaScript?

JavascriptWeb DevelopmentFront End Technology

A block statement groups zero or more statements. In languages other than JavaScript, it is known as a compound statement.

Syntax

Here’s the syntax −

{
   //List of statements
}

Variables with a block get scoped to the containing function. Block statement never introduce scope and using var to declare variables don’t have block scope.

var a = 20; {
   var b = 40;
}

Now, when you will print the value of a, it will print 40, not 20. This is because variable declared with a var within the block has the same scope like var before the block.

var a = 20; {
   var a = 40;
}
// this prints 40
document.write(a);
raja
Published on 23-Jan-2018 13:26:45
Advertisements