difference in defining functions : JavaScript [duplicate] - javascript

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
Do we have any difference between the two mentioned function declaration in JavaScript
//Declaration 1
var foo = function(){
// code goes here
}
and
//Declaration 2
function foo(){
// same code here
}
When i tried to use foo's definition as a class to create other objects
var newObj = new foo();
The Declaration 2 worked but Declaration 1 did not allow me to create and object of this type

this is a function expression:
//Declaration 1
var foo = function(){
// code goes here
}
The func expression in this case is anonymous but assigned to a var foo.
for reference
This is a labeled function :
//Declaration 2
function foo(){
// same code here
}
There's not really any great reason to do expression to var. You
should always try to use labeled statements for constructors,so you
can identify an object's 'type' via its constructor.
people mostly use this where hoisting is needed.Hoisting simply means
calling something before it is defined.
Very very simple example:
foo(); // alerts 'hello'
function foo() {alert('hello');}
V/s
foo(); // throws an error since foo is undefined
var foo = function() {alert('hello');}

First creates a local variable that is assigned a function to. The second declaration creates a function. In first case there is no function to be used for the clients. This is why you can not create objects.

Check this fiddle. It is allowing both declaration:
//Declaration 1
var foo1 = function(){
alert('Declaration 1');
}
//Declaration 2
function foo(){
alert('Declaration 2');
}
var b= new foo1();
var a=new foo();

You can create object of function. here in your case declaration 1 consider foo is a variable so you can not create object of any variable that is why Declaration 2 worked and Declaration 1 did not allow you.

The first one creates an anonymous (nameless) function and assigns it to a variable called foo. The second one declares a function with the name foo. Usually those two forms can be used pretty interchangeable but there are still some differences. The following two are the main differences that come to my mind. The first one might be responsible for what you are experiencing:
Hoisting
In the second example, the complete function definition will be hoisted up to the top of the current scope. So when you write:
var a = new A();
function A() {}
JavaScript will interpret this as:
function A(){}
var a;
a = new A();
...and your code will work fine.
In the first example however, only the variable declaration will be hoisted up. The function body stays where it is. So this:
var a = new A();
var A = function(){};
will be interpreted as this:
var a, A;
a = new A();
A = function(){};
which will lead to an error, since A is still undefined by the time you try to create an instance.
The name property
As I said, the first one creates an anonymous function. That means, if you try to access the name property of that function it will return an empty string:
var A = function(){};
console.log(A.name) //{empty string}
In the second example, your function has the actual name A:
function A(){}
console.log(A.name) //A

Related

What's the difference between these two function expressions?

Please correct me if I am wrong. The snippet below is a function statement:
function foo() {}
where as the ones below are all function expressions.
var foo = function() { } // or
var foo = function foo() { } // or
var foo = new function() { }
My question is, what is the difference between these two forms of a function expression?
var foo = function() { } // and
var foo = new function() { }
Is the second one also a constructor expression? And if it is, of which class (I am at a loss of words here, I know JavaScript does not have classes, but by class, here, I mean template or function or prototype)
Update
Those who have provided links to related questions, thank you very much. I really appreciate it. I am trying to learn this language and at this point, honestly, I am so nascent in my judgement that I cannot tell if they're all the same question. I do know that the more I read, although I find it all very fascinating, the more it confuses me at this stage. I will probably take time to fully understand the beauty of this wonderful language. Meanwhile, please do keep mentioning other related threads.
This
var foo = function() { }
instantiates a function and assigns to foo a reference to that function.
This
var foo = new function() { }
instantiates a function, calls it with a new object as its context, and assigns the newly-created object (or the object return value from the function) as the value of foo. The function itself is discarded unless it by some means manages to return itself.
The second piece of code is, or should be, fairly rare in code not written by a confused person.
A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment ). Functions defined via Functions Expressions can be named or anonymous.
The following are examples of function expression that create a function and assign to the variable foo:
var foo = function() { }
var foo = function foo() { }
When you use the new keyword it does not create a function, it just creates an object and assigns it to the variable foo, the instantiated function gets called as well.
var foo = new function() { }

