JavaScript and TypeScript course ยท Module 1: JavaScript Basics
Statements and Code Blocks
In this lesson8
In a park full of dinosaurs, every step must be carefully planned and executed in the right order. The same is true in JavaScript - code executes as a sequence of statements that must be properly structured for the program to work correctly and safely.
Statements in JavaScript
A statement in JavaScript is a command that performs a specific task. It's like a single order given to a Jurassic Park employee - for example, "feed the T-Rex" or "check the fence."
In JavaScript, each statement usually ends with a semicolon (though, as we'll see in the next lesson, this is sometimes optional):
let dinosaurCount = 5; // Variable declaration
console.log("Warning!"); // Function call
dinosaurCount++; // Value incrementStatements are executed in the order they were written - from top to bottom. It's like a safety procedure in Jurassic Park, where steps must be performed in a strictly defined order:
// T-Rex enclosure closing procedure
verifyDinosaurLocation(); // 1. Verify dinosaur location
activateGates(); // 2. Activate gates
closeFencedArea(); // 3. Close the fenced area
verifyEnclosureSecurity(); // 4. Verify enclosure securityCode Blocks in JavaScript
A code block is a group of statements enclosed in curly braces { }. It works like a fenced zone in Jurassic Park - it designates a specific area that has its own rules and restrictions.
// Code block controlling the dinosaur health review procedure
{
let healthStatus = checkDinosaurVitals();
updateMedicalRecords(healthStatus);
if (healthStatus === "Critical") {
alertVeterinaryTeam();
}
}We use code blocks mainly in four situations:
1. Functions
Functions are key "procedures" in our park that can be executed multiple times:
function feedCarnivore(dinosaurType, foodAmount) {
// This code block defines the carnivore feeding procedure
console.log(`Preparing meal for ${dinosaurType}`);
prepareMeat(foodAmount);
openFeedingHatch();
closeFeedingHatch();
console.log("Feeding completed");
}2. Conditional Statements
Just as park personnel decisions depend on various situations, in JavaScript we use code blocks with conditional statements:
if (rainLevel > 50) {
// This block executes only during heavy rainfall
evacuateOpenAreas();
secureOutdoorEquipment();
activateEmergencyShelters();
}3. Loops
When the park needs to perform the same procedure for many enclosures or dinosaurs, loops are used:
for (let i = 0; i < parkSectors.length; i++) {
// This block executes for each park sector
checkSecuritySystems(parkSectors[i]);
updateSecurityLogs(parkSectors[i]);
}4. Lexical Blocks
Sometimes we use code blocks solely to limit the scope of variables - similar to restricted access zones in the park:
{
// Variables declared here are only accessible inside this block
let securityCode = "TRex2023";
activateSecurityProtocol(securityCode);
}
// The securityCode variable is no longer accessible hereVariable Scope
Code blocks have crucial importance for the scope of variables declared with let and const. These variables are only visible within the block in which they were declared.
It's like employees having access only to specific zones in Jurassic Park:
{
// Genetic laboratory - authorized personnel only
let dinoGenomeSequence = "ACGTACGT...";
// The variable is only accessible here
modifyDinoGenome(dinoGenomeSequence);
}
// Error! This variable is not accessible outside the laboratory
// console.log(dinoGenomeSequence);For a better illustration, let's compare variable scopes to security zones in the park:
// Public area (global scope)
let parkName = "Jurassic Park";
function checkParkStatus() {
// Employee area (function scope)
let isOpen = true;
let visitorCount = 368;
if (visitorCount > 350) {
// Crowd control zone (block scope)
let alertLevel = "Yellow";
console.log(`Alert level: ${alertLevel}`);
}
// alertLevel is not accessible here - error!
// console.log(alertLevel);
}
// Neither isOpen nor visitorCount are accessible here - error!
// console.log(isOpen);Nesting Blocks
Code blocks can also be nested (blocks within blocks), similar to how in Jurassic Park we have zones within other zones:
// Employee zone
{
let employeeAccessLevel = 2;
// Genetics zone - higher access level
if (employeeAccessLevel >= 3) {
let geneticLabAccess = true;
// High security - strict control
if (geneticLabAccess) {
let embryoStorageCode = "LS-445-23A";
console.log(`Access code: ${embryoStorageCode}`);
}
}
}Hoisting and Declarations
In JavaScript, there is a mechanism called "hoisting" - variable and function declarations are "lifted" to the top of their scope. However, values assigned to variables are not lifted.
It's like preparing all safety procedures before opening the park:
// This function is available here thanks to hoisting
securityCheck();
// Function declaration
function securityCheck() {
console.log("Security systems checked");
}
// Variables declared with var are "hoisted"
console.log(parkStatus); // undefined, but not an error
var parkStatus = "Open";
// let and const are NOT fully hoisted
// console.log(dinosaurCount); // Error: Cannot access 'dinosaurCount' before initialization
let dinosaurCount = 20;Expressions vs Statements
In JavaScript, it's important to distinguish between statements and expressions:
- Expression is code that returns a value, like examining a DNA sample that returns a result
- Statement is a command that performs an action, like a dinosaur feeding procedure
// Expressions - return a value
5 + 3 // Expression that returns 8
dinosaurWeight * 0.5 // Expression that returns half the weight
isDangerousSpecies("T-Rex") // Expression that returns true
// Statements - perform actions
let visitorsToday = 500; // Declaration statement
if (visitorsToday > 400) { // Conditional statement
activateCrowdControl();
}Practical Application
Understanding statements and code blocks is like learning the map of Jurassic Park - it allows you to safely navigate through code. Here is an example of complex code using statements, blocks, and various scopes:
// Park monitoring system
// Global variables
const parkName = "Jurassic Park";
let parkStatus = "Open";
let globalAlertLevel = "Normal";
// Main monitoring function
function monitorParkSystems() {
let systemsOnline = true;
// Check fences
checkElectricalFences();
// Dinosaur monitoring block
{
let activeDinosaurs = getDinosaurStatus();
// Loop checking each dinosaur
for (let i = 0; i < activeDinosaurs.length; i++) {
let dinosaur = activeDinosaurs[i];
// Condition block for dangerous species
if (dinosaur.dangerLevel > 3) {
// Inner emergency procedure block
{
let emergencyProtocol = `Protocol-${dinosaur.species}`;
console.log(`Activation: ${emergencyProtocol}`);
// This variable is only accessible here
let emergencyTeam = selectTeamForSpecies(dinosaur.species);
alertSecurityTeam(emergencyTeam);
}
// The emergencyTeam variable is not accessible here
updateSecurityLogs(dinosaur);
}
}
}
// Variables from the dinosaur monitoring block are not accessible here
return generateStatusReport();
}
// Helper function
function checkElectricalFences() {
let sections = 12;
let failedSections = 0;
for (let i = 1; i <= sections; i++) {
let sectionStatus = getFenceStatus(i);
if (sectionStatus !== "Active") {
failedSections++;
// Emergency block
{
let repairTeam = "Echo";
dispatchRepairTeam(repairTeam, i);
}
}
}
if (failedSections > 0) {
globalAlertLevel = "Elevated";
}
}In the above example, you can see how code blocks can be used to organize code, control variable scope, and create a logical program structure. Each block works like a separate zone in the park, with its own rules and restrictions.
Summary
Statements and code blocks in JavaScript are like safety procedures and zones in Jurassic Park - they maintain order, organization, and safety. Well-organized code that properly uses statements and blocks is easier to understand, maintain, and develop.
Key concepts to remember:
- Statements are individual commands ending with a semicolon
- Code blocks are groups of statements enclosed in curly braces
{ } - Variable scope is limited by the block in which they were declared (for
letandconst) - Hoisting is the mechanism of "lifting" variable and function declarations
- Expressions return a value, while statements perform actions
In the next lesson, we will take a closer look at semicolons in JavaScript and their optionality, which is like learning the nuances of park safety protocols - sometimes they are absolutely necessary, and other times they can be omitted.
Code for this lesson: index.js
// Park Enclosures - Working with Arrays
// Exercise: Creating arrays and using array methods
// An array is an ordered collection of elements
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus"];
console.log("Dinosaurs in the park:", dinosaurs);
console.log("First:", dinosaurs[0]);
console.log("Last:", dinosaurs[dinosaurs.length - 1]);
// Array methods
dinosaurs.push("Stegosaurus");
console.log("After adding:", dinosaurs);
const removed = dinosaurs.pop();
console.log("Removed:", removed);
// Searching
console.log("Is there a T-Rex?", dinosaurs.includes("T-Rex"));
console.log("Triceratops index:", dinosaurs.indexOf("Triceratops"));
// Your task:
// 1. Create an array of species in an enclosure
// 2. Add and remove elements using push/pop/shift/unshift
// 3. Find an element in the array
// Your code here:
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is a code block in JavaScript?
Hands-on tasks in the game
- Vertical ordering
Arrange the elements of a code block structure in a JavaScript function:
- Click in order
Arrange the program: comment, constant, function definition and its call:
- Vertical ordering
Arrange the steps in the programming process: