handle empty object passed as argument in javascript

Good day all.

I have this problem: I must provide a way to pass some optional arguments to a javascript function, this is pretty easy, ok. I decide to make all the arguments be an object, so anyone who need to call the function must provide the name of the arguments. But most of the time, the editors simply call the functions with the whole argument object, without omitting the empty arguments, because arguments are passed to the page via another way (let's say in the querystring, but it doesen't matter).

here it is how I have made the function:

function playAnimation(options) {
var timeOutAnimation = options.animationDuration || 15;
var backgroundColor = options.color ; // this argument will be always present, so no default.
//more code...
}

and this is the call (I use a php code for example purposes)

$(document).ready(function(){
    var opt = {
        animationDuration: '<?php echo $_GET['stopAnimationAfter'] ?>', //could be a number, or nothing.
            color: 'black'
        }
    playAnimation(opt);     
});

the problem is that the argument is passed and it seams that it never falls on the default value. I can't change the way the function is called (i.e. checking the avialability of the "get" parameter and build the function call accordingly, I must find a way to test the arguments inside my javascript.

is there a safe way to do so, like options.animationDuration === "undefined" (doens't work) or something?

SOLUTION: putting ' ' around each argument in the call, makes the argument be full or empty accordingly. and then i can test them.

Upvotes: 0

Views: 3468

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78525

You can use:

function playAnimation(options) {
    options = options || {}
    var timeOutAnimation = options.animationDuration || 15;
    var color = options.color;
}

To set options to an empty object if it doesn't exist. You can also check for undefined like this if you want:

if(typeof options === "undefined") {
    // options not passed
}

Here is a fiddle which demonstrates.

Upvotes: 1

Related Questions