Is function declaration without the "function myFunction() {}" syntax discouraged in javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
There are two ways to declare a function in Javascript:
Syntax 1:
function myFunction() {
// something awesome
};
Syntax 2:
var myFunction = function() {
// somtehing even more awesomer
};
It seems to me that I come across Syntax 1 a lot more in legacy code than in well written code (but that's purely empiric).
Q: Should prever a syntax over the other, and why ?
The only difference that I can think of is here:
This code does not run: http://jsfiddle.net/JdCRq/
myFunction();
var myFunction = function() {
console.log('test');
};
While this code does: http://jsfiddle.net/JdCRq/1/
myFunction();
function myFunction() {
console.log('test');
}
function blocks, in the context of the second example, seem to be declared (at least by name) before the code is actually run.
The first example is the normal way of declaring a function.
The second example is an anonymous function that is assigned to a variable. This is used when you declare a function as a member of an object, or assign it to the prototype of a class, and is sometimes also used when assigned to a regular variable when the normal way of declaring a function would suffice.
The only practical difference between the examples is that the second way is assigned at runtime. If you redefine a function, that happens when the code is parsed, so only the last one exists:
console.log(f()); // shows 2
function f() { return 1; }
console.log(f()); // shows 2
function f() { return 2; }
console.log(f()); // shows 2
(Although you normally wouldn't redefine a function like that, because it makes the code hard to follow.)
With an anonymous function, it doesn't exist until it is assigned, and if reassigned it changes to the new function:
condole.log(f); // shows undefined
var f = function(){ return 1 };
console.log(f()); // shows 1
f = function(){ return 2 };
console.log(f)); // shows 2
Declaring a function with the function declaration statement (the first way) binds the function name to the function object in such a way as to allow debuggers to show you the name in stack traces. There's really no reason to declare functions with var declarations in simple cases like this. (Sometimes, of course, it's necessary, as when you create functions with other functions.)
Syntactically, it's OK for function instantiation expressions (the second way) to also include a function name that's bound to the function. Unfortunately, some JavaScript runtimes don't handle that case properly and behave somewhat badly, so it's not a good idea.
Using both var and function can have some advantages depending on what you want to achieve, here are some examples;
var f1 = function nonUnique () {return true;},
f2 = function nonUnique () {return false;};
meaning f1.name === f2.name but f1 !== f2
function nonUnique () {return true;};
var f1 = nonUnique;
function nonUnique () {return false;}; // this line changes f1 too
var f2 = nonUnique;
means f1 === f2 and f1 will now return false.
function nonUnique () {return true;};
var f1 = nonUnique,
f2 = f1;
f1 = function nonUnique () {return false;}; // this line changes f1 but not f2
means f1 !== f2; f1 returns false but f2 will return true. nonUnique() will also give true.
This last example is useful of re-using native functions names but keeping them safe.
Also note that variables effectively don't exist before the line with var whereas function syntax will, and see this question, which your question is a duplicate of.

Behavior of scope in JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Confused by Javascript's variable scope
For example, this is my JavaScript code:
var foo = 'Originalvalue';
var foo = 'Nextvalue';
alert(foo); // Nextvalue
So then, now I am sure writing var in front of an already-declared variable just simply is nullified and of no use to the program.
But then consider this program:
var foo = 'Originalvalue';
function duhfoo() {
var foo = 'Newbievalue';
}
duhfoo();
alert(foo); // Originalvalue
Then, from the logic explained in my first example, the value should be 'Originalvalue', as there is already a variable called foo. Then why is it like so?
In Javascript there are two kinds of variables: local variables and global variables.
When using var outside of functions you are declaring a global variable and the same happens if you don't use var at all. Writing
foo = "first";
at top level (outside any function) is the same as var foo = "first".
When inside a function however things are different, and the keyword var discriminates between local and global variables:
var foo = "first";
var bar = "second";
function f()
{
var foo = "third"; // local
bar = "fourth"; // global
}
f();
alert([foo, bar]); // output will be first,fourth
In other words when you use var inside a function the variable will be a different one with the same name, visible only by code written inside the boundaries of the function.
Please note that the boundary is determined by the function, and not the braces {...}. If you have nested blocks and use another var declaration inside the blocks the variable will be the same and this is different from what happens in other languages like Java, C or C++.
The only way to create a scope is to define a function (including a function inside a function).
Another very important thing to remember in Javascript (especially if having been exposed to similar-looking languages in which this concept is not present like Java, C or C++) is the idea of "capture"/"closure"...
var foo = "first";
function f()
{
// Local variable
var foo = "second";
function g()
{
// This is the local foo of f, not the global
// one even if there is no "var" declaration
// inside this nested scope
return foo;
}
return g;
}
var nested_function = f();
alert([foo, nested_function()]); // output will be first,second
Basically a local variable can "outlive" the function that defined it, by being used by other functions that are said to "capture" that variable. A function that captures one or more variable is called "closure".
In other words a local variable is only visible inside the body of the function, but it may live longer than then function like it happens for the local foo of last example in which the variable survived after returning from f because it has been captured by closure g.
well variable foo inside duhfoo clearly states that its scope is duhfoo() method and not global.
Because
(From MDN)
var has the following properties
function-scoped
hoist to the top of its function
redeclarations of the same name in the same scope are no-ops
Please read this for more information on this subject.

What does this mean in javascript: var obj = (function(){ .... })() [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the purpose of a self executing function in javascript?
Please, can someone explain to me what does that mean in JS:
var obj = (function(){
// code
})()
Thanks
It is an anonymous function that is immediately executed. It's return value is assigned to obj. For example:
var obj = (function () {
return 10;
}()); //Notice that calling parentheses can go inside or outside the others
console.log(obj); //10
They are often used to introduce a new scope so you don't clutter the scope the code is executing in:
var obj = (function () {
var something = 10; //Not available outside this anonymous function
return something;
}());
console.log(obj); //10
Note that since this is a function expression, and not a function declaration, it should have a semi-colon after the closing curly brace.
It's called an immediately instantiated function. It runs the function, and the returned value is assigned to obj. You can create a scope or class with it, in which you can use closures to keep certain variables private within that scope. See John Resigs page on that subject.
So, if the function looks like this:
var obj = (function(n){
return 2+n;
})(3);
The value of obj would be 5.

Purpose of var a = b.c = function(){} syntax

I've lately browsed js code and the following syntax keeps coming up:
var foo = bar.bi = function() {...}
This is unfamiliar syntax to me. Is it only to define two names for the same function? If so, why not only define it as bar.bi = function()?
Assigns the same value to the variable and the bi property of the bar object at the same time.
This way the object's property gets the value, but you can still reference it as a variable, which is likely a little faster.
Effectively the same as...
bar.bi = function() {...};
var foo = bar.bi;
foo === bar.bi; // true
Or you can visualize it as...
var foo = ( bar.bi = function() {...} );
So the assignment to bar.bi happens first. The result returned from the assignment expression is the same function, and that result is assigned to foo.
In addition to assigning the function to 2 variable, the context also changes depending on how you call it.
bar.bi();
would have it's context as the bar object, as if you would have used this:
foo.call(bar);
But using it off the other variable, like this:
foo();
would use the context of foo. So if foo is in the global context, it'll be equivalent to this:
bar.bi.call(window);
It's just a compound assignment
var r = x = 3;
assigns 3 to x, and also to r, which is newly declared.
Your example just substitutes a function in place of 3, and an object property—bar.bi—in place of x.
It depends on where it is used.
Both fooand bar.bi point to same function here. That means the function can be invoked using
foo();
and
bar.bi();
At the same time it differs in the value of this inside the function. To make the first one equal to second one, it should be invoked as given below
foo.call(bar);
or
foo.apply(bar);
This ensures that this will point to bar inside the function.
please refer:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply.
.
var foo = bar.bi = function() {...};
bar.bi === function() {...} //true
foo === bar.bi //true
bar will be an object who responds to method bi.

Categories