Table of Contents
Responsibility
Readability
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.
The last point, but not the least.
What are the common JavaScript style guides commonly used by developers?
How to enforce JavaScript style guide in my project?
Can I create my own JavaScript style guide?
What is the difference between inline styles and external styles in JavaScript?
How to use JavaScript to remove styles from HTML elements?
What are the benefits of using linter with JavaScript style guide?
How to use JavaScript to apply multiple styles to HTML elements?
Can I use JavaScript to style pseudo-elements?
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

Feb 17, 2025 am 11:45 AM

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.

1

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

1

2

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

1

<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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 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.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 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 and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 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.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 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.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 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: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 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.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles