Home>Article>Web Front-end> Several practical JavaScript optimization tips worth knowing
In our work, we can often increase the readability of the code through some small details and make the code look more elegant. This article will share with you some practical JavaScript optimization tips that you can understand at a glance. I hope it will be helpful to you!
「Difficulty:?」「Recommended reading time: 5min
」
if ...else
function, you should think about whether there is a better optimization method. [Related recommendations:javascript learning tutorial]if...else
statement to the internal logic also violates theopening and closing principleto a certain extent. When we need to add a logic, we should try our best to extend the software entity. Address changes in requirements rather than modifying existing code to accomplish changes.Map
to save all products. Here we directly create an object for storage.getPrice
next time we need to add another product. Of course, here is actually More people like to usefoodMap
directly where they are used. I just gave a simple example to express this idea.key
just use strings, then you can usenew Map
, idea It's almost the same, with an additional entity extended to store changes.filter
andmap
instead offor
loop, it can not only make The code is more streamlined and the semantics can be made clearer, so that we can see at a glance that the array is firstfiltered
and thenreorganized
.find
comes into play when searching for specific food in an array based on attribute values.includes
function.return
. This habit is actually bad, because we need to clarify the logic again when we refer to this code next time.result
as the return value.However, usingresult
as the return value above does not apply to all situations. Sometimes we need to end early. Function body to prevent colleagues later from reading redundant programs.
In the following example, when ourselectedKey
does not exist, we shouldreturn
immediately, so that we don’t need to continue reading the following code, otherwise we will face For more complex functions, a lot of reading cost will be increased.
getDocDetail
not only usesicon
andcontent
, but alsotitle
in the future,date
and other attributes, so we might as well pass in the complete object directly, which not only shortens the parameter list but also makes the code more readable.null
or undefined, you can use the simple writing method.[Related video tutorial recommendations:web front-end]
The above is the detailed content of Several practical JavaScript optimization tips worth knowing. For more information, please follow other related articles on the PHP Chinese website!