The target

  • Be able to say why functions are needed (to make a lot of code reusable)
  • Ability to write functions according to syntax
  • Ability to encapsulate functions as required
  • Be able to tell how parameters and arguments are passed
  • The ability to use the return value of a function
  • You can use arguments to get function arguments

You don’t need to read this article if you can answer the target’s questions

directory

  • Concept of function
  • Use of functions
  • Parameters of a function
  • The return value of the function
  • The use of the arguments
  • Function of case
  • Two ways to declare a function

1. The concept of functions

A function is a block of code that encapsulates a call that can be repeated

Purpose: To make a lot of code reusable

2. Use of functions

Functions are used in two steps: declare the function and call the function.

  • Function is the keyword for declaring functions and must be lowercase
  • Since functions are defined to do something, we usually name them as verbs, such as getSum
  • Don’t forget to add parentheses when calling
  • Tip: if a function is not called, it is not executed
Function hanshuming () {// function body code}Copy the code
// Call the function name (); Execute the function body code by calling the function nameCopy the code

2.3 Function encapsulation

  • Function encapsulation encapsulates one or more functions in the form of functions and provides only a simple function interface
  • Simple understanding: Packaging is similar to integrating computer parts into a case (similar to express packaging)

3. Parameters of the function

3.1 Arguments and parameters of a function

When you declare a function, you add some parameters, called parameters, to the function name in parentheses. When you call the function, you also need to pass the corresponding parameters, called arguments.

parameter instructions
parameter Formally parameter functions are defined when the parameters passed are not currently known what
The arguments The actual argument function is called with arguments that are passed to the parameters

What arguments do: Some values cannot be fixed inside a function. We can use arguments to pass in different values when calling a function.

Note:

  • Parameters are separated by commas
  • Parameters can be thought of as undeclared variables

3.3 Parameter Mismatch of function parameters

Number of parameters instructions
Arguments are equal to the number of parameters Output correct results
There are more arguments than parameters Only the number of parameters is taken
The number of arguments is smaller than the number of parameters Multiple parameters are defined as uhdefined and the result is NaN

3.4 summary

  • A function can take arguments or no arguments
  • When declaring a function, the parameters inside the parentheses are parameters that default to undefined
  • When you call a function, the arguments inside the parentheses are arguments
  • Multiple parameters are separated by commas
  • The number of parameters may not match the number of arguments, but the result is unpredictable, so we try to match

4. Return value of the function

4.1 return statement

A ternary expression that determines which of two numbers is the largest

Return num1 > num2? Num1: num2;

  1. Termination of the function
  2. Only one value can be returned, the last value
  3. No value will return undefined

4.2 The maximum value of an array

function getArrMax(arr) { var max = arr[0]; for (var i=1; i<arr.length; i++){ if (arr[i] >max){ max = arr[i]; }} return Max} var re = getArrMax([5,2,99,101,67,77]); console.log(re);Copy the code

In our actual development, we often use a variable to accept the return result of a function to make it easier to use

4.5 Differences between break, Continue, and Return

  • Break: to end the body of the current loop (for, while)
  • Continue: To break out of the current loop and continue with the next loop (for, while)
  • Return: Not only can you exit the loop, you can also return the value of the return statement, and you can also end the code inside the current function

Little homework

  • Write a function where the user enters an arbitrary arithmetic operation of any two numbers (simple calculator small function) and can pop up the result of the operation.
  • Write a function where the user enters the maximum value of any two numbers and returns the result of the pop-up operation.
  • Write a function where the user enters the maximum value of any three different numbers and can single out the result of the operation.
  • Write a function where the user inputs a number to determine if it is a prime and returns the value back.

5. Arguments

Arguments can be used to retrieve arguments when we are not sure how many arguments are passed. In JavaScript,arguments is actually a built-in object for the current function. All functions come with a built-in arguments object, which stores all arguments passed.

Arguments presentation form is a pseudo-array, so it can be iterated over. The pseudo-array has the following characteristics

  • Has the length property
  • Store data by index
  • Methods push, pop, etc. without arrays

5.1 Use the function to find the maximum value of any number

function getMax() { var max = arguments[0]; for (var i=1 ; i< arguments.length ; i++) { if (max <arguments[i]) { max = arguments[i]; } } return max; } the console. The log (getMax (1, 2, 3));Copy the code

6. Function cases

6.1 Invert any array using function encapsulation

Function reverse(arr) {var newArr = []; for (var i = arr.length - 1; i >= 0 ; i--) { newArr[newArr.length] = arr[i]; Return newArr} var arr1 = reverse([1,3,4,6,9]); console.log(arr1);Copy the code

6.2 Bubble sort using function encapsulation.

Sort function sort(arr) {for (var I = 0; i < arr.length - 1; i++) { for (var j = 0; j < arr.length - i - 1; j++) if (arr[j] > arr[j + 1]) { var temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } return arr; } var arr1 = sort([1, 10, 8, 3]); console.log(arr1);Copy the code

6.3 Functions You can call functions

Because each function is a separate block of code for a particular task, it is often used when functions call each other.

6.4 Determine how many days there are in February

Function backDay(){var year = prompt(' please enter the year '); if (isRunyear(year)){ alert('29'); } else { alert('28'); } } backDay(); Function isRunyear (year) {var flag = false; if (year % 4 == 0 && year %100 ! = 0 || year % 400 == 0){ flag = true; } return flag; }Copy the code

6.5 Two ways to declare functions

  1. Custom functions using function keywords (named functions)
function fn (){}

Copy the code
  1. Function expressions (anonymous functions)
Var var name = function() {}Copy the code
  • Function expressions are declared in much the same way as variables, except that variables contain values and function expressions contain functions
  • Function expressions can also pass parameters