Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript shorthand

If I can say:

var big = (x > 10) ? true : false;

instead of:

var big;
if (x > 10) {
    big = true;
}
else {
    big = false;
}

how do I make this similarly shorter?

var now = new Date

if (now.getHours() < 5) {
    return "late night pick me up";
}
else if (now.getHours() < 9) {
    return "breakfast";
}
else if (now.getHours() < 13) {
    return "lunch";
}
else if (now.getHours() < 17) {
    return "afternoon snak";
}
else {
    return "dinner";
}

Thanks a big bunch!

like image 307
Ali Habibzadeh Avatar asked Nov 29 '22 10:11

Ali Habibzadeh


2 Answers

var now = new Date().getHours();

return now < 5 ? "late night pick me up" :
       now < 9 ? "breakfast" :
       now < 13 ? "lunch" :
       now < 17 ? "afternoon snak" : "dinner";
like image 111
Idered Avatar answered Dec 19 '22 18:12

Idered


You can't, without a bunch of messy nested ternary operators. The ternary operator is only good for one liners.

like image 45
Rafe Kettler Avatar answered Dec 19 '22 19:12

Rafe Kettler