Javascript Basics Tutorial: Functions with Return Values

Functions with return values

Sometimes, we want a function to return a value to the place where it was called.

This can be achieved by using the return statement.

When using the return statement, the function will stop execution and return the specified value

Syntax:

function function name (){

Function code ;

}


Let’s write an example

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>函数</title>
	<script type="text/javascript">
			function msg(){
				var sum = 15;
				return sum;
			}

			var ss = msg();
			document.write(ss);

	</script>
</head>
<body>

</body>
</html>

As shown in the above code, we define a sum value of 15 Then return the value of sum. At this time, the value of the function is also 15;

We define a variable to receive the value returned by the function

Finally output the value of the variable

The following Let’s write a function with parameters and a return value. The code is as follows:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>函数</title>
	<script type="text/javascript">
			function msg(a,b){
				var sum = a+b;
				return sum;
			}

			var ss = msg("欢迎来到,","php中文网");
			document.write(ss);

	</script>
</head>
<body>

</body>
</html>


Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>函数</title> <script type="text/javascript"> function msg(a,b){ var sum = a+b; return sum; } var ss = msg("欢迎来到,","php中文网"); document.write(ss); </script> </head> <body> </body> </html>
submitReset Code