Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Block Statement in JavaScript?
2.1.
Example
3.
Syntax
3.1.
Block Statement
3.2.
Labelled Block Statement 
4.
Examples
4.1.
Block Scoping Rules with var or Function Declaration in Non-Strict Mode
4.2.
Block Scoping Rules with let, const, or Function Declaration in Strict Mode
5.
Specifications
6.
Implementing Block Statements in JS with Examples
6.1.
Javascript
6.2.
Javascript
6.3.
Javascript
6.4.
Javascript
6.5.
Javascript
7.
Browser Compatibility
8.
Frequently Asked Questions
8.1.
What is a block of statements called?
8.2.
What is a code block in JavaScript?
8.3.
What is a command block in JavaScript?
8.4.
What is a block variable in JavaScript?
9.
Conclusion
Last Updated: Jun 9, 2024
Easy

Block Statement in JavaScript

Author Ayush Mishra
1 upvote

Introduction

JavaScript is a versatile and powerful programming language that is essential for modern web development. One of the fundamental building blocks of JavaScript is the block statement. Understanding block statements is crucial for writing clean, efficient, and maintainable code. In this blog post, we'll explore what block statements are, why they are important, and how they are used in JavaScript.

Introduction to Block Statement in JavaScript

Recommended Topic,Javascript hasOwnProperty

What is a Block Statement in JavaScript?

A block statement is a statement that combines several other statements. A block, denoted by curly braces, can define a block of statements that will be executed as a single unit, determine the scope of variables, and more.

Example

An example of a Block Statement in Javascript:-

{
    let a = 2;
    let b = 3;
    console.log(a + b);
}

 

In this example, the console.log statement that adds the two variables and prints the result is grouped with the two variable declarations (a and b) in a block statement.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax

Here's the basic syntax:

{
  // Your statements go here
  let x = 10;
  console.log(x);
}

Block Statement

A block statement is defined using curly braces {}. Inside the braces, you can include any number of valid JavaScript statements. Here's the basic syntax:

{
  // Your statements go here
}

Key Points:

  • Scope: Variables declared within a block statement using let or const are block-scoped, meaning they are only accessible within the block.
  • Usage: Block statements are often used in conjunction with control structures like if, for, while, and switch to define the scope of the associated code.

Labelled Block Statement 

A labelled block statement allows you to give a label to a block, which can be particularly useful with control flow statements like break and continue. The syntax is as follows:

labelName: {
  // Your statements go here
  let z = 30;
  console.log(z);
}

Key Points:

  • Label Name: The label is an identifier followed by a colon (:) and precedes the block.
  • Control Flow: You can use the label with break or continue statements to exit the labelled block or to continue to the next iteration of a loop within the block.

Examples

Block Scoping Rules with var or Function Declaration in Non-Strict Mode

In non-strict mode, var declarations are function-scoped or globally scoped, not block-scoped. This means that variables declared with var are accessible outside the block they are defined in, which can lead to unexpected behavior.

Example:

if (true) {
  var x = 10;
  function foo() {
    console.log("Inside function foo");
  }
}
console.log(x); // Outputs: 10
foo(); // Outputs: "Inside function foo"

Explanation:

  • The variable x and the function foo are declared inside the if block.
  • However, both x and foo are accessible outside the block because var and function declarations are not block-scoped in non-strict mode.

Caveat:

  • This behavior can cause bugs and conflicts, especially in larger codebases where the same variable name might be used in different blocks.

Block Scoping Rules with let, const, or Function Declaration in Strict Mode

In strict mode, let and const declarations are block-scoped, meaning they are only accessible within the block they are defined in. Function declarations inside blocks are also block-scoped.

Enabling Strict Mode:

"use strict";

Example with let and const:

"use strict";

if (true) {
  let y = 20;
  const z = 30;
  function bar() {
    console.log("Inside function bar");
  }
}
console.log(y); // ReferenceError: y is not defined
console.log(z); // ReferenceError: z is not defined
bar(); // ReferenceError: bar is not defined

Explanation:

  • The variables y and z, and the function bar, are declared inside the if block.
  • In strict mode, let, const, and function declarations are block-scoped, so y, z, and bar are not accessible outside the block.

Specifications

