1. The problem
Two prices at the till, 3 and 5, and you need the total. In your head that takes a second. Writing the same thing down for the computer is the moment you move from reading about code to writing it. This is the smallest real program there is, and that is on purpose.
2. The idea
Remember the three parts from the first lesson: input (two numbers), step (add them), output (the sum). In code, a recipe you can use again and again is called a function. It takes inputs (called arguments), runs its steps, and gives back a result with return.
The recipe we want:
- name it
addTwo - it takes two numbers,
aandb - it returns
a + b
return gives the result back to whoever called the function. To call a function means to ask it to compute something.
4. Where this shows up
Every "total," "subtotal," "sum of the column" and "score so far" in every app works the same way: it is addition, repeated many times. A shopping cart total is addTwo applied by a loop to the whole list of items (the same running-total box from step 4). The step is small, and it is everywhere.
On LeetCode
Problems that only ask you to compute a value from the inputs and return it. LeetCode has few of them and they are very easy, and they train the function and return that every later answer has.
This is addTwo from the lesson with another name, so return num1 + num2.
Two formulas on one input, returned together as a list of two numbers.
Add the two times, then take the remainder after dividing by 24 with %, so 25 o'clock becomes 1.
Write it yourself
In the editor you will find addTwo(a, b) with a // TODO mark. Code uses this mark for a spot you still have to write. Write the one line that returns the sum, then press Run tests. The tests check a few pairs of numbers, including zeros and negative numbers. A function that adds 3 and 5 correctly may still fail on other pairs.
You write the solution yourself, starting from a blank line. That is the whole skill, in its smallest form.
Practice
Add two numbers
addTwo(a, b) -> a + b
// Step 06: your first program, add two numbers. You write the whole function.
//
// addTwo(a, b)
// a, b: numbers
// returns their sum.
export function addTwo(a, b) {
// TODO: return the sum of a and b
}
Running as a guest
The tests run right here, no account needed. Your code is kept in this browser only. A free account keeps it on every device, marks the step done and shows where you are in the course.