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.
Related
If I pass function to a function with same function name and handler name, which one will get precedence ? and how to access each of those two inside function in case in need to do recursion as well as refer to the passed function. See below code.
var f1,f2;
(function f(f){
return typeof f(f2); /*please check below comments for output of this line*/
})(function(f1){ return 1; });
/* this will call the passed function,why not recursion will not happen here? */
The function parameter gets precedence over the function's own name. If you shadow or overwrite a variable, you can't access it (unless it's a shadowed global).
Solution is to use different names.
The recursion doesn't happen simply because the argument of the function get precendence than the function itself. here is an example that shows it:
(function f (f) {
return f.name;
}) (function funcName () { }); // this will return funcName
if we change the name of the argument to f1, f will become the reference of the function itself
(function f (f1) {
return f.name;
}) (function funcName () { }); // this will return f
I see that you use jquery. So I want to ask where do you have declared your functions? inside
<script type="text/javascript">
$(document).ready(function(){
function f(){
return 'this is local function inside anonymous function, so it's invisible for recursion in aside of current document ready'
}
});
//or here?
function f(){
return 'this function is a window object property, and must be visible for recursion';
}
</script>
The code in https://github.com/mattdiamond/Recorderjs/blob/master/recorder.js
I don't understand the javascript syntax like
(function(window){
// blah-blah
})(window)
When I tried the code follow, I could see "hello world" in the console.
(function(window){
console.log("hello world");
})(window)
What does this mean?
Any references?
Thanks in advance
What does this mean? Any references?
It simply executes the bracketed function, just as if it's splitted as:
f = (function(window){
console.log("hello world");
})
f(window)
In any JavaScript file if you write something like:
justFunction();
//function declaration
function justFunction()
{
alert("something");
}
This will call the justFunction() and show an alert. Defining a function like that is known as function declaration.
Now there is another way to define a function
var anotherFunction = function() { alert ("something")}
Now if you write something like
anotherFunction();
// Function Expression
var anotherFunction = function() { alert ("something"); }
Although anotherFunction is a function here this will give an error in console. This is known as function expression.
The reason behind that is function declarations loads before any code is executed. While function expressions loads only when the interpreter reaches that line of code. So if you try to call a function expression before it's loaded, you'll get an error.
But if you call a function declaration, it'll always work. Because no code can be called until all declarations are loaded. So you will have to always call the function expression after it is defined.
// Function Expression
var anotherFunction = function() { alert ("something"); }
anotherFunction();
Now a function expression can be called immediately by adding parenthesis after the anonymous function like
var anotherFunction = function() { alert ("something"); }(); //paranthesis added
This code snippet and the above does the same thing (shows the alert). Now the anotherFunction variable is not the same as above because it is now assigned with the value , that the anonymous function will return. Right now it is not returning anything so anotherFunction is undefined. So if you write something like
var anotherFunction = function() { alert ("something"); }();
anotherFunction(); //error
This will give an error, because the anonymous function does not return any function. If its returns something like
var anotherFunction =
function() { alert ("something"); return "some string"; }(); //returns string
anotherFunction is now a string variable. And if:
var anotherFunction = function() { alert ("something"); return function(){
alert("somethingElse")
}; }(); // returns function
Now anotherFunction is a function and can be called like anotherFunction().
You can pass parameters to this function expression like
var anotherFunction = function(p1,p2) { console.log(p1);
console.log(p2); }(param1,param2 ); //param1,param2 are parameters
One of the main difference between a function expression and a function declaration is that A function expression can be called (invoked) immediately by using a set of parentheses, but a function declaration cannot be.
Now if we don't want to assign the function expression to a variable, then we have to write it inside parenthesis.
(function() { alert ("something");});
And to call it we need to add another set of parenthesis at the end like
(function() { alert ("something"); }());
And same as earlier, we can also pass parameters to it like:
( function(param){ console.log(param); }(param));
This type of functions are ## Heading ##called IIFE (Immediately Invoked Function Expression).
IFFE is just an anonymous function (no name attached to it) that is wrapped inside of a set of parentheses and called (invoked) immediately.
( function(){ }());
REFERNCE
Consider this example.
var message = 'hello world';
function Say(msg){
console.log(msg);
}
new Say(message);
You can make it self invoking anonymous function by wrapping the Say() without a name with parentheses and adding another parentheses after it and pass the message to it.
(function(msg){
console.log(msg);
})(message);
I have tried folllowing two ways of referring a function:
First
let a = function() {
somefunction();
}
Second
let a = somefunction;
Where somefunction is the following in both cases:
function somefunction() {
alert("hello");
}
Is there any difference between these two ways?
Yes, there is a difference between your two examples.
In the first case, you are defining a new anonymous (unnamed) function which calls somefunction. You are then assigning your new function definition to the variable a. a holds a reference to your new function.
In the second case, you are simply assigning your original function of somefunction to the variable a. The variable a then holds a reference to somefunction. You are not creating a new function as you are in the first case.
I think this example may make the difference clear. arguments is an array like object that contains each of the arguments passed to a function.
Try running each of these lines on your favorite browser console.
var somefunction = function() { console.log(arguments); };
Your first example demonstrates defining a named function a that closes around the named function somefunction.
var a = function() { somefunction(); };
Your second example makes a reference, b, directly to somefunction. This makes invoking b the same as invoking somefunction.
var b = somefunction;
Now if you call each of these a and b with some arguments you will see the difference.
=> a('a', 1);
[]
=> b('a', 1);
['a', 1]
In the first case the arguments object is empty. That's because the arguments that were passed to a were not forwarded onto somefunction.
In the second case the arguments are available to somefunction, because some function is being called directly.
Here is how you could redefine a so that it were functionally equivalent using apply
var a = function() { somefunction.apply(this, arguments); }
Running this at your console prints the argument array.
=> a('a', 1);
['a', 1]
var a = function(){
somefunction();
}
Is an Anonymous Function attributed to a variable.
somefunction :function() {
alert("hello");
}
Is an declaration of a function throungh the Object Literal notation.
The diference are shown when you are creating an object. The anonymous function are not acessible as a "public" method, instead in the Object Literal notation, that are acessible from outside.
As Douglas Crockford said, in JS the Good Parts, the first declaration are just a function and the second one could be a method.
In the first case, you are creating a function which calls someFunction(), then you assign that function to a, so now calling a() calls an anonymous function which in turn calls someFunction().
In the second case, a and someFunction become the exact same thing, calling a() is the same as calling someFunction().
The way you're setting var a by accessing the function is clearly out of scope.
So I suspect you have a typo : instead of = :
var somefunction = function() {
alert("hello");
};
somefunction(); // hello
...Now that your first and second makes sense with the code above:
Anonymous Function stored in variable:
var a = function(){
alert('Hey');
somefunction();
};
a(); // Hey // hello
Variable as Function Reference
var a = somefunction;
a(); // hello
In the other case than:
var objLiteral = {
somefunction : function() {
alert("hello");
}
};
var a = objLiteral.somefunction;
a(); // hello
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.
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.