<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.
Related
The code goes like this (The syntax may seem odd but as far as I know, there is nothing wrong with it. Or is there?)
var add=function addNums(a, b) {
return a+b;
}
alert("add: "+ add(2,3)); // produces 5
alert("addNums: "+addNums(2,3)); // should also produce 5
addNums() is declared as a function. So, when I pass the parameters to it, it should also return the result.
Then, why am I not getting the second alert box?
You are seeing a named function expression (NFE).
An anonymous function expression is where you assign a function without a name to a variable1:
var add = function () {
console.log("I have no own name.");
}
A named function expression is where you assign a named function to a variable (surprise!):
var add = function addNums() {
console.log("My name is addNums, but only I will know.");
}
The function's name is only available within the function itself. This enables you to use recursion without necessarily knowing the "outside name" of the function - even without having to set one in the first place (think callback functions).
The name you choose shadows an existing name, so if another addNums is defined elsewhere it will not be overridden. This means you can use any name you like without fear for scoping problems or breaking anything.
In the past you would have used arguments.callee to refer to a function inside itself without knowing its name. But support for that is being removed from JavaScript2, so NFEs are the correct way to do this nowadays.
Here is a lot of stuff to read on the topic: http://kangax.github.io/nfe/
1 Assigning it to a variable is not necessary, it just serves as an example to distinguish it from a plain function declaration. It could be any other context where JS expects an expression (a function argument, for example).
2 You will receive an error if you have strict mode in effect and try to use arguments.callee.
The problem
You are using a named function expression - and a function expression's name is not available outside of that function's scope:
// Function statement
function statement() {
console.log("statement is a type of " + typeof statement);
}
statement();
console.log("statement is a type of " + typeof statement);
results in:
statement is a type of function
statement is a type of function
whereas:
// Function expression with a name
var expression = function namedExpression() {
console.log("namedExpression is a type of " + typeof namedExpression);
};
expression();
// namedExpression(); // uncommenting this will cause an exception
console.log("expression is a type of " + typeof expression);
console.log("namedExpression is a type of " + typeof namedExpression);
will produce:
namedExpression is a type of function
expression is a type of function
namedExpression is a type of undefined
The solution
Depending on what you are trying to do, you want do do one of the following:
Change your function declaration to use a statement and then alias your function:
function addNums(a, b) {
return a + b;
}
var add = addNums;
Alias both names to your expression:
var add = addNums = function addNums(a, b) {
return a + b;
};
Why does JavaScript do things this way?
Named function expressions are useful because they let you reference a function inside itself and they give you a name to look at in a debugger. However, when you use a function as a value you don't generally want parts of it leaking into the enclosing scope. Consider:
(function setup() {
var config = retrieveInPageConfig();
if (config.someSetting) {
performSomeOtherSetup();
}
kickOffApplication();
})();
This is a perfectly licit use of a function expression - in such a case you would not expect the name setup to leak into the enclosing scope. Assigning a named function expression to a variable is just a special case of this, that just happens to look like a function statement declaration.
addNums is only available in the scope of the newly-defined function.
Quite obviously, when a function expression has a name (technically —
Identifier), it is called a named function expression. What you’ve
seen in the very first example — var bar = function foo(){}; — was
exactly that — a named function expression with foo being a function
name. An important detail to remember is that this name is only
available in the scope of a newly-defined function; specs mandate that
an identifier should not be available to an enclosing scope.
Read more detail form this article.
You should either declare as named function:
function addNums(){
}
or assign function to the variable:
var add= function(){// your code }
The reason why addNum() doesn't return anything is because it's not added to the global scope with the way you declare it.
Demo
function addNums(a, b) {
return a+b;
}
var add = addNums;
alert("add: "+ add(2,3));
alert("addNums: "+addNums(2,3));
I have added your code in my test web app and works fine for me. Here is the code. Would you please share the more details of your code/app?
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="JavascriptTest.aspx.cs" Inherits="GetGridViewColumnValue.JavascriptTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var add = function addNums(a, b) {
return a + b;
}
alert("add: " + add(2, 3)); // produces 5
alert("addNums: " + addNums(2, 3));
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Cheers!!!
Consider the following code:
var f = function g() {
// function
};
The g will be access only in the function itself, and its needed when you want to use the function
by itself, for writing recursive functions. For example, you want the factorial function:
var f = function factorial(x) {
if (x <= 1) return 1;
// here we want to use the function itself
return x * factorial(x - 1);
};
console.log(f(5));
However, its really needed as you can access the function itself by arguments.callee:
// note that the function has not any name
var f = function (x) {
if (x <= 1) return 1;
// here we want to use the function itself
return x * arguments.callee(x - 1);
};
console.log(f(5));
I've slightly modified your code:
var add = function addNums(a, b){
return a+b;
}
console.log(add);
console.log(typeof(add));
console.log("add: "+ add(2,3)); // produces 5
console.log("addNums: "+addNums(2,3));
And then proceeded to run it inside of node.js to get this output:
[Function: addNums]
function
add: 5
/home/mel/l.js:44
console.log("addNums: "+addNums(2,3));
^
ReferenceError: addNums is not defined (... backtrace)
Normally, a variable assigned an inline anonymous method would print out [Function] when called with console.log(var); Here console.log(add); results in the name of the function also being printed.
So it's not like your addNums declaration is invalid or not used, it's simply scoped to be bound to the variable add.
addNums is not a function in the global namespace..
It's an function defined only within the assignment operator..
if you want to have access to it try the follow:
function addNums(a, b)
{
return a+b;
}
var add = addNums;
var add = function <---- the function name is add and it's value is a function..
In JavaScript, we can call a function in two ways:
function f(message) { ... }
f.call(this, "test");
or just:
f("test")
Except that we can specify the scope in the first case, is there any other advantage to using this syntax over the other one?
You can pass a this object as you like/need. E.g.
[].slice.call("abcdef", 2) === ['c', 'd', 'e', 'f'];
or
var x = {hasOwnProperty:function() { return false; }, key:42};
x.hasOwnProperty('key'); // == false
{}.hasOwnProperty.call(x, 'key'); // true
You should take notice that call is not a keyword, but a method of Function.prototype.
Read:
Function.prototype.call
Function.prototype.apply
Except that we can specify the scope in the first case
You can't "specify scope". Scope is set by how code is written, you can't dynamically change it other than to a limited extent using with. A function's this keyword has nothing to do with scope, it's always resolved as a local variable in the current execution context.
You can also use call (and apply) for partial function application, which is when you create a function that calls another function with some preset arguments. For example:
// Basic add function
function add(a, b) {
return a + b;
}
// Function to create new adders with a preset 'a' argument
function createAdder(a) {
return function(b) {
return add.call(null, a, b);
}
}
// Let's create a function that always adds five to what's passed in
var addFive = createAdder(5);
// Now let's test it
addFive(6); // 11 - it works!
What is the different between two declarations of a module in JavaScript?
One has parentheses around the function and other one doesn't?
One article says that
Notice the () around the anonymous function. This is required by the
language, since statements that begin with the token function are
always considered to be function declarations. Including () creates a
function expression instead.
Both seem to do the same thing when checked.
var person = (function () {
// Private
var name = "Robert";
return {
getName: function() {
return name;
},
setName: function(newName) {
name = newName;
}
};
}());
var person = function () {
// Private
var name = "Robert";
return {
getName: function() {
return name;
},
setName: function(newName) {
name = newName;
}
};
}();
Functions are of two types in JavaScript - declarations and expressions.
This is the difference between the two:
Function declarations are hoisted. This means you can call the function before it appears in the program as declarations in JavaScript are hoisted.
Function expressions can be invoked immediately. A function declaration cannot. This is because expressions express (or return a value). Function expressions express a function.
An example of a function declaration:
foo("bar");
function foo(bar) {
alert("foo" + bar);
}
The above program will work because foo is a function declaration.
foo("bar"); // throws an error, foo is undefined - not a function
var foo = function (bar) {
alert("foo" + bar);
};
The above program will not work as foo is declared as undefined, hoisted and then later assigned the value of a function expression. Hence it's undefined when it's called.
An example of a function expression:
(function (bar) {
alert("foo" + bar);
}("bar"));
The above function will be immediately invoked as it's a function expression.
function (bar) {
alert("foo" + bar);
}("bar"); // throws an error, can't call undefined
The above function will not be immediately invoked as it's a function declaration. Remember, declarations do not express (or return a value). So it's like trying to invoke undefined as a function.
How does a function become an expression?
If a function is used in the context where an expression is expected then it's treated as an expression. Otherwise it's treated as a declaration.
Expressions are expected when:
You're assigning a value to a variable (i.e. identifier = expression).
Inside parentheses (i.e. ( expression )).
As an operand of an operator (i.e. operator expression).
Hence the following are all function expressions:
var foo = function () {};
(function () {});
~function () {};
Everything else is a function declaration. In short if your function is not preceded by anything, it's a declaration.
See this code: https://github.com/aaditmshah/codemirror-repl/blob/master/scripts/index.js#L94
The following function isExpression is used to test whether some arbitrary JavaScript code is an expression or not:
function isExpression(code) {
if (/^\s*function\s/.test(code)) return false;
try {
Function("return " + code);
return true;
} catch (error) {
return false;
}
}
Hope this clears any doubts in your mind.
In short:
A function expression expresses or returns a value (in this case a function). Hence it can be immediately invoked, but it can't be called before it appears in the program.
A function declaration is hoisted. Hence it can be called before it appears in the program. However since it doesn't express any value it can't be immediately invoked.
In the current context there's no difference for the interpreter. Usually preferable way of writing module is by wrapping the function with parentheses:
var person = (function () {
// Private
var name = "Robert";
return {
getName : function () {
return name;
}
};
}());
That's because the syntax is cleaner and it's obviously that you want to invoke the function immediately after it is declared. One more reason is because:
(function () {
//some stuff
}());
will work but
function () {
//some stuff
}();
this wont.
By wrapping the function each time you use common codding style which is usually a good thing :-).
The difference is that when writing:
var foo = (function () {
...
}());
the use of the (superfluous but useful) grouping () is a common coding style to make it clear from very like first line that the right hand side is most likely an immediately invoked function expression (IIFE). However, in the second:
var foo = function () {
...
}();
it doesn't become apparent until you read the last line, which might be quite a few lines down. Until you reach the last line, you probably thought you were reading a plain assignment:
var foo = function () {
...
};
Note that the parenthesis can be used in a plain assignment too:
var foo = (function () {
...
});
but in that case they really are superfluous (and probably misleading due to the convention of using them for IIFEs).
See An Important Pair of Parens.
Following are two ways to define BW.Timer. Can someone tell me what the difference is? I am not certain the first is even valid, but if it is valid, what is different about using the myfunc=(function(){}()) syntax?
BW.Timer = (function () {
return {
Add: function (o) {
alert(o);
},
Remove: function (o) {
alert(o);
}
};
} ());
And...
BW.Timer = function () {
return {
Add: function (o) {
alert(o);
},
Remove: function (o) {
alert(o);
}
};
};
The first is the return-value of the immediately-invoked function. The second is a function. It essentially comes down to what the difference is between these:
var f = (function() { return 0; })();
var f = function() { return 0; };
Since the first function is called immediately, the value of 0 is given to the variable f. The first f is not a function. However, the second f we must call in order to get the value:
f(); // 0
It follows that in your example, the first BW.Timer is the object literal itself and the second is a function returning an object literal. You must call the function in order to get to the object:
BW.Timer().Add(x);
Why use the first then?
You might ask yourself why one would use a syntax like a = (function() { return {}; })() instead of a = {}, but there's a good reason. An IIFE (Immeditately-Invoked Function Expression), unlike a regular function allows the emulation of static variables (variables that maintain their value through a single instance). For example:
var module = (function() {
var x = 0;
return { get: function() { return x },
set: function(n) { x = n }
};
})();
The above a text-book example of the Module Pattern. Since the function is called right away, the variable x is instantiated and the return value (the object) is given to module. There's no way we can get to x other than by using the get and set methods provided for us. Therefore, x is static, meaning its variable won't be overridden each time you use module.
module.set(5);
module.get(); // 5
On the other hand, let's see an example where module is declared as a function instead:
// assume module was made as a function
module().set(5);
module().get(); // 0
When we call module() the x variable is overridden each time. So we're effectively using different instances of module and x each time we call module.
The difference is rather large.
In the first case, BW.Timer is executed when it is first encountered, and that is the static version assigned to BW.Timer. In that instance, BW.Timer.Add(1) may be used. Each call to BW.Timer will be the same object.
In the second case, BW.Timer is not executed when first encountered, and instead is a function referece which must be invoked BW.Timer(). For Add to be used, this must be the case BW.Timer().Add(1). Also, you can issue var timer = new BM.Timer();. Each instance of BW.Timer() will be unique here.
In the first example BW.Timer references an object that the self-executing function returns, while in the second example it references a function object, in other words it's a function that can be executed BW.Timer().
I use only jQuery for writing JavaScript code. One thing that confuses me is these two approaches of writing functions,
First approach
vote = function (action,feedbackId,responseDiv)
{
alert('hi');
return feedbackId;
}
Second approach
function vote(action, feedbackId,responseDiv)
{
alert('hi');
return feedbackId;
}
What is the difference between the two and why should one use the first approach or the second approach?
The first is a function expression assigned to the vote variable, the second is a function declaration.
The main difference is that function statements are evaluated at parse time, they are available before its declaration at runtime.
See also:
Named function expressions demystified (article)
Explain JavaScript’s encapsulated anonymous function syntax
function myFunction() {}
...is called a "function declaration".
var myFunction = function() {};
...is called a "function expression".
They're very similar; however:
The function declaration can be declared after it is referenced, whereas the function expression must be declared before it is referenced:
// OK
myFunction();
function myFunction() {}
// Error
myFunction();
var myFunction = function() {};
Since a function expression is a statement, it should be followed by a semi-colon.
See Function constructor vs. function declaration vs. function expression at the Mozilla Developer Centre for more information.
The function declaration syntax cannot be used within a block statement.
Legal:
function a() {
function b() {
}
}
Illegal:
function a() {
if (c) {
function b() {
}
}
}
You can do this though:
function a() {
var b;
if (c) {
b = function() {
};
}
}
The first one is a function expression,
var calculateSum = function(a, b) { return a + b; }
alert(calculateSum(5, 5)); // Alerts 10
The second one is a plain function declaration.