Home Web Front-end JS Tutorial JavaScript Advanced Programming (3rd Edition) Study Notes 2 js basic syntax_basic knowledge

JavaScript Advanced Programming (3rd Edition) Study Notes 2 js basic syntax_basic knowledge

May 16, 2016 pm 05:49 PM

This article reviews the basic syntax in the ECMAScript specification. Friends who are good at English can directly read the official document. JavaScript is essentially a C-like language. Friends who are familiar with C language can easily read this article or even skip it. However, it is recommended that you take a look. During the introduction, I may quote some It is a usage that I think is not easy to understand and is relatively popular.

Basic Grammar

1. Identifier: The so-called identifier actually refers to a name that meets certain specifications and can be recognized by the engine. It can be used to represent all nameable constants, variables, function names, function parameters, objects, object properties, etc. The name of the object.

(1) Case sensitive.

(2) Starts with a letter, underscore (_) or dollar sign ($), and other characters can be letters, underscores, dollar signs or numbers. The letters here contain extended ASCII or Unicode characters.

(3) Identifiers cannot be keywords, reserved words, true, false, or null. (Some browsers allow undefined, some don't).

(4) If the object attributes contain spaces or other special characters, they can be enclosed in parentheses as a whole.

2. Keywords: have specific uses in the language itself.

🎜> 3. Reserved words: reserved by the language itself and may be used as keywords in the future.

Reserved words in ES3:

 

abstract boolean byte char class const debugger double enum export extends final float goto implementations import int interface long native package private protected public short static super syn chronized throws transient volatile

Reserved words in non-strict mode in ES5:

 

class const enum export extends import super

ES5 reserved words in strict mode:

 

implements interface let (new in ES5) package private protected public static yield (new in ES5)

4. Strict mode: Strict mode is introduced in ES5. Strict mode can be turned on by using "use strict". Global strict mode can be turned on at the top, or local strict mode can be turned on within the function scope.


Copy code The code is as follows: "use strict"//Enable global strict mode, in In ES3, there will be no impact function fn(){
 "use strict"//Turn on local strict mode
}


5. Note: In ECMAScript, two types are supported Format comments, single-line comments and block-level comments:


Copy code The code is as follows: / / Single-line comments, starting with two slashes // /*
* Multi-line (block-level) comments, starting with a slash / and an asterisk *, ending with an asterisk and a slash, here the middle line The asterisk * is not necessary
*/


Explanation: As JS code becomes more and more complex, comments become more and more important, and document automation becomes more and more important. Currently There are already many open source JS libraries used to automatically generate JS documents similar to Javadoc, such as JSDoc, YUIDoc, etc. At this time, there will also be corresponding format requirements for comments. Interested friends can find relevant information to study.
6. Variables: Variables are essentially the external abstraction of memory space at the language level.

(1) Dynamic type: In ECMAScript, variables are dynamically typed. You can initialize them to a Number type when defining them. Then, you can assign a string value to it:



Copy code The code is as follows: var age = 29;
age = 'twenty-nine '; //Despite this flexibility, I recommend that you don't do this unless you know exactly what you are doing.


(2) var operator: Variables are declared using var. For uninitialized variables, they will default to undefined. You can also use variables directly without declaring them (in my opinion, this is also a feature that has no reason to exist. ), the most important difference between them is that when declared using var, the declared variable is only valid in the current scope, while when var is not used, the variable will be defined in the global scope. You can appreciate the difference through the following example:
Copy the code The code is as follows:

var name = 'linjisong'; //Define global variables and assign values ​​
age = 29; //Use variables directly, which is equivalent to defining global variables and assign values ​​
//sal; //Error
var salary; / /Define global variables, not initialized
//This is just a function declaration, no actual call, so internally defined variables will not take effect
function fn(){
var name = 'oulinhai';//Definition Local variables and assign values ​​
age = 23; //Assign values ​​to global variables
work = 'it'; // Without using var, even variables local to the function will become global variables
}
//Before the function is actually called
console.info(salary); //undefined
console.info(name); // linjisong
console.info(age); // 29
try{
console.info(work);//Since work is not defined in the global environment, an exception will be thrown here
}catch(e){}
fn();//Actual call, Changes to variables in the code will appear
console.info(name); // linjisong, because var is used inside the function, the global name value will not be changed
console.info(age); // 23
console.info(work); // it

