In this series, I'm going to explain the fundamentals of javascript.
In this post, we are going to learn more about Blocks.
Blocks
Let's read the definition by Mozilla - MDN
A block statement (or compound statement in other languages) is used to group zero or more statements. The block is delimited by a pair of braces ("curly brackets") and may optionally be labelled
In other words, a block
is everything between {}
{ // block started
var foo = "bar";
} // block ended
console.log(foo); // logs "bar"
It is important to mention that the block doesn't create a scope, so in our small example, foo
variable is still accessible from outside the block, that is why we could log the variable with console.log(foo);
. We'll see later in this post more about the scope.
This example is also valid:
function demo() {
// first block
{
var foo = "bar";
}
// second block
{
console.log(foo);
}
}
Now, whenever we invoke demo()
, we'll see that "bar" is logged in the console. Give it a try 💪!
It is worth mentioning, that we hardly ever gonna see this kind of snippet in a real-world app, please don't write functions with multiple blocks like I just did. This was only for demonstration purposes.
So, if blocks are not used as in the example above, why we need them? Well, the blocks are also the way we have to declare several statements "attached" to a conditional, loop, etc.
if (condition) {
// this is a block
}
while (condition) {
// this is a block
}
That’s it! If you have any doubt don’t hesitate to leave your comments or ask me ​​via Twitter.
In the next post of this series, we're going to learn about functions 😎. Stay tuned!
Top comments (0)