2

The JavaScript block statement

 1 year ago
source link: https://www.webpro.nl/scraps/javascript-block-statement
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The JavaScript block statement

The JavaScript block statement

Published by Lars Kappert on May 6, 2022

In the first scrap of this blog I'd like to make a case for a great little feature that I rarely see used in the wild.

  • Want to organize your code a little bit better?
  • Have a hard time coming up with another name for the same variable?

Use blocks! Let's take a bogus unit test:

function test() {
  const type = 'some';

  const thing = getThing(type, 1);
  assert.equal(thing, 1);

  // Ehm... how to call this `thing` now...?
  const thing2 = getThing(type, 2);
  assert.equal(thing2, 2);
}

Specifically for unit tests you could argue that this particular case should be separated in two unit tests, but sometimes that's just not what you want. You can use blocks instead:

function test() {
  const type = 'some';

  {
    const thing = getThing(type, 1);
    assert.equal(thing, 1);
  }

  {
    const thing = getThing(type, 2);
    assert.equal(thing, 2);
  }
}

A pair of curly braces are the delimiters of the blocks, and define a new scope for let, const and function declarations.

Neat!

Frontend Ramblings RSS feedThe content of this website on GitHubMe on TwitterShare this article on TwitterShare this article on Hacker News

Do you have a question or did you find an issue in this article?

Please let me know! This website is fully open-sourced at GitHub.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK