JavaScript functions, return traps, function definitions, parameter passing, default parameters, local variables, global variables, return values, tricks

function

During programming, we often need to use the same piece of code in many places. For example, user registration, login, logout, and logout code snippets often exist on different web pages.

It would be unwieldy to rewrite the code every time we use these functions, so we can use functions .

A function can encapsulate a piece of code into a code block, and give the code a name (function name). Whenever you need to use this code, you only need to provide the function name.

Once a function is written, it can be called an infinite number of times without repeating the code.

In fact, we've been using functions in every previous lesson, such as: alert(), prompt(), confirm()etc.
These functions are JavaScriptfor our convenience to use the built-in functions, and we can also create our own functions.

In many cases, we refer to functions as "methods", and functions and methods are often used interchangeably, and there is essentially no difference between the two.

function definition

Function definitions need to use a new keyword function. The syntax rules for function definitions are as follows:

function funcName(para1,para2,para3,...){
    
    
	//函数体
}

functionThe keyword will tell JavaScriptthe engine that the meaning of this code is to create a function, the name of the function is funcName, then the parentheses are the parameter list, {}and the content is the function body .

for example:

//函数定义的时候不执行
function pow(a,b){
    
    
	let temp = a;
	while(--b){
    
    
		a *= temp;
	}
	console.log(a);
}

The above code creates a powfunction called aba^b that computesab . Line counts are not executed when they are defined, only when they are called.

For example, we calculate 2 3 2^323. After defining thepowfunction, you can simply use thepow(2,3)implementation, as shown below:

Reminder, the power function calculation method here is pownot perfect, for example, when b=-1, it will be an infinite loop

If we need more exponential calculations, we can call the powfunction repeatedly, for example:

//函数定义
function pow(a,b){
    
    
	let temp = a;
	while(--b){
    
    
		a *= temp;
	}
	console.log(a);
}
//函数调用
pow(2,3)//2的3次方
pow(3,4)//3的4次方
pow(4,5)//4的5次方

The execution result is as follows:

This example clearly demonstrates one of the main uses of functions, which is to avoid code duplication.

local variable

Local variables are variables defined inside {}a function, and these variables can only be used inside a function.

forFor example, the variable inside the statement from the previous lessoni

for example:

function doSomething(a,b){
    
    
	let val = prompt('请输入点什么',0);
	console.log(val);
}
doSomething();
alert(val);//ERROR,这里不能使用val

The execution result is as follows:

Since the variable valis defined inside the function, it can only be used inside the function, and the variable defined inside the function cannot be used outside.

external variable

Although the outside of the function cannot access the variables defined inside the function body, in turn, the inside of the function body can access the external variables defined outside the function body.

Take a chestnut:

let val = prompt("请输入点什么",9);
function doSomething(){
    
    
	console.log(val);//使用函数体外的变量没有问题
}
doSomething();

The code execution result is as follows:

When the user entered, he entered 9

Internal and external variable names

If the inner variable and the outer variable have the same name, the inner variable will take precedence.

Take a chestnut:

let num = 1;
function doSomething(){
    
    
	let num = 2;
	console.log(num);//这里使用的是内部变量
}
doSomething();

Code execution result:

If a variable is declared outside all functions, then this variable is a global variable
. Too many global variables declared in the program are not conducive to the optimal execution of the program

parameter

The function body is not completely autonomous. In many cases, a certain input is required to start executing the function body code. This input is the parameter .

for example:

function bless(name,senc){
    
    
	console.log(`${
      
      name}${
      
      senc}`)
}

Code execution result:

In the above example, we blesspass in two parameters for the number of lines, namely the name nameand the word of blessing senc, so that we can bless any words like anyone.

If we modify the variables inside the function body, will the external variables change accordingly?

for example:

let a = 1;
let b = 2;
function exchange(a,b){
    
    
	let temp = a;
	a = b;
	b = temp;
}
console.log(`a=${
      
      a},b=${
      
      b}`);

Code execution result:

It can be found that the value of the external variable asum bhas not changed.

The reason for this is that the parameter passed into the function is a copy of the variable, not the variable itself.

parameter default value

When defining a function, we can set a default value for the incoming parameter. If a parameter is provided when calling the function, the default value will be used instead.

for example:

function bless(name,senc='身体健康'){
    
    
	console.log(`${
      
      name},${
      
      senc}.`);
}

bless('特朗普')

Code execution result:

Although the above function requires two parameters, when calling, passing a parameter does not affect the use, because sencthe default value has been set when the function is defined.

What happens if we don't set a default value for a parameter, but don't pass in the corresponding parameter?

for example:

function bless(name,senc){
    
    
	console.log(`${
      
      name},${
      
      senc}.`);
}

bless('特朗普')

The code execution result is as follows:

It can be seen that without passing parameters, the parameters are undefined.

Default parameters for older codes

How to use parameter default values ​​in older versions JavaScript?

There are two ways:

  1. Use ifjudgment:
function doSomething(val){
    
    
	if(val === undefined){
    
    
		val = 'default val';
	}
	... ...
}
  1. use ||operator
function doSomething(val){
    
    
	val = val || 'default val';
	... ...
}

Application of Null Coalescing Operator

Even in modern times JavaScript, it is necessary to determine whether or not to pass in parameters inside the function. In addition to the above two methods commonly used in old code, we can also use the null value coalescing operator: ??.

for example:

function doSomething(val){
    
    
	val = val ?? 'unknown';
	... ...
}

return value

Parameters are the input to a function, and the return value is the output of a function.

The return value requires the use of returnkeywords to return the calculation result of the function to the body of the function.

The most common example of a return value is computing the sum of two numbers:

let a = 1;
let b = 2;
function add(a,b){
    
    
	return a + b;
}

let res = add(a,b);

Code execution result:

The above code creates a function that adds two variables and returns the result.

When a function is called add, the return result is obtained by assigning the return value to a variable res.

We can also return a null value (return nothing):

function doSomething(){
    
    
	console.log('return nothing');
	return ;//什么都不返回,程序立即结束
	console.log('after return');
}

doSomething();

The code execution result is as follows:

returnIt will cause the program to exit immediately, and the following code will no longer be executed.

A function can also have multiple return values:

function mulReturn(score){
    
    
	if(score >= 60){
    
    
		return '及格';
	}else{
    
    
		return '不及格';
	}
}
console.log(mulReturn(30));

Code execution result:

Although there are multiple return, only one will be selected at a time.

If the function returns nothing return ;, or no returnstatement, then its return value isundefined

return trap

When the return expression is long, we will most likely put it on a separate line, like this:

return
 (a + b + c + or + c * f(d) + f(e));

This should never be the case, because JavaScriptthe semicolon auto-completion mechanism will be returnappended ;, causing the function to always just return undefined.

What if we need to deal with long return value expressions?

The best way is to use parentheses:

return (
	a + b + c
	+ d + 
	e + f
);

Then the program will never have an unknown error~~

Tips

  1. A function is usually a behavior, so you can use the method of "verb + noun" when naming, combined with camel case naming, you can get a concise and clear function name, for example:
getAge();
showMsg();
createForm();
checkInput();
  1. Simplify function functionality, a function does only one thing, for example:

    • add(a,b)The function implements the addition of two numbers and should not have alert()functions such as;
    • checkInput()The function should check the validity of the input, and should not print valid invalidsuch information.
  2. Function names that are too short can be confusing. For example:

function a(){
    
    ...}
function b(){
    
    ...}

But JQueryit $doesn't fall into this category.

We should write functions/code out of comments and keep the code itself simple and readable.

Guess you like

Origin blog.csdn.net/weixin_43302112/article/details/124440030