Home > Web Front-end > JS Tutorial > Why I Use a JavaScript Style Guide and Why You Should Too

Why I Use a JavaScript Style Guide and Why You Should Too

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-02-17 11:45:12
Original
1000 people have browsed it

Why I Use a JavaScript Style Guide and Why You Should Too

Key Points

  • Embroidery JavaScript style guides such as JavaScript Standard Style help reduce team friction, improve programmers' happiness, and ensure code consistency.
  • Coding with mainstream styles of languages ​​such as JavaScript makes it easier to contribute to open source projects and let others contribute to your projects.
  • Style guides don't necessarily make the program more correct, but it can catch errors before errors are posted, making the code easier to read and understand, and prevent disagreements among team members.
  • Implementing JavaScript Standard Style can be done without any tools, but there are npm packages that can be used in lint JavaScript code and text editor plug-ins to help enforce styles.

Let's take a look at @feross' JavaScript Standard Style, a more popular JavaScript style guide. It can help you reduce team friction and improve programmers’ happiness.

It is a set of rules that make JavaScript code more consistent and prevents boring discussions about the advantages and disadvantages of tabs and spaces. It is one of many styles you can take and falls into the same category as other JavaScript linters such as JSLint, JSHint, and ESLint. If you are not sure what linter is, or why you need it, check out our comparison of JavaScript linting tools.

The importance of style

If you have been writing code for a while, you will undoubtedly develop the style you like. This happens when you write a specific pattern hundreds or thousands of times, and you start to find your coding aesthetically pleasing. Suddenly, others came and started placing brackets in strange places and leaving spaces at the end of the line. Some text may be needed. Taking a deep breath, the way you place brackets or select spaces will not make your program more correct, which is a

personal

preference. Every programming language has a

mainstream

style, and sometimes like Python, the official style guide is presented as a correct method to write programs. Wait, do you say indentation is 4 spaces? Coding with the mainstream style of the language will help your program adapt to the language's ecosystem. If you are familiar and agree at the beginning, you will also find it easier to contribute to open source projects and let others contribute to your project.

JavaScript has no official style guide, and maybe a de facto standard appears in Douglas Crockford's "Excellent Part". His book proposes a way to write reliable JavaScript programs, and he emphasizes features that we should actively avoid. He posted JSLint to support these views, and other linters followed suit. Most linters are highly configurable, you can choose the style that suits you best, and better yet, enforce it to others! JavaScript Standard Style is different. Your favorite style is Nothing, it is important to choose a style that anyone can understand and use.

Why I Use a JavaScript Style Guide and Why You Should Too

Adopting a standard style means putting the importance of code clarity and community norms above personal style. This may not make sense for 100% of the project and development culture, but open source can be a hostile place for beginners. Building clear, automated contributor expectations will make the project healthier.

If you are writing a program for yourself that no one needs to participate in contributing, use the tools and styles that make you happiest. When working on a team, you should always minimize friction, stay professional and not worry about small things.

Please take the time to learn the styles of existing code bases before introducing your own styles.

