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
1. The window size opened by the HTML hyperlink C...
One day, the leader put forward a requirement to ...
01. Command Overview md5sum - Calculate and verif...
In the page, external files such as js, css, etc. ...
1. First go to the official website https://www.p...
This article shares the specific code of JS to ac...
Table of contents Scenario Task idea analyze Conc...
today select * from table name where to_days(time...
Vim is a text editor that we use very often in Li...
This article example shares the specific code of ...
It seems that the mysql-sever file for installing...
This article shares the specific code of JS+AJAX ...
Table of contents 1. Simple retrieval of data 2. ...
This article example shares the specific code of ...
In a complex table structure, some cells span mul...