Wednesday, April 23, 2025

JavaScript Functions as Arguments


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>

<script>

	function addition(x, y) {
		add = x + y;
		return add;
	}
	
	function second_level(a) {
		result = a * 2;
		document.write(result);
		document.write("<br><br>");
	}
	
	second_level(addition(30, 20));
	second_level(addition(50, 50));
	
</script>
	
</body>
</html>

That code calls a function addition that takes two arguments x and y, calculates their sum and returns the result.

Then, it defines a function second_level that takes one argument a, multiplies it by 2 and writes the result to the document.

Finally, it calls second_level twice, passing the result of calling addition with different arguments as the argument for second_level. This means that the result of calling addition is used as an argument to call second_level.

In other words, the result of addition(30, 20) is 50, which is passed as the argument a to the first call to second_level. The result of addition(50, 50) is 100, which is passed as the argument a to the second call to second_level


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>

<script>

	function addition(x, y) {
		add = x + y;
		return add;
	}
	
	function second_level(a) {
		result = a * 2;
		return result;
	}
	
	function third_level(b) {
		result_b = b * 5;
		document.write(result_b);
		document.write("<br><br>");
	}
	
	//Addition = 7
	run_1 = addition(2, 5);
	
	//Multiplication by 2; 7 * 2 = 14
	run_2 = second_level(run_1);
	
	//Multiplication by 5; 14 * 5 = 70
	third_level(run_2);
	
</script>
	
</body>
</html>

This code calls three functions: addition, second_level, and third_level.

First, it calls addition with arguments 2 and 5, which returns 7. This result is assigned to the variable run_1.

Next, it calls second_level with run_1 (which is equal to 7) as the argument. second_level multiplies its argument by 2 and returns the result, which is 14. This result is assigned to the variable run_2.

Finally, it calls third_level with run_2 (which is equal to 14) as the argument. third_level multiplies its argument by 5, prints the result to the document, and adds a line break. In this case, the result is 70.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...