AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15876

Javascript switch case?

I have following code:

function SetStartDateIfNull(date, range_id) {
if (date || isEmpty(date)) {
    switch (range_id) {
        case 0:
            date = date.getDate() - 1;
            break;
        case 1:
            date = date.getDate() - 30;
            break;
        case 2:
            date = date.getMonth() - 6;
            break;
        case 3:
            date = date.getYear() - 1;
            break;
        case 4:
            date = date.getYear() - 15;
            break;
    } //end switch
} //end if
return date;
} //end SetStartDateIfNull

my intention if date is null, I set date. I debugged the code. "if" statement is working. If date is null it entire the if block. But it skips the switch block. In debugging, range_id = 0; and date = ""; Why it skips the all switch block?

UPDATE

this code is working.

function SetEndDateIfNull(date) {
    if (date || isEmpty(date)) {
        date = new Date();
    }
    return date;
} //end SetDateIfNull

Thanks.

Upvotes: 0

Views: 1928

Answers (4)

Sibu
Sibu

Reputation: 4617

In your function, you are checking if the date is null, but in your cases you are trying to get date from undefined variable.

function SetStartDateIfNull(date, range_id) {
    if (!date || isEmpty(date)) {
        var date = new Date();//date is undefined
        switch (range_id) {
            case 0:
                date = date.getDate() - 1;
                break;
            case 1:
                date = date.getDate() - 30;
                break;
            case 2:
                date = date.getMonth() - 6;
                break;
            case 3:
                date = date.getYear() - 1;
                break;
            case 4:
                date = date.getYear() - 15;
                break;
        } //end switch 
      } //end if
    return date;
    } //end SetStartDateIfNull

Working Demo

Upvotes: 2

newman
newman

Reputation: 2719

Very strange code. Methods getDate, getMonth and getYear return integer value; But for run with this method date must be object. I think your code going into switch and then generate error or exception, because date is NULL and can't call any methods.

Upvotes: 3

codingbiz
codingbiz

Reputation: 26396

Check out this line

if (!date || isEmpty(date)) 

Upvotes: 1

ScoPi
ScoPi

Reputation: 1195

Your condition will evaluate to false if date is null. if (date) returns false if date is null. Not sure what you're missing. You want to do:

if (!date || isEmpty(date)) {

Upvotes: 0

Related Questions