Lesson 1.10: Functions in JavaScript
The functions from 1.6, written in JavaScript: function to define one and return to give back a result.
The idea
| Pseudocode | JavaScript |
|---|---|
Function double(number) | function double(number) { |
Return number * 2 | return number * 2; |
EndFunction | } |
function double(number) {
return number * 2;
}
console.log(double(4));
console.log(double(10));
8
20
Several parameters
Separated by commas, like in pseudocode:
function area(base, height) {
return base * height;
}
console.log(area(3, 4));
12
Without return
A function can also do something without returning anything:
function greet(name) {
console.log("Hello, " + name);
}
greet("Ana");
Hello, Ana
If you use its result, you'll see undefined: that's JavaScript's word for "no value".
The short form
In other people's code you'll see functions written with an arrow, =>:
const double = (number) => number * 2;
It does the same as the one above. Here we use function until writing functions feels natural.
Try it
Write a function isEven(n) that returns true if n is even and false if it isn't. Hint: the % from 1.8.
Show the solution
function isEven(n) {
if (n % 2 === 0) {
return true;
} else {
return false;
}
}
Since n % 2 === 0 is already true or false, you can return it directly:
function isEven(n) {
return n % 2 === 0;
}
Summary
functiondefines a function;returngives back the result and ends it.- Without
return, the function returnsundefined. - The arrow
=>is another way to write them.