The correct way to do this would be to move your third condition up to the second spot.
When doing this kind of checks always place the most restricting condition first.
In your case, the tidiest way is:
var w = $(window).width();
if (w < 780) { // most restrictive condition. Excludes all the others...
console.log('mobile');
} else if (w < 1280) { // this one includes the one above but it will never be triggered if w < 780
console.log('tablet');
} else { // all the other cases
console.log('desktop');
}
Contrary to what many said, there is no need for this else if statement:
else if (windowWidth < 1280 && windowWidth >= 780) { ... }
This adds an unnecessary, redundant check.
It sure is a light operation, but imagine that, instead of windowWidth < 1280 you were checking
functionForCalculatingWidth() : int {
// huge amount of lines with expensive computation
return result;
}
you would be calling the same function twice. See why it is bad design?
In the same way, if you were to check conditions based on the largest element (plus let's add another fictional condition), you would do:
var w = $(window).width();
if (w > 1280) {
console.log('desktop');
} else if (w > 990) {
console.log('weird device');
} else if (w > 780) {
console.log('tablet');
} else {
console.log('mobile');
}
If/elseis not likeswitch. In any requirements matching condition it returns.