Basic knowledge of JavaScript Chapter 6 - functions (including a large number of case studies)

Posted by Birch on Tue, 22 Feb 2022 02:06:26 +0100

preface❤️ The rainbow after the rain is more beautiful, and the suffering life is more brilliant ❤️

1, JavaScript function

(1) Concept of function

In JS, many codes with the same or similar functions may be defined, which may need to be reused.
Although the for loop statement can also realize some simple repetitive operations, it has limitations. At this time, we can use the functions in JS.
Function: encapsulates a code block that can be repeatedly called and executed. Through this code block, a large amount of code can be reused.

(2) Use of functions

Functions can be used in two steps: declaring functions and calling functions;

2.1 declaration function

The syntax is as follows:

// Declarative function
function Function name() {
    //Function body code
}
  • Function is the keyword to declare the function, which must be lowercase;
  • Since functions are generally defined to implement a function, we usually name the function as a verb, such as getSum

2.2 calling functions

The syntax is as follows:

// Call function
 Function name();  // Execute the function body code by calling the function name
  • Don't forget to add parentheses when calling;
  • Pithy formula: if a function is not called, it will not be executed by itself;

😆 Warm reminder 😆: Declaring the function itself will not execute the code, and the function body code will be executed only when the function is called.

2.3 function encapsulation

  • Function encapsulation is to encapsulate one or more functions through functions, and only provide a simple function interface;
  • Simple understanding: packaging is similar to integrating computer accessories into the chassis (similar to express packaging);
2.3.1 case 1: use the function to calculate the cumulative sum between 1-100

The demo code is as follows:

// Declarative function
function getSum(){
	var sumNum = 0;// Prepare a variable to hold the number and
    for (var i = 1; i <= 100; i++) {
    	sumNum += i;// Add each value to the variable
    }
  	alert(sumNum);
}
// Call function
getSum();

(3) Parameters of function

3.1 formal parameters and arguments

When declaring a function, you can add some parameters in parentheses after the function name. These parameters are called formal parameters. When calling the function, you also need to pass corresponding parameters, which are called arguments.

parameterexplain
Formal parameterThe parameters passed in the formal parameter function definition are unknown at that time
ArgumentIn fact, the parameters and arguments passed during function call are passed to formal parameters

Function of parameters: some values cannot be fixed inside the function. We can pass different values in through parameters when calling the function.

The syntax is as follows:

// Function declaration with arguments
function Function name(Formal parameter 1, Formal parameter 2 , Formal parameter 3...) { // You can define as many parameters as you want, separated by commas
	// Function body
}
// Function call with parameters
 Function name(Argument 1, Argument 2, Argument 3...); 

3.2 transfer process of function parameters

The code is shown as follows:

// Declarative function
function getSum(num1, num2) {
    console.log(num1 + num2);
}
// Call function
getSum(1, 3); // 4
getSum(6, 5); // 11
  • When called, the actual parameter value is passed to the formal parameter;
  • Formal parameters are simply understood as: variables that do not need to be declared;
  • Multiple parameters of arguments and formal parameters are separated by commas (,);

3.3 mismatch between the number of function formal parameters and actual parameters

Number of parametersexplain
The number of arguments is equal to the number of formal parametersOutput correct results
The number of arguments is more than the number of formal parametersOnly get the number of formal parameters
The number of arguments is less than the number of formal parametersMultiple formal parameters are defined as underfined and the result is NaN

The code is shown as follows:

function sum(num1, num2) {
    console.log(num1 + num2);
}
sum(100, 200);             // The number of formal and actual parameters is equal, and the correct result is output
sum(100, 400, 500, 700);   // The number of arguments is more than that of formal parameters. Only the number of formal parameters is obtained
sum(200);                  // If the number of arguments is less than the formal parameter, the more formal parameter is defined as undefined and the result is NaN

😆 Warm reminder 😆: In JavaScript, the default value of formal parameter is undefined;

3.4 summary

  • Functions can take parameters or no parameters;
  • When declaring a function, the formal parameter is in the parenthesis of the function name, and the default value of the formal parameter is undefined;
  • When calling a function, the argument in the parenthesis of the function name;
  • Multiple parameters are separated by commas;
  • The number of formal parameters can not match the number of actual parameters, but the result is unpredictable. We should try our best to match;

(4) Return value of function

4.1 return statement

Sometimes we want the function to return the value to the caller, which can be achieved by using the return statement.

The syntax is as follows:

// Declarative function
function Function name (){
    ...
    return  The value to be returned;
}
// Call function
 Function name();	// At this point, you can call the function to get the value after return in the function body
  • When using the return statement, the function will stop execution and return the specified value;
  • If the function does not return, the returned value is undefined;

The code is shown as follows:

// Declarative function
function sum(){
    ...
    return  888;
}
// Call function
sum();	// At this time, the value of sum is equal to 888, because the return statement will return the value after itself to the caller
4.1.1 case 1: use the function to find the maximum value of any two numbers

The code is shown as follows:

function getMax(num1, num2) {
	return num1 > num2 ? num1 : num2;
}
console.log(getMax(1, 2));
console.log(getMax(11, 2));
4.1.2 case 2: use the function to find the maximum value in any array

Requirement: find the maximum value in the array [5, 2, 99, 101, 67, 77]

The code is shown as follows:

//Define a function to get the maximum number in the array
function getMaxFromArr(numArray){
	var maxNum = 0;
    for(var i =0;i < numArray.length;i++){
        if(numArray[i] > maxNum){
            maxNum = numArray[i];
        }
    }
    return maxNum;
}
// In our actual development, we often use a variable to accept the return result of the function, which is easier to use
var arrNum = [5,2,99,101,67,77];
var maxN = getMaxFromArr(arrNum); // This argument is an array
alert('The maximum value is:'+ maxN);

4.2 return termination function

The code after the return statement is not executed.

The code is shown as follows:

function add(num1,num2){
    //Function body
    return num1 + num2; // Note: the code after return will not be executed
    alert('I won't be executed because there's something ahead return');
}
var resNum = add(21,6); // Call the function, pass in two arguments, and receive the return value of the function through resNum
alert(resNum);          // 27

4.3 return value

Return can only return one value. If multiple values are separated by commas, the last one shall prevail.

The code is shown as follows:

function add(num1,num2){
    //Function body
    return num1,num2;
}
var resNum = add(21,6); // Call the function, pass in two arguments, and receive the return value of the function through resNum
alert(resNum);
4.3.1 case 1: create a function to realize the addition, subtraction, multiplication and division between two numbers, and return the result

The code is shown as follows:

var a = parseFloat(prompt('Please enter the first number'));
var b = parseFloat(prompt('Please enter the second number'));
function count(a, b) {
    var arr = [a + b, a - b, a * b, a / b];
    return arr;
}
var result = count(a, b);
console.log(result);

4.4 the function returns undefined without return

All functions have return values:

  1. If there is a return, return the value after return;
  2. If there is no return, return undefined;

4.5 difference between break, continue and return

  • break: end the current loop body (such as for and while);
  • Continue: jump out of this cycle and continue to execute the next cycle (such as for and while);
  • Return: it can not only exit the loop, but also return the value in the return statement. At the same time, it can also end the code in the current function body;

(5) Use of arguments

one ️⃣ When we are not sure how many parameters are passed, we can use arguments to get them. In JavaScript, arguments is actually a built-in object of the current function. All functions have a built-in arguments object, which stores all the arguments passed.

two ️⃣ arguments is displayed as a pseudo array, so it can be traversed. Pseudo arrays have the following characteristics:

  • With length attribute;
  • Store data by index;
  • Push, pop and other methods without array;

(6) Function case

6.1 case 1: use function to find the maximum value of any number

The code is shown as follows:

function maxValue() {
	var max = arguments[0];
    for (var i = 0; i < arguments.length; i++) {
		if (max < arguments[i]) {
			max = arguments[i];
        }
    }
    return max;
}
console.log(maxValue(2, 4, 5, 9));
console.log(maxValue(12, 4, 9));

6.2 case 2: flip any array by function encapsulation

The code is shown as follows:

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);

6.3 case 3: sorting arrays by function encapsulation - bubble sorting

The code is shown as follows:

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;
}

6.4 case 4: judge leap year

Requirements: enter a year to judge whether it is a leap year (leap year: it can be divided by 4 and cannot be divided by 100 integers, or it can be divided by 400)

The code is shown as follows:

function isRun(year) {
     var flag = false;
     if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
     	flag = true;
     }
     return flag;
}
console.log(isRun(2022));
console.log(isRun(1999));

6.5 case 5: the user inputs the year and outputs the number of days in February of the current year

Requirements: if it is a leap year, February is 29 days; if it is a normal year, February is 28 days

function backDay() {
	var year = prompt('Please enter the year:');
    if (isRunYear(year)) { // Parentheses are required to call the function
    	alert('The current year is a leap year. February has 29 days');
    } else {
        alert('The current year is a normal year. February has 28 days');
    }
}
backDay();

(7) Two ways to declare functions

7.1 user defined function mode (named function)

Use the function keyword function to customize the function mode.

The syntax is as follows:

// Declaration definition method
function fn() {...}
// call  
fn(); 
  • Because of its name, it is also called named function;
  • The code calling the function can be placed either in front of or behind the declared function;

7.2 function expression method (anonymous function)

The function expression method is as follows:

// This is a function expression. Anonymous functions end with semicolons
var fn = function(){...};
// The function call must be written below the function body
fn();
  • Because the function has no name, it is also called anonymous function;
  • This fn stores a function;
  • The principle of function expression is consistent with that of declaring variables;
  • The code of function call must be written after the function body;

2, Summary

😝 Because there are many contents, I decided to write separately. I will keep updating! Like friends, remember to praise! 😝

Topics: Javascript Front-end ECMAScript Visual Studio Code