SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jul 2010
    Location
    Mumbai, Maharashtra, India
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy Return value of a function for Arrays

    Hello Everyone,

    I'm learning JavaScript nowadays and have a query. Consider a function with following declaration.

    Code:
    function args1()
    {
    	var a = [1,2,3];
    	return a;
    }
    When I try to call above function as below, return type is array

    Code:
    alert (typeof args1(1,2,3)); //array
    alert (args1(1,2,3)); //1,2,3
    But this is not true for local array variable "arguments" which JavaScript creates


    Code:
    function args2()
    {
    	return arguments;
    }
    
    alert (typeof args2(1,2,3)); //object
    alert (args2(1,2,3)); //[object][object]
    In both situations, function is expected to return array values. It is an array in first case but object in second case. Could anyone please explain on this? Why it is so?
    Last edited by sanjayabc1234; Oct 30, 2012 at 13:01. Reason: forget to add something

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by sanjayabc1234 View Post
    In both situations, function is expected to return array values. It is an array in first case but object in second case. Could anyone please explain on this? Why it is so?
    The arguments object is an array-like object, but it is not an actual array. It cannot be just an array because changing a value in the arguments object also changes the corresponsing function parameter as well. You can convert the arguments object to an array though, if you require the information in that data format.
    https://developer.mozilla.org/en-US/...cope/arguments
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Tags for this Thread

Bookmarks

Posting Permissions

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