Thursday, April 18, 2019

JavaScript(4)---functions

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.
  • anatomy of a function declaration


  • Use function and console log together.
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:

    alt


  • We’ll explore a few of these techniques below:

  1. 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.
    showcasing how arrow functions parameters differ for different amounts of parameters
  2. 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 the return keyword can be removed. This is referred to as implicit return.
comparing single line and multiline arrow functions
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