JavaScript runs inside the browser as an interpreted language, usually embedded in an HTML document. It is responsible for dynamic page behavior, user interaction, and moving data between the front end and back end. The language itself is standardized by ECMAScript, while browser-specific capabilities come from two object models: BOM (Browser Object Model), which exposes methods for controlling the browser, and DOM (Document Object Model), which exposes methods for manipulating the document.
Putting JavaScript into a page
There are three common ways to connect JS to HTML.
An event handler can be attached directly to an element. Events are user actions such as clicks or double-clicks, or element states such as focus. The element listens for the event and runs a handler when it occurs. For example, onclick responds to a click:
<!--Click the button and print to the console-->
<button onclick="console.log('Hello World');">点击</button>
JavaScript can also be written inside a <script> element:
<script type="text/javascript">
alert("网页警告框");
</script>
A script element may appear anywhere in the document and may appear more than once. Its contents execute as soon as the browser reaches it, so placement affects when the code runs and what it can access. The third option is an external file:
<script src="index.js"></script>
With src, the same tag cannot also contain inline JavaScript; it either loads an external file or holds code, not both.
Syntax, variables, and constants
JavaScript programs are built from statements composed of keywords, variables, constants, operators, and methods. Semicolons can mark the end of a statement but are optional. The language is case-sensitive. Single-line comments start with //; multi-line comments use /* */.
Variables hold values that can change while the program runs. They are declared with var:
var a; // variable declaration
a = 100; // variable assignment
var b = 200; // declare and assign
var m,n,k; // declare multiple variables
var j = 10,c = 20; // declare and assign multiple variables
Variable, constant, function, and method names are chosen by the developer. They may contain digits, letters, underscores, and $, but cannot begin with a digit. They must not collide with reserved words such as var, const, function, if, else, for, while, do, break, case, switch, return, or class. Names are case-sensitive and should describe their purpose; multi-word names use lower camel case, for example userName.
There are a few var behaviors to remember. If a variable is used without var and has never been assigned, accessing it throws an error. A variable declared with var but not assigned starts as undefined. If var is omitted but a value is assigned, the variable can be used and becomes global.
Constants are declared with const and must receive a value at declaration:
const PI = 3.14;
A constant cannot be changed after definition; attempting to do so causes an error. Constant names follow the same rules as variables and are conventionally written in all caps to distinguish them.
Data types
The primitive types covered here are number, string, boolean, undefined, and null. Objects and functions are reference types.
Numbers include integers and decimals. Integers can be written in decimal, octal with a leading 0, or hexadecimal with 0x. Regardless of the notation used in the source, console output is decimal:
var a = 100;
var b = 021; // result is decimal 17
var c = 0x35;// result is decimal 53
Decimal fractions can be written with a decimal point, such as var m = 1.2345;. Scientific notation uses e to represent a power of ten: 1.5e3 means 1.5 * 10^3.
Strings are sequences of one or more characters and can be written with double or single quotes. Each character has a Unicode code point:
var s = "100";
var s1 = "张三";
Booleans have only two values, true and false, and can convert to numbers: true becomes 1 and false becomes 0.
var isSave = true;
var isChecked = false;
undefined is the value returned for a declared variable that has not received a value:
var a;
console.log(a);//undefined
null is an empty type used intentionally, often to release an object reference and indicate that the reference is empty. Unlike Python, where an unassigned variable is None, JavaScript distinguishes undefined from null; null is an explicit value.
Type conversion
When values of different types participate in an operation, JavaScript may convert them. Explicit conversion can be done with toString():
var a = 100;
a = a.toString(); //"100"
var b = true;
b = b.toString(); //"true"
Number(param) attempts to convert a value to a number. It returns a number on success and NaN (Not a Number) on failure. If any non-number character is present, the conversion fails and returns NaN.
Number("abc")
typeof NaN
Number(undefined)
Number(null)
parseInt(param) parses an integer from data. Non-string arguments are first converted to strings, then characters are read from left to right until conversion fails. parseFloat(param) extracts a number that may include an integer and decimal part.
Implicit conversion follows two main rules. When + is used with a string and another type, the operation becomes string concatenation; the other value is converted to a string and the result is a string. In other cases, operands are converted to numbers for arithmetic.
Operators
Assignment uses =. Arithmetic operators are +, -, *, /, and % for addition, subtraction, multiplication, division, and remainder. Compound operators include +=, -=, *=, /=, and %=. The increment and decrement operators, ++ and --, add or subtract 1 from a variable. When used alone with a variable, prefix and postfix forms behave the same. When combined with another operation, the prefix form changes the variable first and then uses the new value; the postfix form uses the current value first and then changes the variable.
Relational operators are >, <, >=, <=, ==, !=, ===, and !==. They always produce a boolean. String-to-string comparison checks Unicode values character by character and stops as soon as a difference is found. Other comparisons convert operands to numbers; if an operand cannot be converted, it becomes NaN, and the comparison is false. A special case: null compared with other types for equality does not convert to a number. null and undefined are equal with ==, but not strictly equal with ===.
Equality with == ignores data type and compares values after automatic conversion. Strict equality with === does not convert types; both type and value must match. Logical operators are && (and), || (or), and ! (not). The conditional operator has the form expression1 ? expression2 : expression3;—if the first expression is true, it evaluates the second; otherwise it evaluates the third.
Control flow
Statements normally run from top to bottom. Branching changes that order. An if block runs its body when the condition is truthy. In JavaScript, every value except the false values is truthy. The false values are 0, 0.0, "", undefined, NaN, and null. If the braces are omitted, an if controls only the next line of code. if-else chooses between two paths, and a chain of else if handles multiple conditions.

