Tuesday 11 December 2018

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

No comments:

Post a Comment