What Is a Code Block?

A block is a pair of braces ({...}) used to group multiple statements.

Block typically gets used in JavaScript functions, conditional statements, and CSS rulesets.

Here’s an example:

{
  var bestColor = "White";
}

The block in the snippet above encased one JavaScript statement.

Here’s another example:

if (new Date().getHours() < 18) {
  const hourNow = new Date().getHours();
  const minutesNow = new Date().getMinutes();
  const secondsNow = new Date().getSeconds();

  console.log(`Check your plans now. The time is ${hourNow}:${minutesNow}:${secondsNow}.`);
}

The if code’s block in the snippet above grouped four JavaScript statements.

Now, consider this snippet:

h1 {
  color: orange;
  font-weight: bold;
  text-transform: uppercase;
  text-decoration: underline;
  text-align: center;
}

In the CSS ruleset above, we used the code block to group five CSS statements.

◇ ◇ ◇

Before we wrap up our discussion on code blocks, you should be aware of the difference between a block and an object literal. So, let’s talk about that below.

Block vs. Object Literal – What’s the Difference?

A pair of braces ({...}) define a block and an object literal. However, they serve different purposes.

A block groups multiple statements, whereas an object literal is a container used to store one or more properties.

For instance, the pair of braces in the snippet below is a block because we used it to group the function’s statements.

function getName() {
  const firstName = "Oluwatobi";
  const lastName = "Sofela";
  return firstName + " " + lastName;
}

However, the pair of braces in the snippet below is an object literal because it encases multiple properties.

const myName = { firstName: "Oluwatobi", lastName: "Sofela" };

Overview

This article discussed what a block is. We also looked at the difference between a block and an object literal.

Thanks for reading!

Similar Posts