-1

I'm passing parameters to a function in a JavaScript library I wrote:

ffff.setup({
    'size':{'width':'100','height':'100'}
});

In the function, I pick them up:

var ffff = {
    setup: function(config) {
        if (config["size"]["width"]) {my_width = config["size"]["width"];}
        if (config["size"]["height"]) {my_height = config["size"]["height"];}
    }
}

My error is, if I do not specify a parameter, I get a Cannot read property 'height' of undefined error: (the error occurs on if (config["size"]["height"]))

ffffr.setup({
    'size':{'width':'100'}
});

How should I detect if a variable has been provided or not?

Patrick Keane
  • 663
  • 3
  • 19
  • 41

6 Answers6

4

There may be more elegant approaches to this (such as jQuery extends() if you use that library), but at a very basic level you could just do

if(typeof config['size'] !== "undefined" && typeof config['size']['height'] !== "undefined")
Lee
  • 10,496
  • 4
  • 37
  • 45
1

If you are looking at the config object, you can use .hasOwnPropertyMDN

if( config.hasOwnProperty("propName") ){
 //use config.propName
}
Travis J
  • 81,153
  • 41
  • 202
  • 273
1
if (config.size && config.size.width) ...
lviggiani
  • 5,824
  • 12
  • 56
  • 89
0

Try:

if (typeof variable === 'undefined') {
    // variable is undefined
}

Or:

if (typeof (conf) === 'object') {
    // object is undefined
}
ajtrichards
  • 29,723
  • 13
  • 94
  • 101
0

You could use

config["size"].hasOwnProperty('width')
ArturSkowronski
  • 1,722
  • 13
  • 17
0

Check if it is defined, and use a ternary operator to set a default

(param===undefined)?default_value:param;

what that will do is check if it is defined, and set it to whatever you want it to if it is undefined, but keep it the same otherwise

scrblnrd3
  • 7,228
  • 9
  • 33
  • 64