Results 1 to 5 of 5

Thread: Need code explanation

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2005
    Posts
    50

    Need code explanation

    Can someone please explain this code to me:

    Why does the funtion call below take in two arguments:

    type = Spry.Widget.Utils.firstValid(type, "none");

    While it was defined without any argument:

    Spry.Widget.Utils.firstValid = function() {
    var ret = null;
    for(var i=0; i<Spry.Widget.Utils.firstValid.arguments.length; i++) {
    if (typeof(Spry.Widget.Utils.firstValid.arguments[i]) != 'undefined') {
    ret = Spry.Widget.Utils.firstValid.arguments[i];
    break;
    }
    }
    return ret;
    };

    Any help and thought wellcomed.

    Thanks.

  2. #2
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: Need code explanation

    Just part of how Javascript works; you're not required to specify all (or any) of a function's arguments. If you write a function that's expected to have a consistent number of arguments, then it's good practice to (and simpler to work with if you) specify them. But if your function may accept a variable number of arguments, then you might use something like what you've got there; all functions have an "arguments" object by which you can access the passed arguments by numeric index.

    It's not an approach you should use without good reason though.
    Last edited by SambaNeko; Jan 6th, 2012 at 05:37 PM.

  3. #3

    Thread Starter
    Member
    Join Date
    Sep 2005
    Posts
    50

    Re: Need code explanation

    Thanks SambaNeko, u've just saved me 3 days of wondering. Thank you soo much.

  4. #4
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: Need code explanation

    It's not necessary to qualify arguments:
    Code:
    Spry.Widget.Utils.firstValid = function() {
    	var ret = null;
    	for(var i=0; i<arguments.length; i++) {
    		if (typeof(arguments[i]) != 'undefined') {
    			ret = arguments[i];
    			break;
    		}
    	}
    	return ret;
    };

  5. #5
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: Need code explanation

    another improvement:
    Code:
    Spry.Widget.Utils.firstValid = function() {
    	for (var i in arguments)
    		if (typeof arguments[i] !== 'undefined')
    			return arguments[i];
    };
    Not really sure of the value of this function, to be frank.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width