Concat String In Javascript using 'arguments object'

Defining a function with arguments object keyword, we can concatenates several strings in javascript. For example we want to create full name of user from number of strings like name title, first name, middle name, last name etc. In case any user don`t have middle name or name title then it will be going null or undefined value.
 
Arguments
 
The arguments object is a local variable available within all functions; arguments as a property of Function can no longer be used. "The arguments object is an Array-like object corresponding to the arguments passed to a function." from - MDN
We can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0. The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. 
 
The arguments object is available only within a function body. Attempting to access the arguments object outside a function declaration results in an error. We can use the arguments object if you call a function with more arguments than it is formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments. from - MDN
 
See below example:
  1. function concatString()   
  2. {  
  3.     var s = '';  
  4.     for (var x in arguments)   
  5.     {  
  6.         s += arguments[x] == null ? '' : arguments[x];  
  7.     }  
  8.     return s;  
  9. }  
  10.   
  11. var title = "";  
  12. var fName = "Ram"  
  13. var mName = null;  
  14. var lName = "Raj";  
  15.   
  16. alert(concatString(title, fName, mName, lName) == "" ? null : concatString(title, fName, mName, lName));  
Ebook Download
View all
Learn
View all