Argument oddity

| | Comments (0) | TrackBacks (0)

If you have any experience with JavaScript, you ought to know that function arguments are accessible via an implicit array-like object called arguments. This method of argument access allows variable-length argument lists:

    function sum() {
        var sum = 0, len = arguments.length;
        for (var i = 0; i < len; i++)
            sum += arguments[i];
        return sum;
    }

How do named arguments interact with implicit arguments? I won’t answer this question for you, but by way of clarification I pose the following puzzles.

What do each of these expressions evaluate to?

    (function(x, y) { x = y; return arguments[0] })(1, 2)

    (function(x, y) { arguments[0] = y; return x })(1, 2)

Variations on a more complicated theme:

    (function(x) {
        var args = arguments;
        return (function(y) {
            x = y;
            return args[0];
        })(2);
    })(1)

    (function(x) {
        var args = arguments;
        return (function(y) {
            x = y;
            return args;
        })(2)[0];
    })(1)

    (function(x) {
        var args = arguments;
        return (function(y) {
            x = y;
            return args;
        })(2);
    })(1)[0]

    (function(x) {
        var args = arguments;
        return function(y) {
            x = y;
            return args[0];
        };
    })(1)(2)

    (function(x) {
        var args = arguments;
        return function(y) {
            x = y;
            return args;
        };
    })(1)(2)[0]

Some of these expressions do not evaluate to 2. Can you spot the reason?

0 TrackBacks

Listed below are links to blogs that reference this entry: Argument oddity.

TrackBack URL for this entry: http://benjamn.com/mt-tb.cgi/14

Leave a comment

About this Entry

This page contains a single entry by Ben Newman published on May 8, 2008 12:45 PM.

Old Union with man was the previous entry in this blog.

Love, hate is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Categories

Pages

Powered by Movable Type 4.25