gengns ES

An entry from the gengns log, written by Génesis García Morilla · · JavaScript

Avoid switch statement when you don’t need logic

Arrays are faster when you don’t need logic, you can also use an string but it’s a little more triky.

// JS
var array = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", 
"Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];

$("div").text(months_array.indexOf("Febrero") + 1);

See a real example:

JavaScript

var months_function = function(monthname) {
    switch (monthname) {
        case "Enero":
            return 1;
        case "Febrero":
            return 2;
        case "Marzo":
            return 3;
        case "Abril":
            return 4;
        case "Mayo":
            return 5;
        case "Junio":
            return 6;
        case "Julio":
            return 7;
        case "Agosto":
            return 8;
        case "Septiembre":
            return 9;
        case "Octubre":
            return 10;
        case "Noviembre":
            return 11;
        case "Diciembre":
            return 12;
    }
    
    return -1;
}

var months_array = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];

var months_str = "Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre";

$("#A").text("Switch: " + months_function("Febrero"));
$("#B").text("Array: " + (months_array.indexOf("Febrero") + 1));
$("#C").text("String: " + (
    months_str.substring(0,months_str.indexOf("Febrero")).split(" ").length
));

HTML

<h2>Get month number using <em>switch, array or string</em></h2>
<label>February</label>
<ul>
    <li id="A"></li>
    <li id="B"></li>
    <li id="C"></li>
</ul>
<p>Arrays are faster when you don't need logic, you can also use a string but it's a little more triky.</p>

CSS

body {
    color: #333;
}
Open in JSFiddle

Tags: jQuery