6

I have this in my javascript:

console.log(filters);
console.log('----');
console.log(filters.max_price);

In Chrome, it shows this. This is the expected behavior.

Object {max_price: undefined, sort_by: undefined, distance: undefined, start: undefined, num: undefined}
----
undefined 

In IE8, the log shows this:

LOG: Object Object
----
LOG: String

Why does IE8 think it is a string? I need to know if it's undefined.

I have lots of code that sets default values.

if(typeof filters.max_price == undefined){ //I use this technique a lot! 
    filter.max_price = 2000; 
}

How can I check for undefine-ds in IE8? Should I do this? This seems to work (yay...), but it seems cheap and hacky.

if(!filters.max_price || typeof filters.max_price == 'undefined'){

Is there a simple way I can do this with underscore?

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • Do you mean `undefined` as in "declared but not defined", or `undefined` as in "not declared nor defined"; two different things... – elclanrs Apr 26 '13 at 08:07
  • http://stackoverflow.com/questions/690251/what-happened-to-console-log-in-ie8 – Jørgen R Apr 26 '13 at 08:07
  • @jurgemaister yea I know... but that has nothing to do with the question – TIMEX Apr 26 '13 at 08:09
  • IE8's `console` isn't really that good. It's better in later IE versions, but if you need to work in IE8, you could try using [Firebug Lite](https://getfirebug.com/firebuglite) instead. It'll give you more functionality for inspecting you JS data, etc. – Spudley Apr 26 '13 at 08:43

2 Answers2

5

You can use this approach, but it would not reduce your code a lot:

filters.max_price = filters.max_price || 2000;

This, however, would overwrite the value if it's 0. The best approach remains:

if(typeof filters.max_price === 'undefined'){
    // init default
}
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
0

You can use a guard operator to set a default value:

filters.max_price = filters.max_price || 2000;

To check if the value is a number (which I supposed a price is), you can use

if(isNaN(filters.max_price)) {
    //enter code here
}

This will also filter out undefined as not a number.

Andrei Nemes
  • 3,062
  • 1
  • 16
  • 22