Reputation: 2761
I'm very new to JavaScript (and coding) and I'm studying through the book Head First JavaScript. From reading, I thought an anonymous function could be an argument since functions are values, but I think I might have this wrong.
The following code, according to what I thought, should output 7
. Instead it outputs, function () { return (m * n); }1
I've done similar things with strings and they don't process as expected either, according to my presumptions.
Please tell me where I have gone wrong in my understanding of anonymous functions, the limits in the use of anonymous functions in javascript, and why we want to use anonymous functions ever, in general. Thanks so much.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p id="demo"></p>
<script>
function addIt(x, y) {
return (x + y);
}
var m = 2;
var n = 3;
var total = addIt(function() { return (m * n); }, 1);
document.getElementById("demo").innerHTML = total;
</script>
</body>
</html>
Upvotes: 2
Views: 82
Reputation: 21917
The issue, as Barmar stated correctly, is that you are not calling the anonymous function, thus you are doing addition on a function value rather than a number value (which is the return value of the function).
where I have gone wrong in my understanding of anonymous functions
You really haven't. Just know that when an anonymous function is assigned to a variable, it's used almost the same as a normal function (there are subtle differences though).
the limits in the use of anonymous functions in javascript
The same limits that apply to any other kind of value. You can pass it as an argument to a function, save it in a variable, etc. Of course, being a function, you usually eventually will have to call it to get its return value.
why we want to use anonymous functions ever
Closures, mainly. Also, important functions like setTimeout
expect a function as an argument, and it's helpful to be able to make one to use once and then never again.
Upvotes: 0
Reputation: 782488
You're not calling the function in addIt()
. To call a function, you have to put ()
after it. So it should be:
function addIt(x, y) {
return (x() + y);
}
If you want to allow both numbers and functions as arguments, you could use if
to test.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p id="demo"></p>
<script>
function addIt(x, y) {
if (typeof x == 'function') {
x = x();
}
if (typeof y == 'function') {
y = y();
}
return (x + y);
}
var m = 2;
var n = 3;
var total = addIt(function() { return (m * n); }, 1);
document.getElementById("demo").innerHTML = total;
</script>
</body>
</html>
Upvotes: 6