Languages
[Edit]
EN

JavaScript - block statement

0 points
Created by:
Aston-Freeman
727

In this article, we would like to show you block statement in JavaScript.

Syntax

{
  // Put your code here
}

Warning:

The block statement was introduced in ES6 (ES2015).

Practical example

In this example, we use a block delimited by a pair of braces to group statements. The block is "curly brackets"  ({}) and may optionally be labeled.

// ONLINE-RUNNER:browser;

var x = 1;
let y = 1;

if (true) {
  var x = 2;
  let y = 2;
}

console.log('x = ' + x); // 2
console.log('y = ' + y); // 1

Output:

x = 2
y = 1

Block scope

Unlike var statement, identifiers declared with let and const do have block scope, which means they are limited in scope to the block in which they were defined.

Example 1

// ONLINE-RUNNER:browser;

let x = 1;
{
  let x = 2;
}

console.log(x); // 1

Example 2

// ONLINE-RUNNER:browser;

const c = 1;
{
  const c = 2;
}

console.log(c); // 1

References

  1. block - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Statements & declarations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join