{"id":24598,"date":"2024-04-08T21:24:25","date_gmt":"2024-04-08T20:24:25","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/estructuras-de-control-condicionales-switch-en-javascript\/"},"modified":"2024-06-03T17:36:35","modified_gmt":"2024-06-03T16:36:35","slug":"estructuras-de-control-condicionales-switch-en-javascript","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/","title":{"rendered":"Switch Conditional Control Structures in JavaScript"},"content":{"rendered":"<p>In programming, control structures are essential to create programs that make decisions and execute different actions depending on different conditions. Among these structures, one of the best known and most used is <code>switch<\/code>, especially in the JavaScript programming language. In this article, we will delve into the use of conditional structures <code>switch<\/code> and its relevance within the fundamentals of JavaScript.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#%C2%BFQue_son_las_Estructuras_de_Control_Condicionales\" >What are Conditional Control Structures?<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Definicion_y_Proposito\" >Definition and Purpose<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Tipos_de_Estructuras_Condicionales\" >Types of Conditional Structures<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Fundamentos_de_JavaScript_El_Uso_de_Switch\" >JavaScript Fundamentals: Using Switch<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Sintaxis_Basica\" >Basic Syntax<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#%C2%BFComo_Funciona_Switch\" >How does Switch work?<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Ventajas_de_Usar_Switch_en_JavaScript\" >Advantages of Using Switch in JavaScript<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Claridad_en_Casos_Multiples\" >Clarity in Multiple Cases<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Facilidad_de_Lectura_y_Mantenimiento\" >Ease of Reading and Maintenance<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Optimizacion_de_Rendimiento\" >Performance Optimization<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Mejores_Practicas_al_Usar_Switch_en_JavaScript\" >Best Practices When Using Switch in JavaScript<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Siempre_Incluir_Break\" >Always Include Break<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Uso_Adecuado_de_Default\" >Proper Use of Default<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Evitar_Casos_Complejos\" >Avoid Complex Cases<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Casos_de_Uso_Comunes_para_Condicionales_Switch\" >Common Use Cases for Conditional Switches<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Menus_de_Navegacion\" >Navigation Menus<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Asignaciones_de_Codigo_de_Error\" >Error Code Assignments<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Maquinas_de_Estado_Simples\" >Simple State Machines<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Ejemplos_de_Switch_en_JavaScript\" >Switch Examples in JavaScript<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Ejemplo_1_Menu_de_Seleccion\" >Example 1: Selection Menu<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-21\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Ejemplo_2_Manejo_de_Respuestas_HTTP\" >Example 2: HTTP Response Handling<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-22\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Limitaciones_y_Consideraciones_de_Switch\" >Switch Limitations and Considerations<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-23\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Tipo_de_Comparacion\" >Comparison Type<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-24\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Solo_para_Valores_Discretos\" >Only for Discrete Values<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-25\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#No_Para_Logica_Compleja\" >Not For Complex Logic<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-26\" href=\"https:\/\/nelkodev.com\/en\/blog\/switch-conditional-control-structures-in-javascript\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"%C2%BFQue_son_las_Estructuras_de_Control_Condicionales\"><\/span>What are Conditional Control Structures?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Definicion_y_Proposito\"><\/span>Definition and Purpose<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Conditional control structures are blocks of code that allow developers to direct the flow of program execution depending on one or more conditions. These structures evaluate an expression and, depending on the result, the program can follow different paths.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Tipos_de_Estructuras_Condicionales\"><\/span>Types of Conditional Structures<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The two most common types of conditional control structures are <code>if-else<\/code> y <code>switch<\/code>. While <code>if-else<\/code> It is excellent for checking several conditions that are not necessarily related to each other, <code>switch<\/code> It is ideal for when you have multiple cases that depend on the value of a single variable or expression.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Fundamentos_de_JavaScript_El_Uso_de_Switch\"><\/span>JavaScript Fundamentals: Using Switch<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Sintaxis_Basica\"><\/span>Basic Syntax<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In JavaScript, the syntax for <code>switch<\/code> is defined as follows:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">switch (expression) { case value1: \/\/ Code block to execute if expression is equal to value1 break; case value2: \/\/ Code block to execute if expression is equal to value2 break; \/\/ There may be more cases here default: \/\/ Block of code that is executed if none of the above cases are true }<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"%C2%BFComo_Funciona_Switch\"><\/span>How does Switch work?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>He <code>switch<\/code> evaluates the given expression and compares its value with the different options listed in the cases (<code>case<\/code>). If it finds a match, it executes the corresponding code block until an instruction is found <code>break<\/code>, which ends the execution of the <code>switch<\/code>. If none of the cases match, the block will be executed in <code>default<\/code>, if present.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Ventajas_de_Usar_Switch_en_JavaScript\"><\/span>Advantages of Using Switch in JavaScript<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Claridad_en_Casos_Multiples\"><\/span>Clarity in Multiple Cases<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>When compared to a series of statements <code>if-else<\/code>, <code>switch<\/code> is clearer and more concise, especially when dealing with multiple conditions based on the value of a single variable.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Facilidad_de_Lectura_y_Mantenimiento\"><\/span>Ease of Reading and Maintenance<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The code is more readable and easier to maintain, since <code>switch<\/code> groups all related cases into a single control block.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Optimizacion_de_Rendimiento\"><\/span>Performance Optimization<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In some cases, the use of <code>switch<\/code> can optimize performance compared to <code>if-else<\/code>, although the differences are usually minimal and depend on the implementation of the JavaScript engine of the browser or environment.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Mejores_Practicas_al_Usar_Switch_en_JavaScript\"><\/span>Best Practices When Using Switch in JavaScript<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Siempre_Incluir_Break\"><\/span>Always Include Break<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>It is crucial to include an instruction <code>break<\/code> at the end of each case to avoid the phenomenon known as &quot;fall-through&quot;, where multiple blocks can be executed unexpectedly.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Uso_Adecuado_de_Default\"><\/span>Proper Use of Default<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The clause <code>default<\/code> It is useful for handling situations where none of the specified cases match. Be sure to include it when default behavior is required.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Evitar_Casos_Complejos\"><\/span>Avoid Complex Cases<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>If your conditions become complex, you should consider using <code>if-else<\/code> or refactor your code. <code>switch<\/code> It is best suited for direct comparisons and not for complicated conditional logic.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Casos_de_Uso_Comunes_para_Condicionales_Switch\"><\/span>Common Use Cases for Conditional Switches<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Menus_de_Navegacion\"><\/span>Navigation Menus<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><code>switch<\/code> is ideal for implementing behaviors in navigation menus where an action (such as clicking a button) results in different responses depending on the selected item.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Asignaciones_de_Codigo_de_Error\"><\/span>Error Code Assignments<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Can be used <code>switch<\/code> to assign specific error messages based on the error code returned by a function or an HTTP request, improving the clarity of error handling.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Maquinas_de_Estado_Simples\"><\/span>Simple State Machines<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>For systems that have a set of well-defined states, such as an automaton or a game with game states (start, pause, play, end), <code>switch<\/code> can be an efficient tool to handle state changes.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Ejemplos_de_Switch_en_JavaScript\"><\/span>Switch Examples in JavaScript<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Let&#039;s look at some examples of how to use <code>switch<\/code> in different common scenarios.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Ejemplo_1_Menu_de_Seleccion\"><\/span>Example 1: Selection Menu<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<pre><code class=\"&quot;language-javascript&quot;\">const selection = &#039;start&#039;; switch (selection) { case &#039;start&#039;: startGame(); break; case &#039;options&#039;: showOptions(); break; case &#039;exit&#039;: exitGame(); break; default: showHelp(); }<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Ejemplo_2_Manejo_de_Respuestas_HTTP\"><\/span>Example 2: HTTP Response Handling<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<pre><code class=\"&quot;language-javascript&quot;\">const responseCode = 404; switch (responsecode) { case 200: console.log(&#039;The request was successful&#039;); break; case 401: console.log(&#039;Unauthorized&#039;); break; case 404: console.log(&#039;Resource not found&#039;); break; default: console.log(&#039;An unknown error occurred&#039;); }<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Limitaciones_y_Consideraciones_de_Switch\"><\/span>Switch Limitations and Considerations<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Tipo_de_Comparacion\"><\/span>Comparison Type<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><code>switch<\/code> perform a strict comparison (<code>===<\/code>), which means that the type and value must match.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Solo_para_Valores_Discretos\"><\/span>Only for Discrete Values<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Not suitable for ranges or conditions based on greater or less than; For those cases, you should use <code>if-else<\/code>.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"No_Para_Logica_Compleja\"><\/span>Not For Complex Logic<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><code>switch<\/code> It should not be used if the conditions depend on multiple variables or require more complex logic.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The conditional structures <code>switch<\/code> in JavaScript are a powerful and efficient tool for handling multiple cases based on the value of a single expression. They offer clarity, maintainability, and readability benefits that can make our code cleaner and more direct. However, like any other tool in programming, they must be used correctly and in the right context. With the practices and examples presented, you are well equipped to start using <code>switch<\/code> effectively in your JavaScript projects.<\/p>","protected":false},"excerpt":{"rendered":"<p>In programming, control structures are essential for creating programs that make decisions and execute different actions depending on different conditions. Among these structures, one of the most well-known and used is switch, especially in the JavaScript programming language. In this article, we will delve into the use of switch and conditional structures.<\/p>","protected":false},"author":1,"featured_media":24599,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420,1123],"tags":[205,792,330,784,518,185,1444],"class_list":["post-24598","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","category-fundamentos","tag-blog","tag-condicionales","tag-control","tag-estructuras","tag-fundamentos","tag-javascript","tag-switch"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/24598","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=24598"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/24598\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/24599"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=24598"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=24598"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=24598"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}