JavaScript -- getting started with JS

Keywords: Javascript Programming Attribute Java

1. Introduction to JavaScript

JavaScript is an interpretive programming language for HTML and web. It is also a weak type lightweight script language with function priority. It can interact with HTML front-end pages without precompiling. It supports cross platform operation and can be used in multiple platforms (such as Windows, Linux, Mac, Android, iOS, etc.). At present, JavaScript is widely used in Web front-end HTML to realize page interaction, browser page event response, front-end data validation, visitor browser information verification, cookie creation and modification control, and server-side programming based on Node.js technology.

2. Basic JavaScript syntax

2.1. Three definitions of JavaScript

There are generally three ways to define JS:

① Write in the href attribute of the < a > tag;

② Write in the < script > tag;

③ Write a JS file separately and import it by external connection;

Here is a code example to distinguish the three ways:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta charset="UTF-8">
    <title>Three kinds JS Writing</title>
    <!--The second way to write: write in script Code block-->
    <script type="text/javascript">
        alert("I'm in the block!")
    </script>
    <!--The third way to write: write one alone js Document in src Introduce in.js file-->
    <script type="text/javascript" src="./js/01hello.js"></script>
</head>
<body>
    <!--
        JS There are three ways to write:
        ①Written in the label;
        ②Written in script Inside the label;
        ③Write a single JS file
    -->
<!--The first way to write it is to show the pseudo protocol to the browser. The code after the pseudo protocol is used as JS Code execution-->
<a href="javascript:console.debug('Point you, point you')">Click on me</a>
</body>
</html>

2.2. Identifier of JavaScript

The identifier in JavaScript is the same as that in Java. The identifier is the name used to identify the elements such as class, method and variable in the program.

All identifiers must comply with the following rules:

  • An identifier is a sequence of characters consisting of letters, numbers, underscores (_), and dollar signs ($).
  • Identifiers must begin with a letter, underscore (_), or dollar sign ($), not a number.
  • Identifiers cannot be reserved words and keywords in JavaScript.
  • Identifier cannot be true, false, or null.
  • The identifier can be any length.

Examples of legal identifiers: identifier, user name, user name, $username;

Illegal identifier examples: int, 98.3, Hello World.

JavaScript is strictly case sensitive, so area, area and area are different identifiers. When using identifiers, descriptive identifiers should be used to improve the readability of the program.

2.3. Keywords and reserved words

Keywords include:

break  continue  debugger  do ... while  for  function  if ... else  return  switch

try ... catch var case break case continue default delete do finally in

instanceof new return this throw typeof void with

Reserved words include:

abstract  Boolean  byte  char  class  const   double  enum  export  extends
final float goto implements import int interface long package private
protected public short static super synchronized throws transient volatile

2.4. Dividers and notes

Each JavaScript execution statement is separated by semicolon ";" and semicolon is not necessary in the actual execution process (remove ";" can be executed), but it is strongly recommended to add semicolon in the actual code writing process!

var a = 5;
var b = 6;
var c = a + b;

If there is semicolon separation, it is allowed to write multiple execution statements on the same line:

var a = 5;b = 6;c = a + b;
console.debug(a);  //5
console.debug(b);  //6
console.debug(c);  //11

JavaScript annotations are used to interpret JavaScript code and enhance its readability. JavaScript annotations can also be used to block execution when testing alternative code.

There are three main annotation types in JavaScirpt:

Single line notes, multi line notes, document notes

 

A single line comment begins with / / and any text between / / and the end of the line is ignored (not executed) by JavaScript.

Multiline comments start with / * and end with * / and any text between / * and * / is ignored by JavaScript.

Document comments start with / *, end with * /, and any text between / * * and * / will be ignored by JavaScript.

//Single-Line Comments
var x = 5;      // statement x,Assign 5
var y = x + 2;  // statement y,Assign to it x + 2

/*
 multiline comment
 The following code will change
 Web page
 id = "myH" Title
 And section with id = MYP:
*/
document.getElementById("myH").innerHTML = "My first page";
document.getElementById("myP").innerHTML = "My first paragraph.";

/**
 Documentation Comments
 Generally used to indicate the product document type with the company's signature head
 */

2.5. Blank characters

JavaScript ignores multiple spaces. We can add multiple space interval statement codes in script statements to enhance the readability of the program.

The following two lines are equal:

var person = "Bill";
var person="Bill"; 

It's a good habit to add a space next to an operator (= + - * /):

var x = y + z;

3. JavaScript variables

JavaScript variable is an identification used to store data value, pointing to specific memory address and saving corresponding value or object address value.

First of all, the variable declaration should follow the identifier naming principle, and the JavaScript declaration variables should use the var keyword, such as:

var name;
console.debug(name);  //Print empty characters
console.debug(typeof(name)); //string

When declaring a variable, you can assign a value to the variable, and then change the value of the variable. Note: you cannot change the type of the variable, for example:

var name = "Zhang San";
console.debug(name); //Zhang San
console.debug(typeof(name)); //string
name = true;
console.debug(name); //true
console.debug(typeof(name)); //string

In addition, JavaScript allows direct use without declaring variables in advance, such as:

num = 1234;
console.debug(num); //1234

Note: JavaScript does not need to specify the type of variables to define variables, any type can be declared using the var keyword.

4. JavaScript data type

Data types in JavaScript include: string type, numeric type, boolean type, array type, object type, etc.

① string

A string (or text string) is a string of characters, such as "Bill Gates.".

Strings are surrounded by quotation marks. You can use single quotation marks or double quotation marks:

var carName = "Porsche 911";   // Use double quotes
var carName = 'Porsche 911';   // single quotes 

