No switch, no complex code blocksSwitch is convenient: given an expression, we can check whether it matches a bunch of other expressions in a case clause. Consider the following example: const name = "Juliana"; switch (name) { case "Juliana": console.log("She's Juliana"); break; case "Tom": console.log("She's not Juliana"); break; } When name is "Juliana", we print a message and immediately break out of the block. When inside a switch function, you can omit break by using return directly in the case block. When there are no matches, the default option can be used: const name = "Kris"; switch (name) { case "Juliana": console.log("She's Juliana"); break; case "Tom": console.log("She's not Juliana"); break; default: console.log("Sorry, no match"); } Switch is also used heavily in Redux reducers (although Redux Toolkit simplifies the boilerplate a bit) to avoid having lots of if s. Consider the following example: const LOGIN_SUCCESS = "LOGIN_SUCCESS"; const LOGIN_FAILED = "LOGIN_FAILED"; const authState = { token: "", error: "", }; function authReducer(state = authState, action) { switch (action.type) { case LOGIN_SUCCESS: return { ...state, token: action.payload }; case LOGIN_FAILED: return { ...state, error: action.payload }; default: return state; } } Is there anything wrong with this? Hardly. But is there a better alternative? Inspiration from PythonThis Tweet from Telmo caught my attention. He shows two styles of "switch", one of which is very close to the pattern in Python. Python doesn't have a switch, which gives us a better alternative. First let's port the code from JavaScript to Python: LOGIN_SUCCESS = "LOGIN_SUCCESS" LOGIN_FAILED = "LOGIN_FAILED" auth_state = {"token": "", "error": ""} def auth_reducer(state=auth_state, action={}): mapping = { LOGIN_SUCCESS: {**state, "token": action["payload"]}, LOGIN_FAILED: {**state, "error": action["payload"]}, } return mapping.get(action["type"], state) In Python, we can use a dictionary to simulate switch. dict.get() can be used to represent the default statement of a switch. When accessing a non-existent key, Python will trigger a KeyError error:
The .get() method is a safer approach because it will not raise an error and you can specify a default value for a non-existent key:
Therefore, this line in Python: return mapping.get(action["type"], state) The equivalent in JavaScript is: function authReducer(state = authState, action) { ... default: return state; ... } Use dictionary to replace switchConsider the previous example again: const LOGIN_SUCCESS = "LOGIN_SUCCESS"; const LOGIN_FAILED = "LOGIN_FAILED"; const authState = { token: "", error: "", }; function authReducer(state = authState, action) { switch (action.type) { case LOGIN_SUCCESS: return { ...state, token: action.payload }; case LOGIN_FAILED: return { ...state, error: action.payload }; default: return state; } } Without using switch we can do this: function authReducer(state = authState, action) { const mapping = { [LOGIN_SUCCESS]: { ...state, token: action.payload }, [LOGIN_FAILED]: { ...state, error: action.payload } }; return mapping[action.type] || state; } Here we use computed properties in ES6. Here, the properties of mapping are calculated on the fly based on two constants: LOGIN_SUCCESS and LOGIN_FAILED. const mapping = { [LOGIN_SUCCESS]: { ...state, token: action.payload }, [LOGIN_FAILED]: { ...state, error: action.payload } } What do you think of this approach? It may have some limitations for switches, but it may be a better solution for reducers. But how does this code perform? How is the performance?The performance of switch is better than that of dictionary. We can test this using the following example: console.time("sample"); for (let i = 0; i < 2000000; i++) { const nextState = authReducer(authState, { type: LOGIN_SUCCESS, payload: "some_token" }); } console.timeEnd("sample"); Measure them about ten times,
The above is the details of why you may not need to use the switch statement in JavaScript. For more information about JavaScript switch statements, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: A brief discussion on Mysql specified order sorting query
>>: Mysql5.6.36 script compilation, installation and initialization tutorial
introduction: There are a lot of information and ...
Table of contents 1. Cross-domain filter CorsFilt...
State Hooks Examples: import { useState } from ...
In the vertical direction, you can set the cell a...
Using js in web design can achieve many page effec...
transform: scale(); Scaling will cause jitter in ...
Phenomenon When using Apache Spark 2.x, you may e...
Shell is a program written in C language, which i...
How can you find the location of the configuratio...
JavaScript can do a lot of great things. This art...
Easy installation of opencv2: conda install --cha...
This article shares the specific code of JS canva...
Table of contents Create a global shared content ...
Table of contents 1. Baidu Encyclopedia 1. MySQL ...
Date-type single-row functions in MySQL: CURDATE(...