user3126119
user3126119

Reputation: 323

JavaScript arguments array

I am new to JavaScript and came across this snippet:

function addSuffix()
{
    var sString= " ";
    for (var k=1, k<arguments.length; k++)
    {
         sString +=arguments[k] + arguments[0] + " " ;
    } 
    return sString;
 }

 console.info(addSuffix('s','bow','dog','kite'));

Can somebody explain. (I have read about java script and know abouts loops etc but this example confused me mainly because of the arguments array)

Upvotes: 0

Views: 204

Answers (3)

b.runyon
b.runyon

Reputation: 154

Variable Values After First Iteration of for loop:

sString = "bows "

Variable Values After Second Iteration of for loop:

sString = "bows dogs "

Variable Values After third Iteration of for loop:

sString = "bows dogs kites "


Return: "bows dogs kites "

The return value from console.info is "bows dogs kites ".

The length of the arguments are 4. The for loop runs a total of 3 times. Each time it will add the element that is in the first position in the arguments array and add it to the end of the string of the k-th element in the argument array. It keeps adding on to the sString.

Does this make sense?

Upvotes: -1

Squirrel
Squirrel

Reputation: 392

The arguments array is a way to pass "unlimited" values to a function, without having to specify every single one of them.

Think of it as a way to make a function recieve a non-specified number of values. In your example, it would be the same as saying:

function addSuffix(argument1, argument2, argument3)
{
    var sString = argument2+argument1+" "+argument3+argument1+" ";
    return sString;
 }

Because it starts from 1 (the second argument passed), then adds the first one again (arguments[0]) then a white space (" "). Then it repeats the process.

See more about this array at the Mozilla Developer Network.

Upvotes: 2

Rida BENHAMMANE
Rida BENHAMMANE

Reputation: 4129

When a function is executed an arguments object is created. The arguments object has an array-like structure with an indexed property for each passed argument and a length property equal to the total number of parameters supplied by the caller.

Upvotes: 0

Related Questions