Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JavaScript: How to access the arguments of a method

One of my friend got this interview question.

HelloWorld.js
/* Concatenate the Arguments Passed to this method using the separator */
function concat(){
   
}

concat("Hello", "How", "are", "you") // Should return Hello How are you

Interviewer given above snippet and asked to implement concat function, without changing the signature.

First thing to understand is, JavaScript allows you to call a function with more arguments than it is formally declared to accept.

Second JavaScript maintains arguments of a function in an array ‘arguments’, using this we can access the arguments.

HelloWorld.js
/* Concatenate the arguments passed to this method using the separator */
function concat(){
var result = "";

for(arg of arguments){
result = result + arg + " ";
}

return result;

}

var result = concat("Hello", "How", "are", "you") // Should return Hello How are you

console.log(result);

Output
Hello How are you




Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

JavaScript: How to access the arguments of a method

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×