


JavaScript minimalist introductory tutorial (1): Basics_javascript skills
Reading this article requires programming experience in other languages.
Before you start studying
Most programming languages have good parts and bad parts. This article only covers the good parts of JavaScript because:
1. Only learning good parts can shorten the learning time
2. The code written is more robust
3. The code written is more readable
4. The code written is easier to maintain
Weak typing and strong typing
Generally speaking, the sooner a bug is fixed, the less costly it is. Compilers for strongly typed languages can check for certain errors at compile time. JavaScript is a weakly typed language, and its interpreter cannot check for type errors, but practice shows:
1. The errors that strong typing can avoid are not critical errors
2. Weak typing can bring flexibility, and there is no need to carry the baggage of strong typing
JavaScript related standards
The ECMA-262 standard defines the language ECMAScript. The JavaScript and ActionScript we know well are both based on ECMAScript. Currently, the mainstream uses ECMA-262 fifth edition, and Google's V8 engine is the implementation of this.
Hello JavaScript
JavaScript is a scripting language that requires an interpreter to interpret and execute. You can interpret and execute JavaScript in the browser or directly use node.js, which integrates Google's V8 JavaScript engine. Since node.js is very convenient to use, here I use node.js to interpret and execute JavaScript. Now look at the first JavaScript program:
// test.js
console.log("Hello JavaScript");
Execute this procedure:
node test.js
Grammar
Notes
JavaScript uses the same comment method as C, // is used for single-line comments, and /* */ is used for multi-line comments.
Number type
JavaScript has only one number type, which is a 64-bit floating point number. The numeric type has two special values, NaN and Infinity. NaN means not a number (not a number). Use the function isNaN to check whether it is NaN. The value Infinity means infinity. In the Math object, there are a set of methods for manipulating numbers, for example: the Math.floor method is used to round down.
String
String literals can be wrapped in single or double quotes, using escape characters (not unlike many other languages). Each character in JavaScript is two bytes and uses the Unicode character set. Strings have a length property:
"Hello".length // The value is 5, note not "Hello".length()
Strings cannot be changed (same as Lua). In addition to the length attribute mentioned here, there are also some methods, such as:
'cat'.toUpperCase() === 'CAT'
Statement
Thevar statement is used to declare local variables, otherwise the variable is a global variable, and the value of an uninitialized variable is undefined:
function f() {
var localVar = 123;
globalVar = 456;
var i; // The value of i is undefined
};
f();
console.log(globalVar); // ok
console.log(localVar); // Error, localVar is not defined
A group of statements wrapped by {} is called a block. Unlike other languages, functions in JavaScript will create new scopes but blocks will not, for example:
{
var v = 123;
}
console.log(v); // ok
if statement
if (expression)
Statement
or
if (expression)
Statement1
else
Statement2
or
if (expression1)
Statement1
else if (expression2)
Statement2
else if (expression3)
Statement3
else
Statement4
The if statement determines whether to execute or skip certain statements by judging whether the value of the expression is true or false. In JavaScript the following values are false (all other values are true):
1.false
2.null
3.undefined
4. Empty string
5.0
6.NaN
The statement in if can be a statement or a statement block.
switch statement
switch (n) {
case 1: // if n equals 1
//Execute code block
Break;
Case 2: // If n equals 2
//Execute code block
Break;
Default: // If n is neither 1 nor 2
//Execute code block
Break;
}
The break here is used to exit the loop statement or switch statement. In JavaScript, there are two operators to compare whether two values are equal:
1.== (corresponding to != operator), equal, when the two operand types are different, this operator attempts to convert the operand type before comparison, for example:
var x = 1;
x == 1; // true
x == "1"; // true
2.=== (corresponding to !== operator), completely equal, comparing two operands without performing operand type conversion, for example:
var x = 1;
x === 1; // true
x === "1"; // false
It should be noted that NaN is not equal to any value. If x is NaN, then x !== x (only true for NaN), we can implement the isNaN function like this:
function isNaN(n) {
Return n !== n;
}
The above switch statement is converted into an if statement:
if (n === 1)
// ...
else if (n === 2)
// ...
else
// ...
while and do-while statements
while (expression)
Statement
If expression is true, statement is executed repeatedly until expression is false.
do
Statement
while (expression);
Similar to a while loop, except that statement is executed first and then the conditional expression is checked.
for statement
for (initialize; test; increment)
Statement
First initialize is executed once (commonly used to initialize loop variables), and then the test condition is tested (commonly used to test loop variables). If the test condition is false, the loop is stopped, otherwise statement is executed, and then increment is executed (commonly used to update loops) variable), and then perform the test condition test, and the loop continues. Usage example:
for (var i=0; i<5; i) {
console.log(i);
}
Another form of for is used to enumerate all property names of an object:
for (variable in object)
Statement
Example:
var obj = {
a: 1,
b: 2,
c: 3
};
for (var name in obj)
console.log(name);
It should be noted that we use the hasOwnProperty method to check whether the property name belongs to the object or is found from the prototype chain (prototype will be introduced in the next article):
for (var in obj) {
If (obj.hasOwnProperty(var)) {
// ...
}
}
return statement
Thereturn statement is used to let the function return a value. If the function does not explicitly use return, then undefined is returned:
function f() { }
var v = f(); // v === undefined
?: conditional operator (the only ternary operator in JavaScript)
?: The conditional operator exists in many programming languages. When the first operand is true, the operator returns the value of the second operand, otherwise it returns the value of the third operand. Usage example:
function abs() {
Return x > 0 ? x : -x;
}
typeof operator
The typeof operator is used to obtain the type of a variable, and its return value includes:
1.'number'
2.'string'
3.'boolean'
4.'undefined'
5.'function'
6.'object'
The special typeof null returns 'object'. Example about typeof:
var a = typeof 'hello'; // a === 'string'
var b = typeof null; // b === 'object'
Operator
The operator can be used for addition operations in JavaScript and can also be used for string concatenation:
var message = 'hello' 'world'; // message === 'helloworld'
&& and || operators
&& operator returns the value of the first operand if the first operand is false, otherwise returns the value of the second operand
The || operator returns the value of the first operand if the first operand is true, otherwise it returns the value of the second operand
var a = 1 && true; // a === true
var b = 1 || false; // b === 1
||:
name = name || 'unknown'; // Set the default value for name 'unknown'

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Concise and easy-to-understand MyBatis introductory tutorial: write your first program step by step MyBatis is a popular Java persistence layer framework that simplifies the process of interacting with databases. This tutorial will show you how to use MyBatis to create and perform simple database operations. Step 1: Environment setup First, make sure your Java development environment has been installed. Then, download the latest version of MyBatis and add it to your Java project. You can download it from the official website of MyBatis

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
