Javascript - Object literals as function argument


Object literals are a preferred way of passing a large number of optional arguments to a function:

function displayInfo(args) {
    var output = "";

    if (typeof == "string"){
        output += "Name: " + + "\n";

    if (typeof args.age == "number") {
        output += "Age: " + args.age + "\n";


    name: "First",
    age: 29

    name: "new Name"

Here, the function displayInfo() accepts a single argument named args.

The argument may come in with a property called name or age or both or neither of those.

The function tests for the existence of each property using the typeof operator and then to construct a message to display based on availability.

Related Topic