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.
Related
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.
There are different ways of defining the javascript functions. I often use the simplest way to define the function
function myfunc(){
}
and the next way to define the function in the variable like this (a little bit confusing the way of using)
var myvar = myfunc(){
/*some code*/
}
and the difficult way for me and mostly found in codes developed by advanced programmers like the following
var SqueezeBox={presets:{onOpen:function(){},onClose:function(){}}
Please, can anyone clear my concept on this how can I use?
function myfunc(){}
Function declaration: the function is declared using the standard syntax
function functionName(params[]) {
//functionbody
}
Using this syntax declares the function at the begin of the scope execution, so they'll be available everywhere in their scope(and in their descendeant scopes).
var s = myfunc(); //s == 0
function myfunc() {return 0;}
var myfunc = function() {};
This uses the pattern known as function expression, it just assigns a reference of an anonymous function to a variable named myfunc. Using this syntax won't allow you to use the function until the variable is parsed. Even if variables are hoisted at the top of their scope, they're initialized when the interpreter parses them, so the above example won't work:
var s = myfunc(); //ReferenceError: myfunc is not defined
var myfunc = function() {return 0;};
But the example below will:
var myfunc = function() {return 0;};
var s = myfunc(); //s == 0
The third example is just assigning an anonymous function to an object property(also known as object method) in the way we've just done with function expression, so if I use the pattern above the code will become:
var onOpen = function() {},
onClose = function() {},
SqueezeBox = {//curly braces denotes an object literal
presets: {//again, this is a nested object literal
onOpen: onOpen,
onClose: onClose
}
};
This acts exactly the same as your example, with the only difference that here I used a variable to get a reference to the anonymous function before passing it to the object. If you need to know more about objects, I recommend you reading the MDN docs. Anyway, if you're really intrested in how JS works, I'd suggest Javascript Garden, which is a very good article about JS.
The first code snippet is a function declaration:
function myfunc() { }
You are declaring a named function called myfunc. You can verify this by myfunc.name === "myfunc"
Your second code snippet contains syntax error. I believe you meant:
var myvar = function() { };
This is an anonymous function expression assigned to a variable. You can verify this by typeof myvar === "function" and myvar.name === "".
The third snippet is a javascript object. Basically you can think of it as a Map or Dictionary<string, object>. So SqueezeBox contains 1 key presets, which in turn is a dictionary that contains 2 keys, onOpen and onClose, which both of them are anonymous functions.
In
var SqueezeBox={presets:{onOpen:function(){},onClose:function(){}}}
He's creating an object SqueezeBox containing another object presets with two empty anonymous functions, he's defining the function inline with an empty body inside the {}.
A better way to see it is formatted this way:
var SqueezeBox={
presets:{
onOpen:function(){/* empty function body */},
onClose:function(){/*empty function body */}
}
}
There is a lot of useful information on this subject here
Functions can have a name, which if specified cannot be changed. Functions can also be assigned to variables like any other object in javascript.
The first example is of a function declaration:
function myfunc(){
}
Using the function declaration you will be able to call the function from anywhere within the closure in which the function is declared, even if it is declared after it is used.
The other two examples are function expressions:
var myvar = function(){
/*some code*/
}
var SqueezeBox= {
presets: {
onOpen:function(){/* empty function body */},
onClose:function(){/*empty function body */}
}
}
Using function expressions you are assigning functions to a variable. When doing this you must declare them before you use them. Most of the time you see this the functions will be anonymous but it is possible to name a function in an expression:
var myvar = function myFunc(){
myFunc(); // Because it has a name you can now call it recursively
}
When doing this, the myFunc function is only available within the body of the function because it is still a function expression rather than a declaration.
The third example declares a javascript object literal, SqueezeBox and within that object there is another called presets. Within this object there are two more objects/labels called onOpen and onClose. This means you can do the following to use these functions:
SqueezeBox.presets.onOpen();
SqueezeBox.presets.onClose();
You can think of onOpen and onClose as variables that are part of the object. So it's very similar to doing the following (but the variable is only in the scope of the presets object which is only available within the SqueezeBox object).
var onOpen = function() {};
This has already been answered here: What is the difference between a function expression vs declaration in Javascript?.
For the last example, as Atropo said, it's affecting an anonymous function to an object. It's similar to the var example.
This question already has answers here:
How does the (function() {})() construct work and why do people use it?
(15 answers)
Closed 9 years ago.
Can someone explain to me what below code does, how it works and why it is used?
I don't understand why the function is within brackets or the brackets after the curly brackets.
(function () {
//Some javascript code...
}());
Thank you.
Edit/Follow up question:
Now that I better understand what above does, what effect would this have when used with jQuery:
$(document).ready(function () {
(function () {
//code here
}());
});
That is a self-executing function. It creates an anonymous function and immediately executes it.
It can be used for many purposes, such as creating a new scope.
var x = 10
(function () {
var x = 5
}())
alert(x) // 10
This is a self executing anonymous function.
First is the anonymous function:
(function(){
//Normal code goes here
})
The really interesting part is what happens when we add this right at the end:
();
Those brackets cause everything contained in the preceding parentheses to be executed immediately.
Javascript has function level scoping. All variables and functions defined within the anonymous function aren't available to the code outside of it, effectively using closure to seal itself from the outside world.
This design pattern is useful for modular Javascript.
You may read more here:
What is the purpose of a self executing function in javascript?
#doornob is correct. However, there is a syntax error in the original post. It should look like this:
(function() {
// your code goes here
})();
While this is commonly described as a "self-executing function", a more accurate term is "Immediately Invoked Function Expression." We can call that an "iffy." This is a type of closure.
This pattern is is commonly extended into something called the module pattern, which looks like this:
var myModule = (function() {
var my = {};
var privateFoo = 'I am foo. I am a private field!';
my.publicMethodGetFoo = function() {
return privateFoo;
}
return my;
}) ();
This is very much like a class in a traditional OOP language such as C++ or Java. The properties declared using the var keyword cannot be accessed outside of the module. Though there is no such thing as access modifiers in JavaScript, these properties are for all intents and purposes 'private'.
Note that we created an object called 'my'. This object is returned at the end of the module, which means it is exposed to the 'outside world.' Therefore it's accessible outside of the module. Any field or method that we add to 'my' will therefore be public.
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
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.