What Is a Code Block?
A block is a pair of braces ({...}
) used to group multiple statements together.
Block typically gets used in JavaScript functions, conditional statements, and CSS rulesets.
Example 1: Use a Code Block to Encase a JavaScript Statement
{ var bestColor = "White";}
The block in the snippet above encased one JavaScript statement.
Example 2: Use a Code Block to Group Four JavaScript Statements
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
condition’s code block grouped four JavaScript statements together.
Example 3: Use a Code Block to Group Four CSS Statements
h1 { color: orange; text-transform: uppercase; text-decoration: underline; text-align: center;}
We used the code block in the CSS ruleset above to group four CSS statements.
Example 4: Use a Code Block to Group Three JavaScript Statements
class Time { hourNow = new Date().getHours(); minutesNow = new Date().getMinutes(); secondsNow = new Date().getSeconds();}
if (new Date().getHours() < 18) { const currentTime = new Time(); console.log( `Check your plans now. The time is ${currentTime.hourNow}:${currentTime.minutesNow}:${currentTime.secondsNow}.` );}
The Time
class’s code block grouped three JavaScript statements, while the if
condition’s code block grouped two.
Note the following:
hourNow
,minutesNow
, andsecondsNow
are the class fields (properties).- The snippet above used the
new
keyword to construct a new object from theTime
class. Therefore, thecurrentTime
object is an instance of theTime
constructor class.
Before we wrap up our discussion on code blocks, you should know 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" };