<script> !function add_them(a,b) { return a+b;} (9,4) console.log(add_them()); </script> Question:
it shows: ReferenceError: add_them is not defined, what is the problem? and how to make it show the right result: 13?
<script> !function add_them(a,b) { return a+b;} (9,4) console.log(add_them()); </script> Question:
it shows: ReferenceError: add_them is not defined, what is the problem? and how to make it show the right result: 13?
You seem to want a simple function declaration:
function add_them(a,b) { return a+b;} console.log(add_them(9,4)); If you wanted to use an immediately invoked function expression, it might look like this:
console.log(function add_them(a,b) { return a+b; } (9,4)); // \ expression / ^^^^^ // invocation however the identifier (add_them) is not reusable outside (after) of the function expression.
Also notice that when your IEFE is supposed to yield some result, the (little) advantage of !function(){}() over (function () {})()? is neglected since the result gets negated.
You're confusing the browser (well, it's technically correct according to the spec).
Try another trick to make it treat the function as an expression:
(function add_them(a,b) { return a+b;})(9,4) // 13 Or simply:
console.log((function add_them(a,b) { return a+b;})(9,4)) // logs 13 If you're just trying to fixate the parameters you can .bind the function to values (which is what it seems to me you're trying to do):
var add_them = (function(a,b) { return a+b;}).bind(null, 9,4) console.log(add_them());// logs 13 The problem is that immediately invoked function expressions are function expressions.
In JavaScript functions may be either declarations or expressions. For instance, consider:
(function (a, b) { return a + b; }) // This is an expression function (a, b) { return a + b; } // This is a declaration How to distinguish a function expression from a function declaration? If the function is used in place where an expression is expected it automatically becomes an expression. Function expressions can be invoked immediately.
On the other hand a function declaration is also easy to spot because declarations in JavaScript are hoisted. Hence the function can be invoked before it appears in the program. For example, consider:
console.log(add(2, 3)); function add(a, b) { return a + b; } Now the problem with your code is that you're immediately invoking a function expression. However because it's an expression and not a declaration you can't use it like a normal function. You need to declare a function before you can use it.
Do this instead:
add_them(9, 4); console.log(add_them()); function add_them(a, b) { return a + b; } If you want to fix the parameters of the function then you may use bind as follows:
var add_9_4 = add_them.bind(null, 9, 4); console.log(add_9_4()); function add_them(a, b) { return a + b; } Hope that helps.