Pavan
Pavan

Reputation: 91

If else conditions in Javascript

I have topdatedata value as 222

I have these 3 conditions specified

if((topDateData<250)&&(topDateData>25)) 
{
alert('one');
}

else if((topDateData>300)&&(topDateData<300)) 
{
alert('Two');
}

else
{
alert('Three');
}

My questions is why is it getting the value as alert(3) and not alert(one)??

Upvotes: -1

Views: 198

Answers (5)

Fabrizio D&#39;Ammassa
Fabrizio D&#39;Ammassa

Reputation: 4769

It looks like your topDateData variable contains a string value "222" instead of an integer.

You could try to cast to an integer this way:

topDateData = parseInt(topDateData);

...

Upvotes: 0

Briguy37
Briguy37

Reputation: 8412

My guess is that you have a string.

var trueBool = '222' < '250'; //true
var falseBool = '222' > '25'; //false

To debug if topDateData is a String or not, do the following:

alert(topDateData + 1);//outputs '2221' if a string, and '223' if a number

Here's a fiddle showing the difference.

UPDATE:

I've tested alert(('222' < 250) && ('222' > 25)); and that outputs true. However, I'm not sure all JavaScript compilers will be smart enough to convert the string to a number first. You should run the same test and see if true is the output on your browser.

Upvotes: 0

JAAulde
JAAulde

Reputation: 19560

When explicitly setting the value to 222, I see 'one' get alerted: http://jsfiddle.net/Wvjfa/

You should debug your actual value ( alert(topDateData); if you like) and see if it really is what you think it is.

Beyond that, Matt Ball is right, your second condition is borked. Also lonesomeday and Kerry are right about your variable case not matching between your question and the posted code.

Upvotes: 2

GrahamJRoy
GrahamJRoy

Reputation: 1643

it's much safer just to set one value - as you're second criteria looks dodgy

var topDateData = 222;

if(topDateData > 300)
{
  alert('two');
}

else if(topDateData > 250)
{
  alert('');
}

else if(topDateData > 25)
{
  alert('One');
}

else
{
  alert('Three');
}

start with the one that's hardest to satisfy (in this example the highest) and then work your way down. It's much easier to follow. Other than that it should work, as per the other comments on here

Upvotes: 0

Kerry Jones
Kerry Jones

Reputation: 21858

Javascript is case sensitive, is topdatedata = 222 or topDateData = 222?

Upvotes: 1

Related Questions