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
The block in the snippet above encased one JavaScript statement.
Example 2: Use a Code Block to Group Four JavaScript Statements
The if
condition’s code block grouped four JavaScript statements together.
Example 3: Use a Code Block to Group Four CSS Statements
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
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.
However, the pair of braces in the snippet below is an object literal because it encases multiple properties.