Functions review
Lets review functions!
function biggerOf(num1, num2) {
if (num1 > num2) {
return num1
} else {
return num2
}
}
console.log(biggerOf(3, 20))
console.log(biggerOf(300, 20))
const biggerNum = biggerOf(23 * 4, 13 * 14))
console.log(biggerNum)
What happens if....
I don't have a
return
at all in the function?I try to
console.log(num1)
outside the function? After the function? After the function is called?What if I use
const
orlet
to create a variable inside the function?How many parameters can I have?
What happens if I put some code after the
return
?
How do I return multiple bits of information from a function? Build this function:
function longestAndShortestWord(words) {}
The transform it into this function, returning an object:
{ longest: 'sentence', shortest: 'a' }
function longestAndShortestWord(words) {
let longestSoFar = "";
for (let word of words) {
if (word.length > longestSoFar.length) {
longestSoFar = word;
}
}
return longestSoFar;
}
longestAndShortestWord(["this", "is", "a", "sentence", "yeah"]);
Arrow functions
An arrow function expression is a compact alternative to a traditional function expression, with some semantic differences and deliberate limitations in usage:
Arrow functions cannot be used as constructors.
Syntax
param => expression
(param) => expression
(param1, paramN) => expression
param => {
statements
}
(param1, paramN) => {
statements
}
Now lets rewrite the above function as an arrow function
const longestAndShortestWord = (words) => {
let longestSoFar = "";
for (let word of words) {
if (word.length > longestSoFar.length) {
longestSoFar = word;
}
}
return longestSoFar;
};
One more example, let write a function to multiply two numbers
// Notice the lack of return when there are no wrapping curly brackets
const multiply = (num1, num2) => num1 * num2
References
Last updated
Was this helpful?