Home Web Front-end JS Tutorial JavaScript minimalist introductory tutorial (1): Basics_javascript skills

JavaScript minimalist introductory tutorial (1): Basics_javascript skills

May 16, 2016 pm 04:32 PM
javascript Getting Started Tutorial

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:

Copy code The code is as follows:

// test.js
console.log("Hello JavaScript");

Execute this procedure:

Copy code The code is as follows:

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:

Copy code The code is as follows:

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

Copy code The code is as follows:

'cat'.toUpperCase() === 'CAT'

Statement

The

var statement is used to declare local variables, otherwise the variable is a global variable, and the value of an uninitialized variable is undefined:

Copy code The code is as follows:

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:

Copy code The code is as follows:

{
var v = 123;
}
console.log(v); // ok

if statement

Copy code The code is as follows:

if (expression)
Statement

or

Copy code The code is as follows:

if (expression)
Statement1
else
Statement2

or

Copy code The code is as follows:

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

Copy code The code is as follows:

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:

Copy code The code is as follows:

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:

Copy code The code is as follows:

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:

Copy code The code is as follows:

function isNaN(n) {
Return n !== n;
}

The above switch statement is converted into an if statement:

Copy code The code is as follows:

if (n === 1)
// ...
else if (n === 2)
// ...
else
// ...

while and do-while statements

Copy code The code is as follows:

while (expression)
Statement

If expression is true, statement is executed repeatedly until expression is false.

Copy code The code is as follows:

do
Statement
while (expression);

Similar to a while loop, except that statement is executed first and then the conditional expression is checked.

for statement

Copy code The code is as follows:

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:

Copy code The code is as follows:

for (var i=0; i<5; i) {
console.log(i);
}

Another form of for is used to enumerate all property names of an object:

Copy code The code is as follows:

for (variable in object)
Statement

Example:

Copy code The code is as follows:

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

Copy code The code is as follows:

for (var in obj) {
If (obj.hasOwnProperty(var)) {
               // ...
}
}

return statement

The

return statement is used to let the function return a value. If the function does not explicitly use return, then undefined is returned:

Copy code The code is as follows:

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:

Copy code The code is as follows:

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:

Copy code The code is as follows:

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:

Copy code The code is as follows:

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

Copy code The code is as follows:

var a = 1 && true; // a === true
var b = 1 || false; // b === 1
An idiomatic usage of

||:

Copy code The code is as follows:

name = name || 'unknown'; // Set the default value for name 'unknown'
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

Beginner's Guide: Start from scratch and learn MyBatis step by step Beginner's Guide: Start from scratch and learn MyBatis step by step Feb 19, 2024 am 11:05 AM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

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

See all articles