1. Basic format
Indentation
It is recommended to have 4 spaces per level. You can set tab = 4 spaces for the editor , automatic conversion
Semicolon
Do not omit the semicolon to prevent ASI (automatic semicolon insertion) errors
Line width
Each line of code should not exceed 80 characters. If it is too long, you should use the operator to manually break the line
Line break
The operator is at the end of the previous line. And the next line is indented 2 levels. If it is an assignment statement, it should also be aligned with the part after the equal sign
Empty line
Function Declaration and Function declarations, variable declarations, function declarations, and logic blocks within functions should all be separated by blank lines
The author Nicholas also recommends leaving a blank line at the top of the Flow control block, but The example given is not very clear
Naming
Variable name/Function name: Camel (camel case) rule, first The first letter of a word is lowercase, the first letter of subsequent words is uppercase, and the rest is lowercase
ConstantName:C language formula, all capitals, underscore word segmentation
Constructor: Pascal rule, all the first letters of words are capitalized, and the rest are lowercase
##Literal
String : wrapped in double quotes, use the [+] operator for line breaks, do not use the \ escape character
- Value: Do not omit the part before and after the decimal point, do not use octal form
Null: only treat null as Object Placeholder, do not use it to detect formal parameters or uninitialized variables
- Undefined: All
objects should be initialized to null to Distinguish between undefined and uninitialized
- Object literal/array literal: Do not declare objects and arrays in constructor mode
Notes
P.S. There is a very classic explanation in the book:Appropriately written comments help tell the story of code,allowing other developers to drop into a part of the story without needing to hear the beginning.
Single-line comments
- End of line: use 1 Level indentation separates code, and there must be a space after //
- is on one line: used to comment below, and must maintain the same indentation as the commented code
- Head of line: used to comment multi-line code
Multi-line comments
Used to wrap large comments , recommendEclipse style, such as
/* * comment line1 * comment line2 */
Note:
- Leave a blank line above the multi-line comment
- *Leave a space after the asterisk
- Multi-line comments must be at least three lines (because there are no comments after the first and last lines)
Where to add comments
- Non-self-explanatory code
- Intentional , but it looks like something is wrong
- Browser hack
Documentation comments
Comments should be added to each function, including function description, parameters, return values, errors thrown, etc., such as the recommended Eclipse style:/** * 添加指定元素到默认数组 * * @method add * @param {Number} 将要添加的元素 * @return {Boolean} 添加成功/失败 * @throw {TypeError} 参数类型不匹配 */ function add(item){ if(typeof item === "number"){ arr.push(item) } else{ throw new TypeError(); } }3. Statements and expressions
Brace alignment
Recommended line ending style, not recommended sub-line styleBlock statement space
after if There is a space before and after the parentheses, for example:if (expr) { code }
- Indentation: case and switch alignment,
breakIndent 1 level
- case penetration: Use a blank line or comment //falls through to indicate that case penetration is intentional
- default: Keep default or use the comment //no default to indicate that there is no default
with statement
No needAll variables should be declared at the top of the function body, including variables used in the initialization part of the for loop, to avoid bugs caused by hosting (promotion) (global variables may be blocked)
for-in loop
Do not use it to traverse arrays. When using it, remember to add hasOwnProperty filtering. If you deliberately traverse prototype properties, you should use comments to explain
IV. Variables, functions, operators
Variable declaration
Function body = variable declaration + function declaration + logical statement. Separate each part with a blank line
Function declaration
Declare first and then use it. Never put the function declaration in the if branch, because browsers understand it differently. Moreover, ES does not provide standard
function calls.
There are no spaces before and after the parentheses to avoid confusion with block statements
## Anonymous functionImmediate execution
Wrap the immediately executed anonymous function in parentheses to avoid confusion with the anonymous function declarationStrict mode
Don’t enable strict mode in the global scope, only enable it inside the function. If you enable it for multiple functions, you can use anonymous functions to immediately execute the scope that limits the strict mode.Judgment is equal to
Only use === and !==eval
Do not use eval() and new Function(), use anonymous function to optimize setTimeout() And setInterval()Basic packaging type
Do not use new Boolean(), new String(), new Number()
The above is the detailed content of Detailed introduction to JavaScript coding style guide. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools
