Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use variables and functions of JS correctly

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to correctly use the variables and functions of JS". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to correctly use the variables and functions of JS".

I. variables

Use meaningful and pronounced variable names

/ / bad writing const yyyymmdstr = moment () .format ("YYYY/MM/DD"); / / good writing const currentDate = moment () .format ("YYYY/MM/DD")

Use the same vocabulary for variables of the same type

/ / bad writing getUserInfo (); getClientData (); getCustomerRecord (); / / good writing getUser ()

Use a searchable name

We read a lot more than we write, so naming too casually will not only make it difficult for subsequent maintenance, but also hurt developers who read our code. To make your variable names readable, tools like buddy.js and ESLint can help identify unnamed constants.

/ / bad writing / / what is the purpose of 86400000? SetTimeout (blastOff, 86400000); / / good writing const MILLISECONDS_IN_A_DAY = 86, 400, 000; setTimeout (blastOff, MILLISECONDS_IN_A_DAY)

Use interpretive variables

/ / bad writing const address = "One Infinite Loop, Cupertino 95014"; const cityZipCodeRegex = / ^ [^,\] + [,\\ s] + (. +?)\ s * (\ d {5})? $/; saveCityZipCode (address.match (cityZipCodeRegex) [1], address.match (cityZipCodeRegex) [2]); / / good writing const address = "One Infinite Loop, Cupertino 95014" Const cityZipCodeRegex = / ^ [^,\] + [,\\ s] + (. +?)\ s * (\ d {5})? $/; const [_, city, zipCode] = address.match (cityZipCodeRegex) | | []; saveCityZipCode (city, zipCode)

Avoid brain-wasting guesses

Explicitly used for implicit

/ / the bad way to write const locations = ["Austin", "New York", "San Francisco"]; locations.forEach (l = > {doStuff (); doSomeOtherStuff (); / /... / etc., what is "l"? Dispatch (l); / / good writing const locations = ["Austin", "New York", "San Francisco"]; locations.forEach (location = > {doStuff (); doSomeOtherStuff (); / /. Dispatch (location);})

There is no need to add unnecessary context

If the class name / object name is already specified, there is no need to repeat it in the variable name.

/ / bad writing const Car = {carMake: "Honda", carModel: "Accord", carColor: "Blue"}; function paintCar (car) {car.carColor = "Red";} / / good const Car = {make: "Honda", model: "Accord", color: "Blue"}; function paintCar (car) {car.color = "Red";}

Use default parameters instead of logical or (and) operations

/ / bad function createMicrobrewery (name) {const breweryName = name | | "Hipster Brew Co."; / /...} / / good function createMicrobrewery (name = "Hipster Brew Co.") {/ /.}

Second, function

Function arguments (ideally 2 or less)

It is important to limit the number of function parameters because it makes it easier to test the function. If there are more than three parameters, it will cause a combined explosion, and a large number of different situations must be tested with each individual parameter.

One or two parameters are ideal, and three parameters should be avoided if possible. In addition, it should also be merged. In most cases, more than three parameters can be replaced by objects.

/ bad function createMenu (title, body, buttonText, cancellable) {/ /...} createMenu ("Foo", "Bar", "Baz", true); / / good writing function createMenu ({title, body, buttonText, cancellable}) {/ /...} createMenu ({title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true})

Function should only do one thing

This is by far the most important rule in software engineering. When functions do more than one thing, they are more difficult to combine, test, and reason. When you can isolate a function into an operation, it can be easily refactored and the code will be read more clearly.

/ / bad writing function emailClients (clients) {clients.forEach (client = > {const clientRecord = database.lookup (client); if (clientRecord.isActive ()) {email (client);}});} / good writing function emailActiveClients (clients) {clients.filter (isActiveClient) .forEach (email);} function isActiveClient (client) {const clientRecord = database.lookup (client); return clientRecord.isActive ();}

The function name should indicate its function.

/ / bad writing function addToDate (date, month) {/ /...} const date = new Date (); / / it is difficult to know what addToDate to add from the function name (date, 1); / / good writing function addMonthToDate (month, date) {/ /...} const date = new Date (); addMonthToDate (1, date)

Functions should have only one level of abstraction

When there is more than one abstract level function, it means that the function has done too much, and the function needs to be split to achieve reusability and easier testing.

/ / function parseBetterJSAlternative (code) {const REGEXES = [/ /...]; const statements = code.split (""); const tokens = []; REGEXES.forEach (REGEX = > {statements.forEach (statement = > {/ /...});}); const ast = []; tokens.forEach (token = > {/ / lex...) }); ast.forEach (node = > {/ / parse... });} / / good function parseBetterJSAlternative (code) {const tokens = tokenize (code); const syntaxTree = parse (tokens); syntaxTree.forEach (node = > {/ / parse...) });} function tokenize (code) {const REGEXES = [/ /...]; const statements = code.split (""); const tokens = []; REGEXES.forEach (REGEX = > {statements.forEach (statement = > {tokens.push (/ * * /);});}); return tokens;} function parse (tokens) {const syntaxTree = [] Tokens.forEach (token = > {syntaxTree.push (/ *... * /);}); return syntaxTree;}

Delete duplicate code

Try to avoid repetitive code, repetitive code is not good, it means that if we need to change some logic, we have to change a lot of things.

Usually, there is repetitive code because there are two or more slightly different things that have a lot in common, but the differences between them force us to write two or more separate functions to do many of the same things. Removing duplicate code means creating an abstraction that can handle this set of different things with just one function / module / class.

It is critical to get the right abstraction, which is why we should follow the "SOLID principles" listed in the classes section. Bad abstraction can be worse than repetitive code, so be careful! Having said so much, if you can make a good abstraction, do it! Don't repeat yourself, or you'll find yourself updating multiple places whenever you want to change something.

"the six principles of design patterns are"

Single Responsibility Principle: the principle of single responsibility

Open Closed Principle: opening and closing principle

Liskov Substitution Principle: Richter substitution principle

Law of Demeter: Demeter's rule

Interface Segregation Principle: interface isolation principle

Dependence Inversion Principle: dependency inversion principle

Combining the initials of these six principles (the two L counts as one) is SOLID (stable), which represents the benefits of the combination of these six principles: to build a stable, flexible, and robust design. Let's take a look at these six design principles respectively.

"A bad way to write."

Function showDeveloperList (developers) {developers.forEach (developer = > {const expectedSalary = developer.calculateExpectedSalary (); const experience = developer.getExperience (); const githubLink = developer.getGithubLink (); const data = {expectedSalary, experience, githubLink}; render (data);});} function showManagerList (managers) {managers.forEach (manager = > {const expectedSalary = manager.calculateExpectedSalary (); const experience = manager.getExperience ()) Const portfolio = manager.getMBAProjects (); const data = {expectedSalary, experience, portfolio}; render (data);};}

"good way to write."

Function showEmployeeList (employees) {employees.forEach (employee = > {const expectedSalary = employee.calculateExpectedSalary (); const experience = employee.getExperience (); const data = {expectedSalary, experience}; switch (employee.type) {case "manager": data.portfolio = employee.getMBAProjects (); break; case "developer": data.githubLink = employee.getGithubLink (); break } render (data);});}

Set the default object using Object.assign

"A bad way to write."

Const menuConfig = {title: null, body: "Bar", buttonText: null, cancellable: true}; function createMenu (config) {configconfig.title = config.title | | "Foo"; configconfig.body = config.body | | "Bar"; configconfig.buttonText = config.buttonText | | "Baz"; configconfig.cancellable = config.cancellable! = undefined? Config.cancellable: true;} createMenu (menuConfig)

"good way to write."

Const menuConfig = {title: "Order", / / User did not include 'body' key buttonText: "Send", cancellable: true}; function createMenu (config) {config = Object.assign ({title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true}, config) / / config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true} / /.} createMenu (menuConfig)

Do not use flags as function arguments

The flag tells the user that this function can accomplish multiple tasks and that the function should do one thing. If functions follow different Boolean-based code paths, split them.

/ / bad function createFile (name, temp) {if (temp) {fs.create (`. / temp/$ {name}`);} else {fs.create (name);}} / good function createFile (name) {fs.create (name);} function createTempFile (name) {createFile (`. / temp/$ {name}`);}

Avoid side effects (part I)

Side effects can occur if a function does nothing but accept one value and return another or more values. The side effects may be writing to files, modifying some global variables, or accidentally remitting all your money to strangers.

"A bad way to write."

