Creating a function in JS [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}
I am curious to which is best pratice when creating a function in js
function x() {
...
}
OR
var x = function() {
...
}
Is there a difference or are they the exact same thing.

x(); // I work
function x() {
...
}
y(); // I fail
var y = function() {
...
}
The first is a function declaration. You can use functions before you've declared them.
The second is a assigning a function to a variable. This means you can assign to anything.
You can assing it to foo[0] or foo.bar.baz or foo.get("baz")[0]

I prefer the first form because it gets defined before variables are defined.
So, you could invoke x in a later scope because the interpreter already defined that function even though it may be declared later on in your code.
This will be simpler with some code:
x(); //logs "hi"
//...
function x() {
console.log("hi");
}
vs
x(); //fails
var x = function() {
console.log("hi");
};

They are not exactly the same thing, people have mentioned the forward-lookahead difference, here's a less known subtlety - the function name property:
function x(){}
x.name; // "x"
var x = function(){};
x.name; // ""

In the second case, you can pass functions as parameters and store them in arrays

You might find this useful:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope

The first is a function declaration, the latter is a function expression. Read more here while I try to find a very in-depth article I once read on the differences and implications.
Edit: Ah, here we go. Grab a cup of tea and settle in for an in-depth discussion.

Related

Is Function Declaration is only right way to define function inside closure? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
What is the difference between the following lines of code?
//Function declaration
function foo() { return 5; }
//Anonymous function expression
var foo = function() { return 5; }
//Named function expression
var foo = function foo() { return 5; }
Questions:
What is a named/anonymous function expression?
What is a declared function?
How do browsers deal with these constructs differently?
What do the responses to a similar question (var functionName = function() {} vs function functionName() {}) not get exactly right?
They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.
Function declarations load before any code is executed.
Function expressions load 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! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.
Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
As for the second part of your question:
var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.
Function Declaration
function foo() { ... }
Because of function hoisting, the function declared this way can be called both after and before the definition.
Function Expression
Named Function Expression
var foo = function bar() { ... }
Anonymous Function Expression
var foo = function() { ... }
foo() can be called only after creation.
Immediately-Invoked Function Expression (IIFE)
(function() { ... }());
Conclusion
Douglas Crockford recommends to use function expression in his «JavaScript: The Good Parts» book because it makes it clear that foo is a variable containing a function value.
Well, personally, I prefer to use Declaration unless there is a reason for Expression.
Regarding 3rd definition:
var foo = function foo() { return 5; }
Heres an example which shows how to use possibility of recursive call:
a = function b(i) {
if (i>10) {
return i;
}
else {
return b(++i);
}
}
console.log(a(5)); // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15
Edit:
more interesting example with closures:
a = function(c) {
return function b(i){
if (i>c) {
return i;
}
return b(++i);
}
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8
The first statement depends on the context in which it is declared.
If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.
If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"
EDIT:
I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.
END EDIT
Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore
var foo = function foo() { return 5; }
Is the same as
var foo = function fooYou() { return 5; }
Though the complete difference is more complicated, the only difference that concerns me is when the machine creates the function object. Which in the case of declarations is before any statement is executed but after a statement body is invoked (be that the global code body or a sub-function's), and in the case of expressions is when the statement it is in gets executed. Other than that for all intents and purposes browsers treat them the same.
To help you understand, take a look at this performance test which busted an assumption I had made of internally declared functions not needing to be re-created by the machine when the outer function is invoked. Kind of a shame too as I liked writing code that way.

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.

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.

Javascript Function Definition Syntax [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
Declaring functions in JavaScript
I've seen 2 different syntaxes for defining functions in javascript:
function f() {
...
}
As well as
var f = function() {
...
};
What's the difference between these? Is one of them deprecated?
Neither are deprecated, and both will work. The difference here is that one is a named function ( function f() ) while the other is a variable equal to a function ( var f = function() ).
You have to be careful when setting variables equal to functions. This will work:
var f = function(n) { console.log(n); };
f(3); // logs 3
But this will break, since the variable is defined after the call to it.
f(3); // what is f? breaks.
var f = function(n) { console.log(n); };
But normal functions work fine.
function abc(n) { console.log(n); }
abc(3); // logs 3
xyz(5); // logs 5
function xyz(n) { console.log(n); }
This is because the code is analysed before execution, and all functions are available to call. But setting a var equal to a function is like setting a var to anything else. The order of when it happens is important.
Now for some more confusing stuff...
There are also 'self-executing' anonymous functions. They go by a variety of names. The most common way to do it looks something like this:
(function() {
// code in here will execute right away
// since the () at the end executes this (function(){})
})();
There is also an arguably better version.
!function() {
// again, the tailing () will execute this
}();
Check out this Stack Overflow post for more on anonymous functions.

JavaScript function different syntax? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between a function expression vs declaration in JavaScript?
This JavaScript syntax I haven't seen till now, what does it do really?
What is the difference between the following two ways of writing a function? I've seen both used, but I'm not sure which one is 'correct'.
function init() {
}
init: function() {
},
And what are the advantages to writing it the second way?
Function declaration
function init() {
}
Function expression
var init = function() {
};
The primary differences have to do with Variable Hoisting in JavaScript. You can read more here: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting and http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
By your example, I believe you are also interested in defining anonymous functions in object literals. Here is an example:
//obj is the object name
var obj = {
//init is the property name or key and the anonymous function is the value
init: function() {
},
anotherProp: 'some value'
};
This would be used like so:
obj.init();
alert(obj.anotherPorp);
In object literals different properties of the object are defined with a key: value syntax and use commas to separate them.
I would recommend going through this free series on JavaScript http://learn.appendto.com/lessons, it will answer a lot of these questions for you and give you a solid base to becoming a JS developer.
The second one can only be used in the context of an object literal:
var myNamespace = {
func1: function () {
// do something
},
func2: function () {
// do something else
},
someValue = 5
};
The first form is executed as a statement. It is equivalent to:
var init = function () {
// do something
};
The first example defines a function in the global scope which can be called with init(). The second defines a property of an object called init that is the function declaration to the right.
Generally, the second example provides a smaller scope in which you could execute the function.
First example allows you to call the function like so:
init();
And the second, more likely this:
var thing = function() {
init: function() { }
};
thing.init();
Try to always use:
init: function (){
}
when writing an object literal.
When you're trying to process a global function set it as a var instead, so:
var init = function(){
}
Remember, each has its place, but I've personally become fond of writing a namespace for the project I'm working on and using an object literal.
Now both of these will only be available in the object as soon as the object is set. The other method is a little sloppier and less used now, but can be called no matter the order of operations, so it can be called before or after it's set in the code... Again, this is being abandoned in a lot of cases.
function init(){
}

Categories