JavaScript Standard Style

  • 2 spaces - for indentation
  • Strings use single quotes - unless to avoid escape
  • No unused variables - this can catch a lot of errors!
  • No semicolon
  • Do not start with (, [ or `
  • There are spaces after the keyword if (condition) { ... }
  • There is space after the function name function name (arg) { ... }
  • Always use === instead of == - but allow obj == null to check null || undefined.
  • Always handle Node.js err function parameters
  • Always add window prefix to browser global variables - but document and navigator can
    • Prevents accidental use of improperly named browser global variables such as open, length, event, and name.

View the full list of rules

The most controversial rule is undoubtedly the absence of a semicolon. For years, people have thought that semicolons should always be to avoid errors, Crockford has made a lot of effort to promote this, but it also has deep roots in C, where semicolons are Strictly required, otherwise the program will not be able to run.

JavaScript Standard Style changed my view on this, without semicolon JavaScript is good.

Automatic semicolon insertion is a

feature of JavaScript, which reduces noise and simplifies the program, I have never encountered an error due to the lack of a semicolon, I don't I believe you will encounter it too. For more information about this, see Is the semicolon necessary in JavaScript?

Not everyone agrees, and the famous branches semistandard and happiness strongly restore the semicolon. I find these branches a little regretful because they seem to miss the full meaning of the standard.

I disagree with rule X, can you change it?

No. The focus of the standard is to avoid unnecessary debates about styles. There are many debates on the Internet about tabs and spaces, etc., and these debates will never be resolved. These arguments will only distract and cannot complete the work. Ultimately, you have to “select only something”, and that’s all the philosophy of the standard – it’s a bunch of wise “select only something” perspectives. Hopefully users can see the value of this, rather than defending their own opinions.

Personally, I've become accustomed to coding without a semicolon, maybe it's because I've taken the time to write Ruby, Python, and CoffeeScript, which require less syntax. Whatever the reason, I found the program clearer when there was less content to view.

Mark's excellent program level

Programmers should pay attention to:

  1. Responsibility
  2. Readability
  3. Happiness
  4. Efficiency

It turns out that adopting a style guide like standard can bring benefits in all of these aspects.

Responsibility

To play any role, the program must be executed as you intend and without errors. Styles won't make the program more correct, but linter can catch errors before errors are posted.

Readability

As a professional developer, the readability of the code is the most important thing in addition to providing an effective program. It takes much more effort to read and try to understand a program than writing, so optimize for your future self and others who will inherit your code. Clear and predictable styles make the code easier to read and understand.

Programmer's sense of happiness

What I like most about this aspect is that it focuses on people rather than machines. It ranks third on the list simply because the team’s need for readable, functional code should take precedence over our own happiness, but that doesn’t mean it will come at the expense of happiness.

You want to enjoy life, don't you? If you can get the job done quickly and the work is fun, that's great, isn't it? This part is the purpose of life. Your life is better.

- Matsumoto Yuhiro

Life is short, don’t worry about differences in personal preferences, set a standard and move on. If standard styles prevent disagreements and frictions among team members, you will be happier because of this.

Efficiency

The last point, but not the least.

If you have to weigh any of these points, you should value correct, readable, and making people happy

than

quick code.

The computer is very fast. If the program is efficient enough, then there is no problem. If you notice poor performance, then take the time to find bottlenecks and make the code more efficient.

Humans are very slow. It is more valuable to improve our efficiency. The clarity gained from adopting standard styles makes your code easier to understand and engage in contributions. The time spent on disagreement has also been greatly reduced, which is very popular.

Implement JavaScript Standard Style

You can adopt standards without any tools, just read the rules and note the different rules. Try it for a week and see if you like it. If you don't like it, keep using it!

There is also an npm package for lint your JavaScript code.

<code>npm install standard --global</code>
Copy after login
Running standard will run all JavaScript files in the directory through linter.

In addition, all common editors have text editor plugins, here is how to install linter in Atom.

<code>apm install linter
apm install linter-js-standard</code>
Copy after login

Why I Use a JavaScript Style Guide and Why You Should Too

Personally, I find the automatic lint program when typing is very distracting. If you feel the same way, you might prefer to use these linters after you finish your work. The standard command also has a flag that automatically fixes certain style errors, which may save you time.

<code>standard --fix</code>
Copy after login

Using JavaScript Standard Style

Should you adopt a standard style? Well, it's all up to you.

If you don't have a style guide, then be prepared to deal with conflicts of opinion.

If you have perfected your ideal set of rules and want to enforce it throughout your code base, ESLint may be what you are searching for.

If you'd rather not waste your time on these boring details of syntax, try JavaScript Standard Style and let us know what you think in the comments below.

FAQs about JavaScript Style Guide

Why is it important to use JavaScript style guide?

The JavaScript Style Guide is a set of standards that developers follow when writing JavaScript code. It ensures consistency, readability and maintainability of the code. When multiple developers work on a single project, it is crucial that they all follow the same style guide to avoid confusion and make the code easier to understand and debug. It also helps reduce the possibility of errors and vulnerabilities in the code.

How to style HTML elements using JavaScript?

You can use JavaScript to style HTML elements by accessing the style attribute of the element. For example, if you have an element with id "myElement", you can change its background color to red, like so: document.getElementById("myElement").style.backgroundColor = "red"; This applies the CSS style directly to the element.

What are the common JavaScript style guides commonly used by developers?

Some of the most common JavaScript style guides used by developers include Airbnb's JavaScript style guide, Google's JavaScript style guide, and StandardJS. These guides provide rules for syntax, formatting, and best practices to ensure that the code is clean, consistent, and easy to read.

How to enforce JavaScript style guide in my project?

You can enforce JavaScript style guides in your project using linters like ESLint. linter is a tool that analyzes your code to find potential errors and violations of your style guide. You can configure ESLint to follow the rules of the style guide of your choice, and it alerts you when your code violates these rules.

Can I create my own JavaScript style guide?

Yes, you can create your own JavaScript style guide. However, it is often more efficient to use existing style guides that the community has tested and verified. If you have specific needs that are not covered by existing style guides, you can create your own rules and add them to your linter configuration.

What is the difference between inline styles and external styles in JavaScript?

Inline styles are applied directly to HTML elements using the style attribute, while external styles are defined in separate CSS files and linked to HTML documents. While inline styles are very convenient for small projects or quick fixes, for large projects, external styles are often preferred because they can improve reusability and separation of concerns.

How to use JavaScript to remove styles from HTML elements?

You can use JavaScript to remove styles from HTML elements by setting the style attribute to an empty string. For example, to remove the background color from an element with id 'myElement', you can do the following: document.getElementById("myElement").style.backgroundColor = ""; This will remove the inline style from the element.

What are the benefits of using linter with JavaScript style guide?

Using linter with JavaScript style guide can help you catch errors and inconsistencies before they become problems. It can also help you write cleaner, easier to read code by enforcing best practices and style rules. Additionally, it can save you time by automatically fixing certain types of errors and formatting issues.

How to use JavaScript to apply multiple styles to HTML elements?

You can use JavaScript to apply multiple styles to HTML elements by setting multiple style properties. For example, to set the background color and font size of an element with id 'myElement', you can do the following: var elem = document.getElementById("myElement"); elem.style.backgroundColor = "red"; elem.style.fontSize = "20px"; This applies both styles to the element.

Can I use JavaScript to style pseudo-elements?

No, JavaScript cannot directly style pseudo-elements such as ::before and ::after. These are part of the CSS specification and can only be used to style it. However, you can add or remove classes to elements using JavaScript, and these classes can have pseudo-element-related styles in your CSS.

The above is the detailed content of Why I Use a JavaScript Style Guide and Why You Should Too. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template