-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
  • 643
  • 3
  • 18
  • 39

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,216
  • 4
  • 35
  • 45
1

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

if( config.hasOwnProperty("propName") ){
 //use config.propName
}
Travis J
  • 79,093
  • 40
  • 195
  • 263
1
if (config.size && config.size.width) ...
lviggiani
  • 5,442
  • 9
  • 49
  • 85
0

Try:

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

Or:

if (typeof (conf) === 'object') {
    // object is undefined
}
ajtrichards
  • 28,323
  • 13
  • 90
  • 97
0

You could use

config["size"].hasOwnProperty('width')
ArturSkowronski
  • 1,632
  • 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
  • 6,725
  • 9
  • 32
  • 63