JavaScript Function with 2 names? [duplicate] - javascript

This question already has an answer here:
Named anonymous functions vs anonymous functions
(1 answer)
Closed 2 years ago.
I know this might be a simple question, but I'm learning JavaScript and found these two ways to define functions:
Method 1
var myFunction = function() {
statements
}
Method 2
var myFunction = function namedFunction(){
statements
}
My question is: what is the difference between the name of the variable and the name of the function?
Could I call the second function with myFunction(); and namedFunction(); ?
Thanks for your help!

One difference is that the namedFunction becomes an identifier inside the second function, to refer to the function without having to use the outer myFunction variable name:
var myFunction = function namedFunction(){
console.log('running');
setTimeout(namedFunction, 1000);
};
myFunction();
It's not particularly useful here, since you could just refer to the outer variable, but it becomes more useful when there isn't an outer variable you can cleanly reference, eg:
const obj = {
nested: {
fn: function namedFunction(){
console.log('running');
setTimeout(namedFunction, 1000);
// the above looks cleaner than
// setTimeout(obj.nested.fn, 1000);
}
}
};
obj.nested.fn();
Could I call the second function with myFunction(); and namedFunction(); ?
Yes, both will refer to the function, though the namedFunction identifier will be scoped only inside the function, whereas the myFunction identifier will be scoped anywhere in the outer script.

Related

Difference between funct1: function versus funct1 function () [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
I often see code like the following in JavaScript:
func1: function() {
return array1.pop();
}
What is the difference between the above and something like this:
function func1 (){
return array1.pop();
}
Are the above two the same thing with different way of writing? The first one looks like a switch statement to me. Sorry if this question is too simple but JavaScript books seldom uses the first syntax if this is just the matter of syntax issue; the main reason for me to ask this question in StackOverflow.
The first one is creating a property on an object literal. The property name is func1 and the property value is an anonymous function. For example:
var someObject = {
someProp: function () {
alert('foo');
}
};
someObject.someProp(); // alerts "foo"
For the second one you probably meant function func1 ..., which is a plain old function declaration. For example:
function someFunction() {
alert('foo');
}
someFunction(); // alerts "foo"
Most people use object literals as a way of grouping logical functionality together, similar to namespaces in other languages. By defining functions as properties of other variables, you keep the number of variables in the global namespace down and the code more organized.
The second form is that of a “normal” function declaration: the function is available within the scope in which you’ve declared it. The first form is used inside an object literal:
var myObject = {
func: function() {
return array1.pop();
},
name: 'John Smith'
};
The function can be called as myObject.func() whenever myObject is accessible. Aside from this difference in scoping, the two definitions of the function are equivalent.
There is also a very important difference referred to as "function hoisting" (vague in terms of ECMA, but is a common term to describe the behavior).. This is directly related to the "second way" in original question namely -
function func1 (){
return array1.pop();
}
There are two ways we may use functions (again wrt to second way):
As a function expression -
var a = function() {
}
As a function declaration
function a() {
}
As you know, all variables, no matter where in the function body they are declared, get
hoisted to the top of the function behind the scenes. The same applies for functions
because they are just objects assigned to variables. The only “gotcha” is that when using
a function declaration, the definition of the function also gets hoisted, not only its
declaration.

Explain the following JavaScript statement? [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Why do you need to invoke an anonymous function on the same line?
(19 answers)
Closed 9 years ago.
var ninja = (function(){
function Ninja(){};
return new Ninja();
})();
Why is the function above encapsulated in parentheses and why is there a (); at the end?
I think it's a constructor function because of the (); at the end, but why is the object wrapped in parentheses?
This code is equivalent to:
function Ninja() {
// nothing here
}
var ninja = new Ninja();
Though in the code you listed, the function/object Ninja is not global scope.
The code (function() {...})(); basically says "take whatever function is contained inside here and execute it immediately". So it's creating an anonymous function and calling it right afterwards.
It's called an Immediately-Invoked Function Expression (or IIFE). It creates a new scope and executes the contents immediately. There are many uses for it; the one I use the most is when the this keyword would change meaning, e.g. in
var someClass = function() {
this.property = something;
this.update = (function(obj) {
function() {
$('.el').each(function() {
$(this).html( obj.property );
});
};
)(this);
};
While I want to refer to this.property inside the $('.el').each(), this changes meaning within that scope and refers to the current DOM element that is being looped through with .each(). So by passing this as a parameter into the IIFE (and calling that parameter obj) I can use obj.property to refer to what is this.property when outside the scope of $('.el').each( ..., function() { ... });.
Let me know if that makes sense or if you have any questions :)
Why is the function declaration encapsulated in '('s and also why is
there a '();' in the end
Its declaring and executing the function at the same time.
You may see: Named function expressions demystified - by Juriy "kangax" Zaytsev
As suggested: Refering to Benalman
Immediately-Invoked Function Expression (IIFE)
Fortunately, the SyntaxError “fix” is simple. The most widely accepted way to tell the parser to expect a function expression is just to wrap in in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
// Either of the following two patterns can be used to immediately invoke
// a function expression, utilizing the function's execution context to
// create "privacy."
(function(){ /* code */ }()); // Crockford recommends this one
(function(){ /* code */ })(); // But this one works just as well

What do these double parentheses do in JS? [duplicate]

This question already has answers here:
What do parentheses surrounding an object/function/class declaration mean? [duplicate]
(7 answers)
Closed 9 years ago.
I'm reading the book secrets of the js ninja, and very often I saw code like this
(function(){
something here;
})();
Why do we need to enclose the function within parentheses and why do we add one more pair of parentheses after that?
Its a self calling function, that invokes its self as the script finishes loading. You can call it without arguments, or you can add arguments to it such as window or document.
You use it in a way that jQuery use it:
(function( window, undefined ) {
// jQuery code
})(window);
An (almost) alternative syntax to do the same thing:
! function( window, undefined ){
// some code…
}(window);
Read more at: http://sarfraznawaz.wordpress.com/2012/01/26/javascript-self-invoking-functions/
This
(function(){
alert('hello');
})();
although it is a function is it called automatically so you dont/can't call it manually
These can be useful for for loops like so
This will fail because i would be equal to 9 after 5 seconds
for(var i = 0; i < 10; i++) {
window.setTimeout(function(){
console.log(i);
}, 5000)
}
So you could do this
for(var i = 0; i < 10; i++) {
(function(a){
window.setTimeout(function(){
console.log(a);
}, 5000)
})(i);
}
Also good for creating a "private" scope like this
(function(){
var test = 'hello';
console.log( test ); // 'hello'
}());
console.log( test ); // 'undefined'
The last set of parentheses causes the function to execute immediately. A function is created and executed without ever assigning it anywhere. The reason one might wrap their code in a function like this is to encapsulate code. Take this for example:
var myVar = 'whatever';
function shout() { alert(myVar); }
Here, myVar and shout have just become global variables. You can open up your console and type window.myVar or window.shout and you'll be able to access and change those variables. By wrapping it in a function, those variables remain local to the outer function:
(function() {
var myVar = 'whatever';
function shout() { alert(myVar); }
})();
window.myVar and window.shout are undefined. The only exist inside that function.
The pattern is also used to create a closure around local variables. See JavaScript closure inside loops – simple practical example.
Self invoking function, basically it calls itself stright away.
Used normally to pass in a variable like jQuery to insure that $ is truly the jQuery object!
(function($){
// $ now is equal to jQuery
})(jQuery);
It runs the function you just created. The reason to do this is that it encloses all of the code you write within a new scope. This means when you define vars and functions, they will be kept within the scope of that function() you just created.
In short, it encapsulates code.

Javascript function definition [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Do var fn = function() {…} and var fn = function foo() {…} ever differ?
From here
What is the difference between a function expression vs declaration in JavaScript?
I understand that there is a difference between declaring functions and declaring them as variables.
But It's not clear if there is any difference between:
var func_name = function(param, param1){...};
and:
var func_name = function func_name(param, param1){...};
Are they exactly identical?
There are 2 ways of declaring a function in JavaScript.
Function Declaration
Functions declarations are statements so they begin with the function keyword and you have to give the function a name.
These are also parsed before code execution starts, so the code below would not throw an error:
foo(); // "foo" exists because it was created at parse time
function foo() {
}
Function Expressions
Function expressions are - as the name states - expressions. Functions in
expressions are treated like any other value (e.g. numbers, strings etc.) and
naming them is purely optional.
Functions from expressions are created at runtime, so the code below will
throw an expection:
foo(); // "foo" does not exist yes because it will not be created until the line below is executed
var foo = function() {
}
Function names
Functions names are mainly good two things.
Calling function declarations
Accessing the function object from within the function
As stated, in case of expressions the name can be left out; thus, creating a so called anonymous function
So in your example you got two function expressions, one of which is a anonymous function and the other is not.
See also: http://bonsaiden.github.com/JavaScript-Garden/#function.general
the answer is "no".
You can always call the function by its name inside the function.
var func_name = function other_0func_name(param, param1){
..... ;
other_func_name()};
I'm pretty sure that's only used to make debugging easier.
It appears that named functions make for a much more pleasant debugging experience. When debugging an application, having a call stack with descriptive items makes a huge difference.
var func_name = function(param, param1){...};
will create an anonymous function and assign to the variable "func_name"
var func_name = function func_name(param, param1){...};
will create a function named "func_name" and then assign that function to the variable "func_name"
If you test these two lines in the console, you will see
var func_name = function(param, param1){};
console.log(func_name)
will give
function (param, param1){}
whereas
var func_name = function func_name(param, param1){};
console.log(func_name)
will give
function func_name(param, param1){}
There will be no difference in terms of usage so for your purposes they are the same.
Hope this clears it up.

"function foo(bar) { }" versus "foo = function(bar) { }" [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 years ago.
function foo(bar) {
// ...
}
and
foo = function(bar) {
// ...
};
What is the benefit of one versus the other? The main benefit I see in the latter is not running into errors with a function name already being defined. However, there may be other benefits or drawbacks that aren't obvious. What are they (if any)?
This has been asked a few times, this seems to be the best one.
There are other things that you can do with an anonymous function other than assigning it to a variable. You can for example execute it right away:
(function() { ... })();
This is sometimes used to create a scope for the code. Anything declared in the scope is local to it, and you can return a result to the code outside:
var a = (function() {
var answer = 42;
function display() { window.alert(answer); };
return display;
})();
Now the variable a contains a function that displays the value of the variable answer, but the variable answer is local to the scope:
a(); // displays the value
display(); // not available
window.alert(answer); // not available
This pattern is for example used to create plugins for jQuery:
(function($) {
$.fn.blackText = function() {
return this.css('color', '#000');
};
}(jQuery);
The jQuery object is sent into the scope as the $ parameter, that way the code in the scope can use the $ shortcut even if it has been turned off (using noConflict) outside the scope.

Categories

Resources