Flow, Scope and Program Structure
Flow of a program
A JavaScript file is executed line by line, top to bottom. A function call interrupts that sequence: the statements inside the function run first, and only when the last of them, or a return, has finished does control go back to the point immediately after the call. The program then carries on from there.A function definition is not a set of instructions to run on the way past. It packages work under a name, and the code inside it runs only when something calls it.
Follow it through. The first call arrives with a holding 3, so the if block runs: it prints 3 and returns 5, which is stored in x and not printed yet. The second call arrives with a holding 9, so the if is skipped, b is printed giving 12, and the 13 it returns is printed by the caller. Only on the last line does the 5 that has been sitting in x finally appear.
A function that finishes without running a return statement still hands something back: the value undefined. Python calls that value None; JavaScript calls it undefined, and it turns up any time a caller prints the result of a function that had nothing to return.
Names declared inside a function are local
Declaring a variable inside a function creates a local variable. It is called local because it exists only while that function is running, and the rest of the file cannot see it at all. Reading it from outside stops the program with a ReferenceError.let stops at the nearest braces
JavaScript goes further than Python here. A name declared with let belongs to the nearest enclosing pair of braces and nothing wider, so a let written inside an if body or a for body has already stopped existing by the line after the closing brace. This is called block scope.var does not stop at the braces
There is an older keyword, var, which is scoped to the whole function instead. A var written inside an if body is visible everywhere else in that function, including after the block has ended. That sounds convenient and is the reason var causes bugs: the name outlives the situation it was meant for.An assignment with no keyword at all
Leave the keyword off completely and JavaScript does not make a local variable. It makes a global one, which stays alive after the function returns and is visible to every line below. Nothing warns you, at least in the plain script mode your code runs in here; JavaScript also has a stricter mode, which some files switch on, where that same line is an error rather than a silent global. This is why the declaration keyword is not a formality: it is the thing that decides whether a name stays inside the function you wrote it in.| Written as | Where the name lives |
|---|---|
| let size = 5; | Only inside the nearest pair of braces |
| var size = 5; | Everywhere inside the function, whichever block it was written in |
| size = 5; | Global in plain script mode: visible everywhere below, long after the function ends |
The program below prints one message before the call, one during it, and two after it, so the output shows where control goes. The function also has a local variable,
grams. Run it, then change it and run it again:• Add a second call,
flourNeeded(2);, right below the first one.• Press Reset, then add
console.log(grams); at the very end of the program.• Keep
console.log(grams); at the end, and delete the keyword in front of grams = loaves * 450;.function flourNeeded(loaves) {
console.log("Weighing flour for", loaves, "loaves");
let grams = loaves * 450;
return grams;
}
console.log("Start");
let needed = flourNeeded(3);
console.log("Back from flourNeeded");
console.log("Flour in grams:", needed);
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.
Reassigning a parameter
A parameter is a local variable too. It starts out holding a copy of the argument, and assigning to it changes that copy and nothing else. The caller's own variable is untouched, whatever it happens to be called.Functions calling other functions
Any function you write can be called from inside another one. Each call gets its own private set of local variables, so two functions may use the same parameter name without interfering in the slightest.The shape of a program
From here on, write programs in this order: any values the whole file needs first, then every function definition, then the program logic that calls them. Putting the calls last is not a style preference. It makes the file readable, because by the time you reach the logic you have already met every name it uses.The program below has the same shape: a value the whole file needs, then the function definitions, then the program logic. It reads the number of pages in a book, works out the hours of reading at 40 pages an hour, and picks a plan. Run it, and type a whole number of pages when it asks. Then try these:
• Run it again and type 90, then run it once more and type 900.
• Press Reset, then cut the line
let pagesPerHour = 40; and paste it at the very end of the program.// values the whole file needs
let pagesPerHour = 40;
// function definitions
function hoursToRead(pages) {
return pages / pagesPerHour;
}
function readingPlan(hours) {
if (hours <= 3) {
return "one evening";
} else if (hours <= 10) {
return "a weekend";
}
return "a few weeks";
}
// program logic
let bookPages = Number(prompt("Pages in the book: "));
let hours = hoursToRead(bookPages);
console.log("Hours of reading:", hours);
console.log("Plan:", readingPlan(hours));
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.