[Javascript] Upgrading Parameter Creation Techniques in JS Functions
Ph?m ?ình Thi?n
??Lead Software Engineer @ MISA JSC | Youtube “Ph?m ?ình Thi?n - T?i ?u Frontend”
1. Concept
A function is a very familiar concept in programming and it plays an important role in code reuse, increasing modularity, and making code more readable. A function can have one or more parameters and they are used inside the function. In addition, we can also assign default values to function parameters.
There are many different techniques for creating function parameters and in this article I will introduce you to 3 techniques for creating parameters from basic to advanced.
2. Parameter Creation Techniques in Javascript Functions
For example, we are given a small task: Create a function to print user information.
With this requirement, we will apply the 3 techniques for function parameter creation below.
2.1. "Traditional" Technique
However, the problem starts to arise when the printPerson function has been called in many places in the project. When we need to add a new parameter to the function, in order to handle it properly and avoid affecting the project, we usually add that new parameter to the end of the function.
Ex1: The task requires printing additional information about the user's date of birth, we handle it as follows:
Advantages:
Disadvantages:
To overcome the disadvantage of "have to pass the correct order and full value of the parameters", "the function contains too many parameters", we apply the second technique: "Putting all eggs in one basket" technique.
2.2. "Putting all eggs in one basket" technique
The idea of this technique is to take advantage of JSON Objects to make parameters passed into the function and we only need one parameter to add the fields we need.
领英推荐
If we need to add more new fields, we just add them to the function's object parameter.
Ex2: Re-handling the requirement to print additional date of birth information, we modify it as follows:
Advantages:
Disadvantages:
To address all the disadvantages of the two techniques above, we apply a very useful technique called JSON Destructuring.
3. "JSON Destructuring" Technique
In essence, this technique utilizes the Destructuring mechanism for JSON Objects in Javascript.
Ex3: Re-handling the requirement to print additional date of birth information, we modify it as follows:
Advantages:
The above are 3 techniques that help improve the creation of Function Parameters, which I hope will be useful for you. If you have any comments or discussions, please comment below the article. Thanks all!
#javascript #frontend