SpecificationsStatusSyntax
Defined by a pair of curly braces {}. Groups zero or more statements, creating a block of code that defines a new scope for let and const variables.ECMAScript 1st Edition{ <statements> }
Allows you to name a block statement, which can be useful with break and continue statements to control the flow of code execution.ECMAScript 3rd EditionlabelName: { <statements> }
Declares a variable, optionally initializing it to a value. var is function-scoped or globally scoped, not block-scoped.ECMAScript 1st Editionvar variableName = value;
Declares a block-scoped local variable, optionally initializing it to a value. let is block-scoped.ECMAScript 6th Editionlet variableName = value;
Declares a block-scoped, read-only named constant. const must be initialized at declaration and cannot be reassigned.ECMAScript 6th Editionconst variableName = value;
Declares a function that is hoisted to the top of its scope. In non-strict mode, functions are not block-scoped, leading to potential accessibility outside the block in which they are defined.ECMAScript 1st Editionfunction functionName(parameters) { <statements> }
Declares a function that is hoisted to the top of its block scope. In strict mode, functions are block-scoped, limiting their accessibility to the block in which they are defined.ECMAScript 5th Editionfunction functionName(parameters) { <statements> }

Implementing Block Statements in JS with Examples

We have already seen in JavaScript what is a block of statements. Here, we will see methods to implement block statements in Javascript are:-

1. Control flow statements: Block statements are frequently used with control flow statements like if/else, for loops, and while loops to control how a program is executed.

For Example: 

  • Javascript

Javascript

const a = parseInt(prompt("Enter the first number "));
const b = parseInt(prompt("Enter the second number "));
if (a > b) {
console.log("a is greater than b");
} else {
console.log("a is less than or equal to b");
}

Output:

Output

 

2. Function definition: Block statements define the executed code when a function is called.

For Example:
 

  • Javascript

Javascript

const a = parseInt(prompt("Enter the first number "));
const b = parseInt(prompt("Enter the second number "));
function addTwoNumbers(a, b) {
return a + b;
}
prompt(addTwoNumbers(a, b));

Output:

Output

3. Exception Handling: Block statements can be used to handle exceptions, which are runtime errors that occur when a program is executed.

For Example:

  • Javascript

Javascript

const a = 5;
try {
// code that may throw an exception
console.log(a);
} catch (err) {

// code to handle the exception
console.log(err.message);
}

Output:

Output

4. Closure: Block statements can be used to create closures.

For Example:

  • Javascript

Javascript

function mCounter() {
let c = 0;
return function () {
return c++;
};
}

let count = mCounter();
// 0
console.log(count());
// 1
console.log(count());
// 2
console.log(count());

Output:

Output

5. Immediately Invoked Function Expressions (IIFE): Block statements can be used to create an IIFE, which is a function that runs as soon as it is defined.

For Example:

  • Javascript

Javascript

(function () {
console.log("Hello World!");
})();

Output:

Output


Check out this problem - Redundant Braces

Browser Compatibility

FeatureBrowser CompatibilityVersion
Block StatementAll major browsersAll versions
Labelled Block StatementAll major browsersAll versions
var DeclarationAll major browsersAll versions
let DeclarationChrome, Firefox, Safari, EdgeChrome 41+, Firefox 44+, Safari 10+, Edge
const DeclarationChrome, Firefox, Safari, EdgeChrome 41+, Firefox 44+, Safari 10+, Edge
Function Declaration (non-strict mode)All major browsersAll versions
Function Declaration (strict mode)Chrome, Firefox, Safari, EdgeChrome 13+, Firefox 4+, Safari 5.1+, Edge

Frequently Asked Questions

What is a block of statements called?

A block of statements is called a "block statement" or simply a "block," enclosed within curly braces {} in JavaScript.

What is a code block in JavaScript?

A code block in JavaScript is a set of statements enclosed within curly braces {}, defining a scope for variables and functions.

What is a command block in JavaScript?

In JavaScript, there is no specific term "command block." It might refer to a "block statement" or simply a "block" of code.

What is a block variable in JavaScript?

A block variable in JavaScript is a variable declared with let or const within a block, limiting its scope to that block.

Conclusion

Congratulations on finishing the blog! We have discussed in javascript what is a block of statement. Block statements are an important JavaScript tool for planning and managing the execution flow of a program, as well as for adding new scopes as needed.

We hope this blog has helped you to know in javascript what is a block of statement. Do not stop learning! We recommend you read some of our Javascript articles: 

1. Introduction to Javascript

2. Javascript throws statement

3. Javascript Switch Statement

4. Difference Between "var", "let" and "const" in JS
 

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problemsinterview experiences, and interview bundles.

We wish you Good Luck! 

Happy Learning!

Live masterclass