(3) Statement promotion: This issue will be discussed again when talking about function declarations and function expressions. Let’s mention it here first. , look at the code:
Copy code The code is as follows:

console.info(name);/ /undefined
console.info(getName);//getName() function
console.info(getName());//undefined
try{
console.info(age);// Exception
}catch(e){
console.info(e);//ReferenceError
}
console.info(getAge);//undefined
try{
console. info(getAge());//Exception
}catch(e){
console.info(e);//TypeError
}
var name = 'linjisong';//Variable declaration , raise
age = 29;//Use global variables directly, without raising
function getName(){//Function declaration, raise
return name;
}
var getAge = function( ){//Declaration of variable getAge, promoted; anonymous function expression to obtain age, not promoted
return age;
}
console.info(name);//linjisong
console.info (getName);//getName() function
console.info(getName());//linjisong
console.info(age);//29
console.info(getAge);// Anonymous function to get age
console.info(getAge());//29

Have you ever inferred the above output yourself? If you have already inferred it, you can skip it. If you still have questions, first take a look at the description of statement promotion below, and then go back and verify the above output results:
A. When the engine is parsing, it will first Parse the function declaration, then parse the variable declaration (the type will not be overwritten during parsing), and finally execute the code;
 B. When parsing the function declaration, the type (function) will be parsed at the same time, but it will not be executed. When parsing the variable declaration, Only variables are parsed, not initialized.
What is involved here is only the global scope. There are also function parameters in the function scope that are also related to declaration promotion. We will discuss it later when we talk about functions.
The above code will first promote the function declaration on line 18 and the variable declaration on lines 16 and 21 to the beginning for parsing, and then execute it. Therefore, lines 1 and 9 output undefined because the variable declaration is promoted but not initialized, so line 11 throws a type exception because the function type cannot be determined; lines 2 and 3 are because the function declaration is promoted and the function type is parsed, so line 11 Line 2 outputs the function, line 3 can call the function, but the return value is not initialized and outputs undefined; line 5 will throw a reference exception because the variable has not been declared.
(4) You can use one statement to define multiple variables, just separate them with commas. For example:
Copy code The code is as follows:

var name='linjisong',
age=29,
work='it';

(5) In the strict mode of ES5, variables named eval or arguments cannot be defined.
7. Statement
(1) Statement: ends with a semicolon ";". If the semicolon is omitted, the parser determines the end of the statement.
I can’t think of any reason why statements in JS can omit semicolons. It is strongly recommended that each statement be clearly ended with a semicolon. Don’t let the parser spend time “guessing” your program. Moreover, More importantly, in many compression tools, guessing is not guaranteed to be 100% correct.
(2) Code block: Start with a left curly brace ({) and end with a right curly brace (}).
Although there is the concept of code block in JS, there is no corresponding block-level scope, which is different from general C-like languages. For control statements (such as if), don't avoid using code blocks just because there is only one statement. This will sow the seeds of mistakes for the people who maintain your program.
Copy code The code is as follows:

for(var i=0; i<10; i )
{
}
console.info(i);//Output 10, i can still be accessed after the code block, indicating that JS has no block-level scope
if(i < 10)
//console.info(i); Without using code blocks, it is easy to make mistakes during maintenance (such as adding a statement)
{
console.info(i);
}

In addition to being used as code blocks, curly braces ({}) also have a very important use in defining object literals, which will be discussed later.
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
1673
14
PHP Tutorial
1277
29
C# Tutorial
1257
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.

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.

Python vs. JavaScript: Use Cases and Applications Compared Python vs. JavaScript: Use Cases and Applications Compared Apr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles