Jump to content

The Group Operator ( ) - Proper Use


iwato
 Share

Recommended Posts

REQUEST:  Please consider the following two blocks of code and answer the questions that follow.  The second block is a sub-block of the first.

THE MAIN BLOCK:

    $(function () {
        function createDemo(name) {
            var container = $('#pagination-' + name);
            var sources = function () {
                var result = [];
                for (var i = 1; i > 196; i++) {
                    result.push(i);
                }
                return result;
            }();
            var options = {
                dataSource: sources,
                callback: function (response, pagination) {
                    window.console && console.log(response, pagination);
                    var dataHtml = '<ul>';
                    $.each(response, function (index, item) {
                        dataHtml += '<li>' + item + '</li>';
                    });
                    dataHtml += '</ul>';
                    container.prev().html(dataHtml);
                }
            };
            //$.pagination(container, options);
            container.addHook('beforeInit', function () {
                window.console && console.log('beforeInit...');
            });
            container.pagination(options);
            container.addHook('beforePageOnClick', function () {
                window.console && console.log('beforePageOnClick...');
                //return false
            });
            return container;
        }
        createDemo('demo1');
    });

THE SUB-BLOCK:

            var sources = function () {
                var result = [];
                for (var i = 1; i > 196; i++) {
                    result.push(i);
                }
                return result;
            }();

QUESTION ONE:  The group operator ( ) at the end of the sub-block appears to execute the anonymous function assigned to the reference variable called sources and to assign the result of that execution to the variable.  Is this correct?  

 I have seen similar use of the operator in the following context:

(function(){...})()

However, in this context, the function is enclosed in parentheses, not assigned to a variable.  This suggests that the empty group ( ) operator is a "word" of its own, and that after specific kinds of expressions, it is akin to the command "execute what comes before".

QUESTION TWO:  Is the above a correct assessment?  If so, what can and cannot appear before the group operator in order for the group operator to behave in the manner just stated.

Roddy

Link to comment
Share on other sites

REQUEST:  Please consider the following block of code and answer the question that follows:

callback: function (response, pagination) {
    window.console && console.log(response, pagination);
    var dataHtml = '<ul>';
    $.each(response, function (index, item) {
        dataHtml += '<li>' + item + '</li>';
    });
    dataHtml += '</ul>';
    container.prev().html(dataHtml);
}

QUESTION ONE:  The word console appears to be a property of the window object.  The word log appears to be a method of the console property.

window.console && console.log(response, pagination);

Why not just write:  window.console.log(response, pagination)?  Would it not have the same effect?

I do not understand the purpose of the author's phrasing.

Link to comment
Share on other sites

I don't know if I'd call that an operator necessarily, you can use parentheses to wrap blocks of code and it's also the syntax used for executing functions like you mentioned.  Yes, for the first question it assigns the return value of the function to sources.  The other line of code you show is typically used to execute a function that doesn't return a value, one reason for that is to have the function run in its own scope so that it doesn't clash with other defined variables.  

Link to comment
Share on other sites

Quote

Why not just write:  window.console.log(response, pagination)?  Would it not have the same effect?

That would give a runtime error if window.console was not defined for whatever reason.  The one-liner they have in the code tests if it's defined and then calls the log method.

That works because of the fact that boolean operators in Javascript can be "short-circuited".

Link to comment
Share on other sites

So, if I have correctly understood, the expression

window.console && console.log(response, pagination);

reads as follows:  If window.console exists and console.log() can be performed, then execute console.log().  Else, do nothing and proceed to the next statement.

Is this correct?

Roddy

Edited by iwato
Link to comment
Share on other sites

You wouldn't really say the "and", it's more like an if statement if window.console exists.  The reason that works is because logical operators get short-circuited.  Since everything in an AND expression needs to be true for the entire thing to be true, if it finds something that is false then it stops evaluating the rest of the expressions and the result is false.  Similarly with OR, if it finds any expression that is true then it stops evaluating the rest and the result is true.  So in that expression above, if window.console is logically false then it does not try to execute console.log.  Note that they just use console.log instead of window.console.log because window is the default global scope.  They don't need window on the left side either but I guess put it there to make it more explicit.

There's something else a little weird about logical expressions in Javascript.  Take this example:

var x = 1;
	var y = 2;
	var z = 3;
	var result = (x && y && z && (x+y+z));

What do you think result is going to be set to?  That expression is a bunch of logical AND operators, so it's going to be set to boolean true, right?  Wrong, it's going to be set to 6, the value of the last expression that was evaluated.  You can use that with OR to have a variable set to the first thing which has a non-falsy value, e.g.:

var ajax_object = which || of || these || exists;

That can be shorter than writing a bunch of if/else statements, but it only works if things like false, zero, or the empty string are not possible values for those variables.

  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...