How JavaScript moves duplicate code to the same location
This article mainly introduces how JavaScript moves the repeated code to the same location, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.
Move duplicate code to the same location
We should extract the duplicate code and merge it into the same location, so that when we need to change it, we only need to change one place, and at the same time reduce the error rate.
Suppose we are likely to write the following code:
Const button = document.querySelector ('button'); let toggled = true; button.addEventListener (' click', () = > {toggled =! toggled; if (toggled) {document.querySelector ("p"). Style.color = 'red';} else {document.querySelector ("p"). Style.color =' green';}})
There are two document.querySelector ("p") in the above code, which we can optimize by saving document.querySelector ("p") to a variable and then using that variable, as shown below:
Const button = document.querySelector ('button'); const p = document.querySelector ("p"); let toggled = true; button.addEventListener (' click', ()) = > {toggled =! toggled; if (toggled) {p.style.color = 'red';} else {p.style.color =' green';}}
So we don't have to write a long document.querySelector ("p"), just write a variable p.
Numbers in another common code example, it's hard to know what they mean just by looking at them:
Let x = 1; let y = 1; let z = 1
We don't know what the above three ones mean, so we can remove the duplicate code and represent it with an appropriate variable name, as shown below:
Const numPeople = 1; let x = numPeople; let y = numPeople; let z = numPeople
So we can know that the value of numPeople is 1, which represents the number of people.
Thank you for reading this article carefully. I hope the article "JavaScript how to move repeated code to the same location" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!