Write a pure add function and call it twice with the same values, joining the answers.
Acceptance criteria
- 1.#out should show 5,5.
JavaScript Tutorial · JavaScript Functions
These 10 tasks go with the JavaScript Pure Functions chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “A JavaScript pure function always returns the same result for the same input and changes nothing outside itself.” .
1.Write a pure functionexercise · easy · 10 min
Write a pure add function and call it twice with the same values, joining the answers.
Passes when: #out should show 5,5.
2.Take everything as a parameterexercise · easy · 10 min · practice plan
Pass the tax rate in rather than reading an outside variable. Show 100 at 1.2.
Passes when: #out should show 120.
3.Return a new arrayexercise · easy · 10 min · practice plan
Add a value without changing the original array. Show the original length.
Passes when: #out should show 3.
4.Copy before sortingexercise · easy · 10 min · practice plan
Sort a copy so the original order is kept. Show the original joined by commas.
Passes when: #out should show 3,1,2.
5.A pure totalexercise · medium · 10 min · practice plan
Add up a list with reduce without changing it, and show the total.
Passes when: #out should show 60.
6.Fix the outside variablebug fix · easy · 8 min
Reading an outside rate makes the answer change unexpectedly.
Passes when: #out should show 120.
7.Fix the array that was changedbug fix · easy · 8 min · practice plan
push changes the array that was passed in.
Passes when: #out should show 3.
8.Fix the sort that reorders the originalbug fix · easy · 8 min · practice plan
sort changes the array it is called on.
Passes when: #out should show 3,1,2.
9.Fix the counter side effectbug fix · easy · 8 min · practice plan
The function changes a variable outside itself.
Passes when: #out should show 0.
10.Fix the object that was mutatedbug fix · easy · 8 min · practice plan
The function changes the object it was given.
Passes when: #out should show Ada.
Between them these tasks cover Purity, Side effects and Immutability.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.