JavaScript: Statements
We can call console.log('Hexlet') a statement; it tells the JavaScript interpreter what to do. There can be as many such statements as you like. Each one runs after the previous one has finished, and that is how we build an arbitrarily large and complex program out of simple elements.
Statement 1: console.log('Hello') → executed
↓
Statement 2: console.log('World') → executed
↓
Statement 3: console.log('!') → executedHere is an example of code with two statements. These lines tell the computer to print phrases on the screen.
console.log('Mother of Dragons.'); // First statement
console.log('Dracarys!'); // Second statementThe result:
Mother of Dragons.
Dracarys!Order matters
The JavaScript interpreter runs code strictly in the order in which you wrote it. If you swap the lines:
console.log('Dracarys!');
console.log('Mother of Dragons.');they will be swapped on the screen as well:
Dracarys!
Mother of Dragons.An alternative way to write it
Usually statements are written on separate lines, but they can also be written on a single line separated by ;:
console.log('Mother of Dragons.'); console.log('Dracarys!');Both versions work the same way, but the second one is harder to read. That is why statements are almost always written one per line.
Why this matters
Right now we are writing very simple programs, but over time they will start to grow more complex, and one of the most important skills that will help you understand them is the ability to break a program (in your head) into independent statements. That is the only way to figure out what is going on in the code. Below is an example to grab your attention; you don't need to understand it yet:
const isPrime = (number) => {
if (number < 2) {
return false;
}
let divider = 2;
while (divider <= number / 2) {
if (number % divider === 0) {
return false;
}
divider += 1;
}
return true;
};Instructions
Print the parcel delivery status to the screen — three lines, each with a separate console.log() call:
Order #1337
Status: in delivery
Estimated time: 2 daysTips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Your exercise will be checked with these tests:
// @ts-check
import { expect, test, vi } from 'vitest';
test('instructions', async () => {
const consoleLogSpy = vi.spyOn(console, 'log');
await import('./index.js');
const firstArg = consoleLogSpy.mock.calls.join('\n');
expect(firstArg).toBe(
'Order #1337\nStatus: in delivery\nEstimated time: 2 days',
);
});Teacher's solution will be available in:
20:00
