[JavaScript] Pass an object as function argument

[JavaScript] Pass an object as function argument

You are probably used to passing arguments to a function in this way:

function man (name, age, city){
console.log ('name:  '+name+'  age:  '+age+' city: '+city);
}
man ('Frank', 40, 'Amsterdam')

But what happens then if you pass those arguments in the wrong order? like

man (40,'Frank', 40, )

then all your apps will have wrong values. It’s really handy than to pass an object as an argument.

Passing an object as a functions argument.

function man(args) {

    document.getElementById('output').innerHTML += " <br><br>*** New Man ***";
    document.getElementById('output').innerHTML +=" <br> ------------------- <br> ";

    args =  args || new Object(); // otherwise if no argument get passed, it's undefined and breaks the script
    args.name = args.name || "Anonymous";
    args.age = args.age || "Immortal";
    args.city = args.city || "Nowhere";

    for (var k in args) {

        document.getElementById('output').innerHTML += k + ': ' + args[k] ;
        document.getElementById('output').innerHTML +=" <br> ------------------- <br> ";

    }
}

args = args || new Object(); // otherwise if no argument get passed, it’s undefined and breaks the script
args.name = args.name || “Anonymous”;
args.age = args.age || “Immortal”;
args.city = args.city || “Nowhere”;

Those are fallback values. If the values we need are not passed to the function, we overwrite them with default values. Note that if no argument gets passed then ‘args’ would be undefined, breaking the whole script, instead we back it up by creating a new object and filling it with default values.

the way to pass an object to that function is

man({
    name: "Frank",
    age: 40

});

Note that I left the properties ‘city’ not defined to illustrate the fallback default value
Another method that I do prefer if I do have to save the object that I send to that function is to create the object first, and then pass it:

var Frank = new Object();
Frank.name = "Frank";
Frank.age = 40;
Frank.city = "Amsterdam ";
man(Frank);

Here's the jsfiddle to test it. If you have any comments/questions, please drop me a line in the comment.

Here is the example link

Read More: Ultimate Small Business Custom Design and Development Guide