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.
Related
How to call a function expression which being nested inside another function ?
let a = function() {
//do something
let b = function() {
console.log('Hello World!')
}
}
a();
There are different ways to define functions in Javascript like Function declaration, Function expression and Arrow functions.
Function declaration can be defined as follow :
function a() {
alert("a");
}
and you can call it by its name a()
and the second is function expression which can be defined in two ways:
//Anonymous Function Expression
let anotherFn = function(){};
//Named function Expression
let anotherFn = function b() {};
you can only call the above function as anotherFn()
In anonymous function expression, the function is assigned to a variable and that function can only be called by the variable name. An anonymous function expression doesn't have any name.
However, you can also provide the name to the function expression. It is useful when you want to refer the current function inside the function body, e.g. in case of recursion. But the name is only accessible within the function body and can't be used to invoke the function outside.
That's why you are getting error b is not defined.
See function expression:
Syntax
var myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
statements
};
[...]
name
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
Note the last sentence.
why should i use variable to call a function and put parentheses after it?
You can define functions either as a function statement or as an expression. See var functionName = function() {} vs function functionName() {} for more information.
I don't understand a part of the accpeted answer of this OP:
Javascript function scoping and hoisting
Writer says:
"
Also, in this instance,
function a() {}
behaved the same as
var a = function () {};
".
What I know is that function expression is different than function declaration, at least for hoisting. Why are they similar in this case?
Why are they similar in this case?
Because var is hoisted (but not set), like a function declaration is hoisted, meaning that there is an a in the local scope before a = 10; is evaluated, so the global a never gets modified - the identifier lookup finds the local a first so sets that
Related parts of the other question
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
Why is a === 1?
That the answer was trying to say was that b is equal to
function b() {
function a() {}
a = 10;
return;
}
Similar to
function b() {
var a = function () {};
a = 10;
return;
}
i.e. there is an identifier a defined in b, so
function b() {
var a = 10;
return;
}
And now, obviously, the global a will not be modified by b
Please note that the position of the var isn't really important, just that it's there, the following will produce the same behaviour
function b() {
a = 10;
return;
var a;
}
The difference is that the first line is defined at run-time, whereas second line is defined at parse-time for a script block.
Look at the full answer on stack, here : var functionName = function() {} vs function functionName() {}
En example can be found in Twitter'a typeahead.js here:
function () {
// ...
return this.each(initialize);
function initialize() {
// ...
}
}
Questions:
What are the scopes and what function sees what?
What is the reason for using such a construct (usage scenarios and advantages)?
Javascript has function based scope, which means that every thing defined inside a function is available from the first line, since the definition is "hoisted" by the complier.
That goes for both variable and function definitions - variable values however, are not available until after assignment.
You can read all about javascript scoping and hoisting here
This means that the function initialize is available from the first line of the wrapping anonymous function.
There is no real reason, and no advantages, for doing it that way, unless you count the code structure as an advantage.
Personally I don't see any reason to do this. For me even it looks a little bit weird. Martin is right. You should be careful, because the defined variables are not accessible like functions. For example this doesn't work:
var getValue = function(func) {
return func();
}
var f = function() {
return getValue(now);
var now = function() {
return 10;
}
}
alert(f());
However, this works:
var getValue = function(func) {
return func();
}
var f = function() {
return getValue(now);
function now() {
return 10;
}
}
alert(f());
<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.
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.