Javascript Function Syntax - javascript

In my feeble attempt to learn JavaScript, I bought a book which teaches you how to do things in JavaScript, but forgets to mention WHY.
Coming from PHP I am familiar with the typical function syntax:
function name() {return;}
which from what I understand works the same in JS.
Then I decide I want to attempt to use the YUI 3 framework for a small project to continue learning and come across this...YUI Global Object
YUI().use('node', function(Y) {
Y.Node.get('#demo');
});
As far as I understand this is using the 'use' function of the YUI() object, passing 'node' to the 'use' function....but then what...why is it declaring a function within another function call?
Could someone please explain the syntax being used here?
Also a good reference that explains JavaScript general syntax's similar to php.net would also be beneficial.
Thanks for your help.

Its an anonymous function. Its considered a callback.
In PHP 4 and early versions of PHP 5 you might see something like this:
PHP
function callback($var){
...
}
array_filter( $array, "callback" );
In later versions of PHP 5 you can define them as anonymous functions inline.
So, in JavaScript, the old version would look like this:
JavaScript
function use_callback(Y){
Y.Node.get('#demo');
}
YUI().use('node', use_callback);
But by defining an inline anonymous function, you can save the extra clutter and defined function:
YUI().use('node', function(Y) {
Y.Node.get('#demo');
});
Both those functions are equivalent.

In javascript, functions can be passed around as variables. So, here's some other ways that the YUI code could have been written
//original
YUI().use('node', function(Y) {
Y.Node.get('#demo');
});
//more traditional "global function"
function useNode(Y) {
Y.Node.get('#demo');
}
YUI().use('node', useNode);
//local callback function
var myUseNode = function(Y) {
Y.Node.get('#demo');
}
YUI().use('node', myUseNode);
edit As for the second half of your question, you could write what I know about PHP on a postage stamp, so I can't help you there, sorry :-)

This is constructing an anonymous function, and then passing the function itself in as an argument to use. The use method will then call your anonymous function with a value, which in your function will be called Y, which contains the modules that you asked for in the previous arguments to use.
This is essentially equivalent to the following, which passes myFunction in as a callback to YUI().use, except that the anonymous function doesn't have a name:
function myFunction(Y) {
Y.Node.get('#demo');
}
YUI().use('node', myFunction);
This pattern is used because JavaScript doesn't have any kind of explicit notion of namespaces or modules. They can be emulated, however, by using the scope of a function to act as a sort of namespace. In this case, YUI().use will construct an object that has all of the functionality that you request, and pass that object in to the function you provide, so you can use that Y object to call methods that you have imported.
For a good online reference on JavaScript syntax and methods, I like to use the Mozilla Developer Center documentation. In particular, they have good references on JavaScript and the DOM. As it is part of the Mozilla project, they focus on the methods and syntax supported by Gecko (the rendering engine of Firefox), but they usually include compatibility notes to mention what is portable and what is specific to Gecko.
For your question, I would recommend reading the MDC documentation on functions and function scope. Sadly, the MDC doesn't usually come up on top on a Google search; instead, you get W3Schools, which tends to be lower quality and have more ads. I've found it useful to always prefix my searches for anything about JavaScript or the DOM with "mdc" in order to get the MDC documentation; so, for instance, to find that link, I searched for mdc function, and found what I needed.

In JavaScript, functions are objects. In that case, they are passing in an object as the second parameter value (and defining it inline).
YUI().use('node', function(Y) {
Y.Node.get('#demo');
});
is the same as this:
var xxx = function(Y) {
Y.Node.get('#demo');
};
YUI().use('node', xxx);

It is an anonymous function (akin to lambda function) declaration.
YUI().use('node', function(Y) {
Y.Node.get('#demo');
})
In Javascript, functions are 1st class citizens - they are objects like any other; hence, they can be passed as parameter.

