Full-Stack course / JavaScript fundamentals
Scope repair
How to fetch and submit this exercise
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach exercise: download it, edit the file named in the instructions, then submit.
gonomicon fetch fs-week-2/02-04-scope-repair
cd 02-04-scope-repair
gonomicon submitScope repair
Goal: fix a script whose functions crash with ReferenceError because they look for variables in rooms where those variables can't be seen.
What you're given
The starter file has two functions and one line above them:
lastMultiple(step, limit)should give back the largest multiple ofstepthat is at mostlimit, or0if there is none.sumOfSquares(n)should give back1*1 + 2*2 + ... + n*n, or0whennis0.const demo = lastMultiple(7, 50);sits at the top of the file, above both functions.
The starter doesn't work yet. Run node scope_repair.js in your terminal and you'll see a ReferenceError.
Worked example
| Call | Returns |
|---|---|
lastMultiple(7, 50) | 49 |
lastMultiple(5, 5) | 5 |
lastMultiple(10, 3) | 0 |
lastMultiple(1, 0) | 0 |
sumOfSquares(3) | 14 (1 + 4 + 9) |
sumOfSquares(1) | 1 |
sumOfSquares(0) | 0 |
And once the file runs, demo must equal 49.
Rules
- Keep
function lastMultiple(step, limit)andfunction sumOfSquares(n)as function declarations with these names. - Keep the line
const demo = lastMultiple(7, 50);above the two functions. Don't move it down. - Both functions must
returntheir answers, and must give the same answer every time they're called with the same inputs. - Neither function may leave anything behind in the global scope: every box they use must be made with
letorconstin a room where it can be seen. - Don't use
var. - To look at things yourself, add a line such as
console.log(demo, sumOfSquares(3));at the bottom, then remove it.
What you'll practice
- Reading a
ReferenceErrorand working out which room it points at - Block scope: where a box made inside curly braces can and can't be seen
- Why a declared function can be used from a line above it
- Loops that build up a result
Run it
gonomicon fetch fs-week-2/02-04-scope-repair
cd 02-04-scope-repair
gonomicon test
gonomicon submit
Hints
- Run
node scope_repair.jsand read theReferenceErrorout loud: it names a variable, and says it can't be seen. Ask two questions: in which room was that box made, and from which room is the code asking for it? - A box made with
letorconstinside the curly braces of a loop lives only inside those braces. If you need its value after the loop, make the box before the loop and only change it inside. And a name that was never made anywhere (liketotal) has to be made withletbefore you use it. - In
lastMultiple: putlet best = 0;above thefor, and inside the loop writebest = n * step;with nolet. InsumOfSquares: putlet total = 0;above the loop. Leave theconst demoline where it is, above the functions.