A switch statement matches a value against case labels using strict equality. break ends the match and prevents fall-through; when omitted, execution continues through the following cases until a break or the end is reached. default handles the situation where no case matches and is usually placed last. Multiple cases can share one block.

Loops repeat code while a condition holds. while checks the condition before each iteration. do-while runs the body once before checking, so it always executes at least once. for combines initialization, condition, and update. break exits a loop immediately; continue skips the rest of the current iteration and starts the next. Loops can be nested.



Functions
Functions package code that is meant to be executed together. A named function is declared with function, a name, a parameter list, and a body; calling the function uses its name and arguments:
//function declaration
function 函数名(参数列表){
函数体
return 返回值;
}
//function call
函数名(参数列表);
Function names follow variable naming rules and should describe what the function does. Ordinary functions conventionally start with a lowercase letter, while constructors start with an uppercase letter to distinguish them from classes.



An anonymous function omits the name and is generally used once. It can be invoked immediately:
(function (形参){
})(实参);
or stored in a variable and called later:
var fn = function (){};
fn(); //function call

Scope in JavaScript is divided into global scope and function scope; braces in a function define the boundary. A variable declared with var outside any function, or a function declared outside, is global and can be accessed anywhere. Any variable created by assigning a value without var is also global. A variable declared with var inside a function is local and can only be used in that scope; functions declared inside a function are local too. When code inside a local scope looks up a variable or function, it checks the current scope first, then moves outward through enclosing scopes until it reaches global scope.

Arrays
Arrays store multiple values. Each value receives an index starting at 0. Elements can be of any type, and the length can change dynamically. Read or modify an element with arr[index].
var arr = [];
The length property reports the array length and can be read or written. Common methods include:
push(data)adds one or more elements to the end and returns the new length.pop()removes the last element and returns it.unshift(data)adds one or more elements to the beginning and returns the new length.shift()removes the first element and returns it.splice(index,num)adds or removes items and returns the removed items.toString()converts the array to a string.join(param)converts the array to a string using an optional separator; the default separator is a comma.reverse()reverses the array in place and returns the rearranged array.sort()sorts elements in place. By default it sorts by Unicode code point in ascending order. It can take a custom comparison function.
//custom ascending order
function sortASC(a,b){
return a-b;
}
//custom descending order
function sortDESC(a,b){
return b-a;
}
//If the return value is > 0, swap the element values; b-a means descending order
The comparison function receives two elements. If a-b is greater than 0, the elements are swapped, which produces ascending order.
Strings
Strings are created with quotes:
var str = "100";
A string stores characters in an array-like structure with indexes starting at 0. The length property returns the number of characters.
toUpperCase() converts letters to uppercase and toLowerCase() converts them to lowercase; both return a new string and leave the original unchanged. charAt(index) returns the character at a given index, and charCodeAt(index) returns its character code. The index defaults to 0 if omitted.
indexOf(str,fromIndex) searches from the beginning and returns the index of the first match, or -1 if the string is not found. fromIndex is optional and defaults to 0.
substring(startIndex,endIndex) extracts from startIndex up to, but not including, endIndex. If endIndex is omitted, extraction continues to the end. substr(startIndex,len) extracts a substring beginning at an index for a given length.
split(param) divides a string by a separator and returns an array. The separator must be a character or string that exists in the original; if it does not, the split produces no separation but still returns an array.
Math
The Math object provides mathematical operations. It has properties such as Math.PI for pi and Math.E for the base of natural logarithms. Methods include Math.random() for a random number between 0 and 1, Math.ceil(x) for rounding up while ignoring the decimal part, Math.floor(x) for rounding down and keeping the integer part, and Math.round(x) for rounding to the nearest integer.
Dates
Date objects can be created from date strings:
var date2 = new Date("2011/11/11");
var date3 = new Date("2011/11/11 11:11:11");
getTime() accesses the millisecond value for the current time. Time components are available through getFullYear() for the four-digit year, getMonth() for the month from 0 to 11, getDate() for the day of the month, getHours(), getMinutes(), and getSeconds(). Subtracting one date object from another returns the difference in milliseconds.