Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
Blocks
One way to organize our code is to use blocks.
A block statement is a way to group other statements together.
We have already used block statements while working with if
statements:
var x = 2; if (x < 4) { x++; }
The truth is, those curly braces and everything in between them are a single JavaScript statement!
Why Blocks?
An if
statement only applies to a single statement. We could have written the above example this way:
var x = 2; if (x < 4) x++;
However, the curly braces of a block statement are widely considered easier to read, even if they involve more lines.
Besides, if we need to execute two or more statements together, we need to use a block statement to group them anyway:
var x = 2; var y = 4; if (x < y) { x++; y--; }
Using block statements with if
, else if
, else
, and similar statements is a best practice.
Arbitrary Blocks
We can also create arbitrary blocks of code without any if
, else if
, or else
statement:
var x = 2; var y = 4; { x++; y--; }
Without a conditional statement in front of it, the block statement will always run.
Next, we will learn how to use block statements to keep our variables organized.
Learning Goals
I know what a block statement is
I can group multiple statements with a block statement
I know it is best practice to use curly braces with
if
,else if
, andelse
statements
Code Editor
Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.
Console Output
0 output lines