What is being shown is what is known as an anonymous function that is being passed as an argument to a function. I don't think PHP has first-class functions like this, so I have no idea how to explain the syntax in terms of that (I also don't do much with PHP, so..)
Here is my example code:
function something_random(a) {
alert("the type of a is ... " + typeof(a));
if (typeof(a) === 'function') {
a();
}
}
Now with this function in mind, you can plug this into Firebug or something similar and run the following code:
something_random(function () {
alert("This is a test.");
});
Something interesting will happen here - you will get two alerts. One should say "the type of a is... function" and the other should say "this is a test." This is because in JavaScript - as well as some other languages - functions are treated just like objects (well, they technically are objects.)
You can throw around functions all day if you like - they are just like numbers, arrays, and so on.
Something interesting can also happen. You can also pass arguments into anonymous functions, which is something that jQuery does quite a bit (except it uses call, but we won't go there.) This is where you get the special things like where you put function(d) {} in a code.
Hope this helps.

Related

Differences Between Named and Unnamed Anonymous Javascript Functions

Normally, in Javascript, when I want to pass an anonymous/inline function as an argument to another function, I do one of the following.
someFunctionCall(function() {
//...
});
someFunctionCall( () => {
//...
});
However, I've recently inherited a codebase that uses named function as inline arguments, like this
someFunctionCall(function foo() {
//...
});
I've never seen this syntax before. The function still seems to be anonymous -- there's no foo function defined in either the calling or called scope. Is this just a matter of style, or can using a named function (foo above) as an anonymous function change the behavior or state of that program?
This is specifically for a NodeJS (not a browser based program) program, and I'm specifically interested in behavior specific to using functions as parameters. That said information from behavior across platforms and runtimes is welcome.
There are at least three advantages of using named function expressions instead of anonymous function expressions.
Makes debugging easier as the function name shows up in call hierarchy.
The function name is accessible in the inner scope of the function, so it can be used for recursion
The function name itself acts like a self documentation of what the function is doing instead of reading the code.
Using those "named anonymous functions" won't change the behavior but will show the function name in stack traces which is very useful. Also the function gets callable within itself that way.
I'll give an example
Case 1:
var obj = {count: 0, counter: ()=> {this.count+=1;}}
If you do console.log(obj.count) you'll get 0
Case 2:
var obj = {count: 0, counter (){this.count+=1;}}
In 2nd case if you do console.log(obj.count) value will be one.
Hope you understood by now. Lamda expressions cannot access values with reference of this object. It can only access variables with global reference.
In case 1 if you want to make it work with lamba you have to use obj.count+=1 with name has reference.
And rest of the JavaScript function implementation remains same there is not much difference.

Grammar of Self Invoking Anonymous Functions

From what I have read from other topics about the issuse SIAFs or Self Invoking Anonymous Functions are simply there to serve as a container, and it limits the scope of variables (from what I have learnt). Now, the question is, why can I do this:
$("ul>li").click((function(){
}));
But not add another SIAF after it? Like so:
$("ul>li").click((function(){
}));
(function(){
});
It is weird to me, as this, just the SIAF on its own gives me no errors in the IDE:
$("ul>li").click((function(){
}));
(function(){
});
This:
(function() { .. });
is a no-op expression, and in particular it does not involve a function call. A function object is instantiated but it's not used in any way.
This:
(function() { ... })();
does do something, because the trailing () causes the function to be invoked. (It doesn't invoke itself.)
In JavaScript, a reference to a function is just a value, and a function is just an object (well, a special object). When a reference to a function is followed by a parenthesized list of values, then that's a function call. It doesn't matter where the reference to the function comes from. (Where it comes from can affect the semantics of the function call, but not the basic fact of the function call itself.)
edit — the terminology "self-invoking function expression" has gained some currency. I won't wade into a dispute, but in my opinion it's less accurate than the alternative "immediately-invoked function expression" because really a function can't invoke itself externally. It can include a call to itself, but that's a different thing entirely. However I understand the spirit of the term and I think it's harmless.

Code convention for function and callbacks

So I started learning javacript and I've noticed that the coding convention for functions and callbacks is something like this (this is a jQuery example but I've seen these everywhere):
$.getJSON('some/url.json', function(a) {
// do stuff with a here
});
Coming from other languages, I would usually write the above as this:
function myFunction(myVar){
//do stuff with myVar here
};
$.getJSON('some/url.json', myFunction());
Why is the former usually the preferred way of writing in JS, instead of the [probably more readable] latter?
There are plenty of good reasons to use the second, more explicit, format (assuming you fix the issue listed in the comment), including:
reusing the function passed as a callback
giving that function a definitive name to make it easier to debug
making sure that function is noted as something important in your system
separating out that functions because it's simply too long to comfortably declare in place
But the first format, with an anonymous function passed as a callback is short and sweet. If you don't need to reuse the function, if it's relatively short, and if it's not of high importance in your system, it can be really useful to declare it exactly where you use it. You avoid adding another variable to your scope, and you make it entirely clear exactly what that function is for.
It's not the preferred way. You can do anything you want. However, if you need to reuse the function, then you need to do your second option, or alternatively the following, for code reuse:
// in some accessible context/namespace
App.myCallback = function(a){
...
};
// somewhere else
$.getJSON('url', App.myCallback);
Your first example is what is referred to as an anonymous function or block. They are used when they'll only be called once. The second example is when you'd use the function many times... it would be a lot of wasteful typing if you repeated the anonymous block over and over.

What javascript coding style is this?

I am working on maintaining a ASP.NET MVC application that has the following coding style. The view has:
<script type="text/javascript">
$(document).ready(function() {
SAVECUSTOMERS.init();
});
</script>
There is a js file included that goes along these lines:
var SAVECUSTOMERS = (function() {
init = function () {
$("#saveCust").bind("click", OnSave);
$("#cancel").bind("click", OnCancel);
},
OnSave= function() {
//Save Logic;
},
OnCancel = function() {
//Cancel logic;
}
return { init: init };
})();
Is this a best practices JS coding style? Is the intent to have non obtrusive JS?
What is the SAVECUSTOMERS? I understand that there are different ways of creating classes in javascript (per this link), but this style does not fall into any of those categories listed
Where can I find more information on this style of JS coding?
1) Using a $(document).ready (or similar function from another library) function is considered standard practice in JavaScript. First of all, it ensures your JavaScript executes on page that has finished evaluating/building it's DOM. And it also abstracts away some of the browser-implementation inconsistencies when identifying when the DOM is in fact ready. But I assume you are mainly referring to the 2nd code block.
What you see there is that SAVECUSTOMERS is assigned the result of a self-executing an anonymous function. This is done for a few reasons, the most common being the ability to control the scope and 'namespace' of the functions and data inside the anonymous function. This is because JavaScript has lexical scope, and not block level scope.
The practice of using these self-invoking functions in JavaScript is very common
However the code itself has several problems. The variables init, OnSave and OnCancel are declared as global variables (because the var keyword was omitted). This largely defeats the purpose of wrapping them in an self-invoking function. Furthermore, the contents of that function are using a mix of object assignment syntax and standard expression syntax, which will result in syntax errors.
Also, by returning only the init function, the onSave and onCancel functions have been effectively 'hidden' or made 'private' through the use of closures. This helps keep namespaces clean and encapsulated.
If I were writing this code (some personal perferences here, there are a few ways to accomplish something simliar), then it would look like this:
var SaveCustomers = (function($) {
var init = function () {
$("#saveCust").bind("click", onSave);
$("#cancel").bind("click", onCancel);
};
var onSave = function() {
//Save Logic;
};
var onCancel = function() {
//Cancel logic;
}
return { init: init };
})(jQuery);
Some notes on the above:
I declare variables using the var keyword. This keeps their scope local to this function (you could also technically use named functions declarations as well)
I pass jQuery as the parameter in the self-invoking function, and assign it to $ as the argument in the function call. This protects the $ variable inside the function so that we know it references jQuery, and hasn't been munged by a secondary library that also uses $.
2) SAVECUSTOMERS is a basic JavaScript object, which has a single owned property called 'init', whose value is a function, as defined by the init declaration inside the execution.
3) Not sure about how to answer this question - your best bet for understanding JavaScript best practices is to read through other JavaScript code that is known to be of quality, such as the jQuery source, or Prototype, or Underscore, etc.
this style is known as jquery ... have you checked the JQuery website, go through it ...
This is called self-invoking functions in javascript. One of the articles I am giving below. you can get more on google.
http://2007-2010.lovemikeg.com/2008/08/17/a-week-in-javascript-patterns-self-invocation/
If you are referring to the $ programming, then its related to JQuery which other answers have provided links too.
It's using the JQuery library.
JQuery includes a function called $(), which allows you to select elements from the DOM using a CSS-like syntax.
The $(document).ready bit is a standard JQuery method for making sure that the enclosed code only gets run after the page has finished loading. This is required to ensure that events get correctly attached to the relevant DOM objects.
The bit with functions being used as arguments for others functions is known as a 'closure' it's a very common way of writing Javascript, but in particular when using JQuery, which goes out of its way to make things easy to do and minimal code with this coding style.
See this page: http://blog.morrisjohns.com/javascript_closures_for_dummies for a beginners discussion of how closures work in Javascript and how to write them (note that this page doesn't look at JQuery at all; closures are a Javascript feature that is used heavily by JQuery, but you don't need JQuery to write closures)
This is a normal way to use jQuery for handling events.
What basicly happens is that you check that the document is loaded hence
$(document).ready(function() {
SAVECUSTOMERS.init();
});
And when it is you start to add your bindings to buttons or what ever they might be.
The intent of the code in SAVECUSOMTERS is to mimic private and public properties in objects. Since JS does not support these by default, this self invoking function executes and returns a certain number of properties. In this case it returns the 'init' method. Despite the fact that you see OnSave and OnClick, you'll find that you can't access them at all. They are "private" and only used internally within that function.
The $() function is part of a javascript library called jQuery http://jquery.com It's a pretty well rounded library and primarily is used for DOM manipulation.
The $(document).ready() function is a way for jQuery to continuously poll the page until it is loaded. When it is, the javascript within is executed.
The goal is to have public and private functions. OnSave and OnCancel are private functions that are only accessible within the scope of the self-executing anonymous (function() { ... } ()) which returns an object that gives access to the init function publicly.
SAVECUSTOMERS becomes the object returned by the above mentioned function, i.e. { init: init }, an object with one method init that has access to the functions within that closure.
You can read Douglas Crockford's Javascript: The Good Parts or Stoyan Stefanov's Javascript Patterns
Other notes:
The $() functions belong to the jQuery library
There are syntax errors because the functions should be separated by ; not , since they are within a function, not an object.

