7.1 - Functions? The math ones?
functions in programming
Functions are a useful tool where we can store code separately so we donβt have to rewrite it. This reduces repetitiveness in code, because you can just call functions multiple times!
To define a function in JavaScript:
- Use the
function
keyword - Give it a name
- List parameters, or inputs, inside parentheses (
(β¦)
) - Write the body between
{ β¦ }
- Use
return
to specify the output
function addNums(a, b) {
return a + b;
}
let result1 = addNums(4, 5);
let result2 = addNums(10, 11);
console.log(result1); // 9
console.log(result2); // 21
In the above function, the name is addNums
, parameters are a
and b
, and the body is return a + b
You can call it multiple times with different input to reuse the same logic.
question
What does the return keyword do inside a function? Can you explain the difference between calling a function and defining it?
tasks
- Create a function called greet that takes one parameter (name) and returns "Hello, [name]!"
- Call your greet function with different names and print the result
- Create a function called multiply that takes two numbers and returns their product
- Print out the result of calling
multiply(3, 4)
andmultiply(7, 2)
Bonus: Try writing a function that takes a number and returns whether it's even or odd