In witch direction does our program run?

Does it run from left to right or from right to left? Does it run differently depending on the code we are writing, e.g, for loops, functions, if-else statements, etc?

It goes top to bottom, but that doesn’t mean the first line get executed first. For example:

1    function getGoodies(){
2      console.log('G5 airplane!');
3    }
4
5    function allTheGoodies() {
6      console.log('Welcome to the goodie room!');
7      getGoodies();
8    }
9   
10   console.log('This is Flaming Dragon!');
11   allTheGoodies();

We expect the output to be:

This is Flaming Dragon!
Welcome to the goodie room!
G5 airplane!

This is because even though the functions getGoodies() and allTheGoodies() appear first, they are only executed when called (like in lines 11 and then 7).

To better understand the flow of a program, I suggest you read what a block of code is, and how JavaScript decides what to do next after every line of code (if going to the next line, calling a function, calculating something, etc).

1 Like

Adding to what @irlfede said:

Keywords, brackets, parentheses, and semicolons all make the code structure work explicitly like you want it to.

It is normal to define things and call them later, out of order (depending on context).

You can also get a bit ahead of yourself, and call things before defining them…

predictTheFuture("The future is orange...");

const myFavourite = (thing, fave) => {
    console.log(`My favourite ${thing}.... is ${fave}!`);
}

const someRandomNumber = () => {
    let randomated = Math.floor(Math.random() * 24) ^ 7;
    console.log(`The random number is ${randomated}!`);
}

myFavourite("potato", "roast");
someRandomNumber();

function predictTheFuture(forecast) { 
    console.log("The future's bright... " + forecast);
}

All thanks to hoisting. :slight_smile:

1 Like

Anarchy! Madness!

Haha, yes. As a devoted pythonista I resist the urge to think such thoughts. But it’s totally fair game in Javascript.

1 Like