Are named functions underrated in JavaScript?

Taking the jQuery framework for example, if you run code like this:
$(document).ready(function init() { foo.bar(); });
The stack trace you get in Firebug will look like this:
init()
anonymous()
anonymous([function(), init(), function(), 4 more...], function(), Object name=args)
anonymous()
anonymous()
As you can see, it's not very readable, because you have to click on each function to find out what it is. The anonymous functions would also show up as (?)() in the profiler, and they can lead to the "cannot access optimized closure" bug. It seems to me that these are good reasons to avoid them. Then there's the fact that ECMAScript 5 will deprecate arguments.callee in its strict mode, which means it won't be possible to reference anonymous functions with it, making them a little less future-proof.
On the other hand, using named functions can lead to repetition, e.g.:
var Foo = {
bar: function bar() {}
}
function Foo() {}
Foo.prototype.bar = function bar() {}
Am I correct in thinking that this repetition is justified in light of the debugging convenience named functions provide, and that the prevalence of anonymous functions in good frameworks like jQuery is an oversight?
I agree there are certain downsides to using anonymous methods in JavaScript/EMCAScript. However, don't overlook how they should be used. For simple one liners that you want to pass to another function, they are often excellent.
I found the answer to my question in this very informative article. Firstly, it turns out that I was right about named functions being more desirable, but the solution is not as simple as adding identifiers to all anonymous functions. The main reason for this is JScript implementing function expressions in a very broken way.
Secondly, there is a distinction between function statements and expressions. An anonymous function is just a function expression with the identifier omitted, and adding an identifier (naming it) wouldn't make it a statement (except in JScript, which is why it's broken). This means that all of the other answers were off mark.
But for me anonymous functions are more readable in the source code, because I am sure they are only used there.
Anonymous functions are very convenient. A better fix to this problem, instead of naming the functions, would be if firebug told you on which line in which file the anonymous function was created.
init()
anonymous() // application.js, line 54
anonymous() // foo.js, line 2
And the stack trace is the only place where anonymous functions are a problem imo.

Categories

Resources