matt3224 matt3224 - 2 months ago 6
Javascript Question

Is there a neater way to write a set of time based conditions in js?

Hey so I have the following code but am curious as to whether there is a shorthand or better/neater way to write such a seemingly cumbersome piece of code.

var time = new Date().getHours();
var greet;

if ( time >= 0 && time < 4 ) {

greet = 'Wow you\'re up late! Good morning.';
}

else if ( time >= 4 && time < 12 ) {

greet = 'Good morning.';
}

else if ( time >= 12 && time < 17 ) {

greet = 'Good afternoon.';
}

else if ( time >= 17 && time <= 23 ) {

greet = 'Good evening.';
}

document.querySelector('.js-greet').innerHTML = greet;


Any insight would be greatly appreciated.

Answer

Another alternative

let time = new Date().getHours();

let hours = [4, 12, 17, 23];
let greetings = ['Wow you\'re up late! Good morning.', 'Good morning.', 'Good afternoon.', 'Good evening.'];

console.log(greetings[hours.findIndex(hour => hour > time)]);
Comments