search
HomeWeb Front-endJS TutorialWhy I Use a JavaScript Style Guide and Why You Should Too

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>
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>

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>

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
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools