Full-Stack course / JavaScript fundamentals
Swap the boxes
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/01-01-swap-the-boxes
cd 01-01-swap-the-boxes
gonomicon submitSwap the boxes
Goal: swap what two let variables hold, without typing their values again, and record whether the swap changed anything.
Worked example
The file starts with two boxes:
let first = 1;
let second = 2;
After your code runs, first holds 2, second holds 1, and a new const box called changed holds true, because the two originals were different.
Starting first | Starting second | first ends as | second ends as | changed |
|---|---|---|---|---|
1 | 2 | 2 | 1 | true |
"a" | "a" | "a" | "a" | false |
5 | "5" | "5" | 5 | true |
The last row is there on purpose: the number 5 and the text "5" are different shapes, so they count as different.
Rules
- Keep the two lines at the top of the file as they are:
let first = ...;andlet second = ...;. The tests replace the values on those two lines and run your code with other values, so don't type the starting values anywhere else. - Write your code below those two lines.
- Declare
changedwithconst. Compare the two original values strictly. - Don't use
varanywhere. - To look at your boxes while you work, add
console.log(first, second, changed);at the bottom and runnode swap_the_boxes.js.
What you'll practice
- Making and changing
letboxes, and making aconstbox - Strict equality between different shapes of value
- Thinking about the order of your lines
Run it
gonomicon fetch fs-week-2/01-01-swap-the-boxes
cd 01-01-swap-the-boxes
gonomicon test
gonomicon submit
Hints
- A box holds one thing at a time. If you put the contents of
secondintofirst, what happens to whatfirstwas holding? - You need a third box to park one value while you move the other. Work out
changedbefore you start moving things, while both original values are still in their boxes. - Start with
const changed = first !== second;. Then parkfirstin a new box, putsecondintofirst, and put the parked value intosecond.