Functions
In programming, we often use code to perform a specific task multiple times. Instead of rewriting the same code, we can group a block of code together and associate it with one task, then we can reuse that block of code whenever we need to perform the task again. We achieve this by creating a function. A function is a reusable block of code that groups together a sequence of statements to perform a specific task.
EX: Let’s create a function that prints a reminder to the console. Using a function declaration, create a function called
getReminder()
. log the following reminder to the console: 'Water the plants.'
function getReminder() {
console.log('Water the plants');
}
Notes: Functions can be called as many times as you need them.
EX: Declare a variable named
totalCost
using the const
keyword. Assign to totalCost
the value of calling costOfMonitors()
with the arguments 5
and 4
respectively.const numOfMonitors = monitorCount(5, 4);
Function Expressions
To define a function using arrow function notation:
- We’ll explore a few of these techniques below:
- Functions that take only a single parameter do not need that parameter to be enclosed in parentheses. However, if a function takes zero or multiple parameters, parentheses are required.
- A function body composed of a single-line block does not need curly braces. Without the curly braces, whatever that line evaluates will be automatically returned. The contents of the block should immediately follow the arrow
=>
and thereturn
keyword can be removed. This is referred to as implicit return.
EX: Let’s refactor
plantNeedsWater()
to be a concise body. Notice that we’ve already converted the if
/else
statement to a ternary operator to make the code fit on one line.
const plantNeedsWater = day => day === 'Wednesday' ? true : false;
What I learned in this lesson and what I'm doing tomorrow...
I learned about the expression and the declaration of the functions, and used the const and function keywords a lot to complete the code. I'll be doing more Scope of the language.
No comments:
Post a Comment