Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check for undefined values in IE8?

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?

like image 693
TIMEX Avatar asked Apr 26 '13 08:04

TIMEX


People also ask

How do you verify undefined values?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

How do you check if a value is undefined in HTML?

Try it. function test(t) { if (t === undefined) { return 'Undefined value! '; } return t; } let x; console. log(test(x)); // expected output: "Undefined value!"

How do you know if something is undefined in TypeScript?

We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.

Can JSON contain undefined?

undefined , Function , and Symbol values are not valid JSON values.


1 Answers

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
}
like image 79
Konstantin Dinev Avatar answered Sep 23 '22 05:09

Konstantin Dinev