what is the use of anonymous function in this code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

what is the use of anonymous function in this code

<!DOCTYPE html> <html> <head> <title>Area calculator</title> </head> <body> <form name="frmArea"> Enter the width and height of your rectangle to calculate the size:<br> Width: <input type="text" name="txtWidth" size="5" id="width"><br> Height: <input type="text" name="txtHeight" size="5" id="height"><br> <input type="button" value="Calculate area" id="calc"> </form> <script> function calculateArea( width, height ) { var area = width * height; return area; } document.getElementById( "calc" ).onclick = function(){ console.log( calculateArea( document.getElementById( "width" ).value, document.getElementById( "height" ).value )); } </script> </body> </html>

29th Aug 2020, 11:32 AM
xavi
5 Answers
+ 1
you can change your code to this if you want to use your own function as a callback. <input type="button" value="Calculate area" id="calc" onclick="calculateArea()" </form> <script> function calculateArea() { var height = document.getElementById( "width" ).value var width = document.getElementById( "height" ).value; var area = height * width; console.log(area); } </script>
29th Aug 2020, 11:55 AM
Bahhaⵣ
Bahhaⵣ - avatar
+ 1
thank you bro
29th Aug 2020, 12:55 PM
xavi
0
Anonymous function here outputs the result of calculateArea. It takes argument values from inputs #width and #height.
29th Aug 2020, 11:36 AM
BlazingMagpie
BlazingMagpie - avatar
0
it's used to display the result of calculateArea when the button is clicked.
29th Aug 2020, 11:39 AM
Bahhaⵣ
Bahhaⵣ - avatar
0
why can't i just use calculateArea function without anonymous function to display my output...when i try to do that it doesn't work #plzzexplainthis#confused
29th Aug 2020, 11:41 AM
xavi