You can also use quotation marks inside a string, as long as they do not match the quotation marks of the enclosed string:

var answer = "It's alright";             // Single quotes within double quotes
var answer = "He is called 'Bill'";    // Single quotes within double quotes
var answer = 'He is called "Bill"';    // Double quotes in single quotes

② Numerical (number)

JavaScript has only one numeric type. Use no decimal point when writing numerical value.

var x1 = 34.00;     // Decimal point
var x2 = 34;        // Without decimal point

Very large or very small values can be represented by scientific counting.

var num1 = 123e5;      // 12300000
var num2 = 123e-5;     // 0.00123

③ boolean

JavaScript Booleans have only two values: true or false.

var res = true;
console.debug(res); //true
console.debug(typeof(res)); //boolean

④ Array type

JavaScript array is represented by square brackets, and array item elements are separated by commas. The following code declares an array named cars, which contains three elements (car brand):

var arr = ["Porsche", "Volvo", "BMW"];
console.debug(arr.length); //3
console.debug(arr[0]); //Array index from 0 to array length-1 End, value usage arr[Index location];Porsche
console.debug(arr[arr.length-1]); //BMW

⑤ Object type

JavaScript objects are represented by curly braces.

The object property is a name:value key value pair, separated by commas. Declare an object type and use:

//object type
var person = {
   firstName : "Bill",
   lastName  : "Gates",
   age       : 62,
   eyeColor  : "blue"
};
//Object value: use object.Attribute value
console.debug(person.firstName + " is " + person.age + " years old"); //Bill is 62 years old

4.1. typeof operator

Use typeof to determine the type of JavaScript variables:

The typeof operator returns the type of the variable or expression:

The typeof operator can return one of the following primitive types:

  • string
  • number
  • boolean
  • object
  • undefined
var name = "Zhang San";
typeof name; //string
typeof 3.14  // Return "number"
typeof true // Return "boolean"
typeof x    // Return "undefined" (If x No value)
var arr = ["Porsche", "Volvo", "BMW"];
typeof arr; //object

At the same time, when dealing with complex data, the typeof operator can return one of the following two types:

  • function
  • object

The typeof operator returns the object, array or null to the object;

The typeof operator returns a function

typeof null     // Return "object"
typeof function myFunc(){}  // Return "function"

4.2. Undefined/Null / null

①    undefined

In JavaScript, if there is no value for a variable, that is, there is no value assigned to the variable initialization, then its value is undefined. typeof also returns undefined.

var person;
console.debug(person); //Return undefined

②    Null

In JavaScript, the null data type is an object.

var person = null;
console.debug(person); //null
console.debug(typeof person); //object

Difference between undefined and null:

undefined and null values are equal, but the types are not equal;

typeof undefined       // undefined
typeof null             // object
null === undefined    // false
null == undefined     // true

③ Null

A null value means that the value of a string variable is an empty string, which has both value and type.

var str = "";
console.debug(str); //""
console.debug(typeof str); //string

5. JavaScript functions

JavaScript functions are blocks of code designed to perform specific tasks. JavaScript functions are executed when a code calls it.

5.1. JavaScript function syntax

JavaScript functions are defined by function keywords, followed by function names and parentheses ().

Function names can contain letters, numbers, underscores, and dollar symbols (rules are the same as variable names).

Specific examples are as follows:

Function function name ( Parameter args) {
    Method body - execution code
}

Function function: to avoid code execution when the page is loaded, and one definition, multiple use (call).

5.2. Function return value

Return is used in JavaScript function body to return the execution result after the function is called. In a function, the execution result is usually calculated, and the return value is returned to the caller by return. On the function function, there is no need to declare the function return type (the flexibility of JS's weak type).

Example:

function getMsg() {
    var msg = "Return any string";
    return msg;
}
console.debug(getMsg()); //Return any string
console.debug(getMsg); //ƒ getMsg() { var msg = "Return any string"; return msg;}

Function return calls need to use: function name (), while using function name alone will return the whole function body.

5.3. Local variable and global variable

Variables declared in JavaScript functions will become local variables of functions, and local variables can only be accessed inside functions.

Because local variables can only be identified by their functions, variables with the same name can be used in different functions.

Local variables are created at the beginning of the function and are deleted when the function completes.

The global variable is defined outside the function body, independent of the local variable, and can be used globally. However, if the local variable inside the function body has the same name as the global variable, the value of the global variable may be changed after the function is called.

An example is as follows:

/**
* 1.JS The definition of global and local variables in
*/
var str = "global variable";

function showStr() {
   str = "local variable";
   console.debug(str);
}

showStr();  //local variable
console.debug(str); //Local variable, str The overall value goes into showStr()Changed in method

console.debug("================Dividing line==================")

var str2 = "Global variable 2";

function showStr2() {
   var str2 = "Local variable 2";
   console.debug(str2);
}

showStr2();  //Local variable 2
console.debug(str2); //Global variable 2,Defined in showStr2()In function str2 Variable has been executed and destroyed

6. More

JavaScript in this section (1) – JS introduction mainly summarizes the common knowledge in JS elementary knowledge system, omits the description of JS output printing, JS operator and JS process control (this part is relatively simple, and Java language is also a general type), and simple knowledge will not be described one by one. For more complete JavaScript introduction knowledge system, please refer to the w3shop website. For this part of knowledge, please refer to the W3school website:

https://www.w3school.com.cn/js/index.asp

Learning chapter: JS tutorial - JS function part, more self learning summary contents of JavaScript chapters will be summarized and updated in the future.

Posted by TutorMe on Mon, 06 Apr 2020 02:53:25 -0700