Let name = "Ryan McDermott"; function splitIntoFirstAndLastName () {namename = name.split (");} splitIntoFirstAndLastName (); console.log (name); / / ['Ryan',' McDermott']

"good way to write."

Function splitIntoFirstAndLastName (name) {return name.split (");} const name =" Ryan McDermott "; const newName = splitIntoFirstAndLastName (name); console.log (name); / / 'Ryan McDermott'; console.log (newName); / / [' Ryan', 'McDermott']

Avoid side effects (part II)

In JavaScript, primitive type values are passed by value, while objects / arrays are passed by reference. For objects and arrays, if a function is changed in the shopping cart array (for example, by adding items to be purchased), any other functions that use the shopping cart array will be affected by this addition. That may be great, but it may also be bad. To imagine a bad situation:

The user clicks the Buy button, which calls a purchase function, which then makes a network request and sends the cart array to the server. Due to a poor network connection, the purchase function must constantly retry the request. Now, what if users accidentally click the add to Shopping cart button on items they don't actually need before the web request starts? If this happens and the network request starts, the purchase function sends the accidentally added item because it has a reference to the shopping cart array that the addItemToCart function modifies by adding.

A good solution is that addItemToCart always clones the cart array, edits it, and then returns the clone. This ensures that other functions referenced by the shopping cart are not affected by any changes.

There are two points to note about this approach:

Maybe in some cases, we do need to modify the input object, but when we adopt this programming practice, we will find that this is very rare, and most things can be modified to have no side effects.

Cloning large objects can be very expensive in terms of performance. Fortunately, this is not a big problem in practice, because there are many great libraries that make this programming method fast and do not take up as much memory as manually cloning objects and arrays.

/ / bad writing const addItemToCart = (cart, item) = > {cart.push ({item, date: Date.now ()});}; / / good writing const addItemToCart = (cart, item) = > {return [. Cart, {item, date: Date.now ()}];}

Do not write global functions

Polluting global variables is a bad practice in JS because it may conflict with another library and users of API will be useless until they encounter an exception in their production. Let's consider an example: what if you want to extend the native Array method of JS to have a diff method that shows the difference between two arrays? You can write a new function to Array.prototype, but it may conflict with another library that is trying to perform the same operation. What if other libraries only use diff to find the difference between the first and last elements of an array? That's why it's better to just use the ES6 class and simply extend the Array global.

/ / bad writing Array.prototype.diff = function diff (comparisonArray) {const hash = new Set (comparisonArray); return this.filter (elem = >! hash.has (elem));}; / / good writing class SuperArray extends Array {diff (comparisonArray) {const hash = new Set (comparisonArray); return this.filter (elem = >! hash.has (elem);}}

Try to use functional programming instead of imperative

JavaScript is not a functional language like Haskell, but it has a functional style. Functional languages can be more concise and easier to test. Try to like this programming style if you can.

"A bad way to write."

Const programmerOutput = [{name: "Uncle Bobby", linesOfCode: 500}, {name: "Suzie Q", linesOfCode: 1500}, {name: "Jimmy Gosling", linesOfCode: 1500}, {name: "Gracie Hopper", linesOfCode: 1000}]; let totalOutput = 0; for (let I = 0; I)

< programmerOutput.length; i++) { totalOutput += programmerOutput[i].linesOfCode; } 「好的写法」 const programmerOutput = [ { name: "Uncle Bobby", linesOfCode: 500 }, { name: "Suzie Q", linesOfCode: 1500 }, { name: "Jimmy Gosling", linesOfCode: 150 }, { name: "Gracie Hopper", linesOfCode: 1000 } ]; const totalOutput = programmerOutput.reduce( (totalLines, output) =>

TotalLines + output.linesOfCode, 0)

Encapsulation condition

/ / Bad if (fsm.state = = "fetching" & & isEmpty (listNode)) {/ /...} / / good function shouldShowSpinner (fsm, listNode) {return fsm.state = = "fetching" & & isEmpty (listNode);} if (shouldShowSpinner (fsmInstance, listNodeInstance)) {/ /.}

Avoid using non-conditional

/ / bad writing function isDOMNodeNotPresent (node) {/ /...} if (! isDOMNodeNotPresent (node)) {/ /...} / / good writing function isDOMNodePresent (node) {/ /...} if (isDOMNodePresent (node)) {/ /.}

Avoid using too many conditions

This seems to be an impossible task. When you hear this, most people will say, "how can I do anything without an if statement?" The answer is that you can use polymorphism to accomplish the same task in many cases.

The second question is usually, "that's good, but why would I do that?" The answer is the concept mentioned above: a function should only do one thing. When you have classes and functions with if statements, this is telling your users that the function does more than one thing.

"A bad way to write."

Class Airplane {/ /... GetCruisingAltitude () {switch (this.type) {case ()-this.getPassengerCount (); case "Air Force One": return this.getMaxAltitude (); case "Cessna": return this.getMaxAltitude ()-this.getFuelExpenditure ();}

"good way to write."

Class Airplane {/ /...} class Boeing777 extends Airplane {/ /... GetCruisingAltitude () {return this.getMaxAltitude ()-this.getPassengerCount ();} class AirForceOne extends Airplane {/ /... GetCruisingAltitude () {return this.getMaxAltitude ();}} class Cessna extends Airplane {/ /... GetCruisingAltitude () {return this.getMaxAltitude ()-this.getFuelExpenditure ();}}

Avoid type checking

JavaScript is untyped, which means that the function can accept any type of argument. Sometimes we are bothered by this freedom and want to do type checking in the function. There are many ways to avoid doing so. The first thing to consider is a consistent API.

/ / bad writing function travelToTexas (vehicle) {if (vehicle instanceof Bicycle) {vehicle.pedal (this.currentLocation, new Location ("texas"));} else if (vehicle instanceof Car) {vehicle.drive (this.currentLocation, new Location ("texas"));}} / good function travelToTexas (vehicle) {vehicle.move (this.currentLocation, new Location ("texas"));}

Don't over-optimize.

Modern browsers do a lot of optimization work at run time. A lot of times, if you're optimizing, you're just wasting your time. There are good resources to see where optimization is missing, and we just need to focus on where it needs to be optimized.

/ / Bad writing / / in old browsers, every iteration using cacheless "list.length" was expensive / / recalculated for "list.length". In modern browsers, this is the optimized for (let I = 0, len = list.length; I < len; iTunes +) {/ /...} / / good for (let I = 0; I < list.length) Thank you for reading, the above is the content of "how to correctly use the variables and functions of JS". After the study of this article, I believe you have a deeper understanding of how to correctly use the variables and functions of JS, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report