Basic overview and syntax for front-end Foundation-javascript

Source: Internet
Author: User
Tags arithmetic operators logical operators map data structure natural logarithm object model rounds script tag square root

    • 1. JavaScript overview

    • 2. JavaScript Introduction method

    • 3. JavaScript Language Specification

    • 4. JavaScript Language Basics

    • 5. JavaScript data type

    • 6. JavaScript operators

    • 7. JavaScript Process Control

    • 8. JavaScript functions
    • 9. JavaScript Lexical analysis
    • 10. JavaScript built-in objects and methods

I. JavaScript Overview 1, ECMAScript and JavaScript relationships

In November 1996, the creator of JavaScript,--netscape, decided to submit JavaScript to the International Organization for Standardization, the ECMA, in the hope that the language would become a global standard. The following year, ECMA released the first edition of Standard No. 262 (ECMA-262), which specifies the standard of the browser scripting language and calls this language ECMAScript, which is version 1.0.

The standard was developed for JavaScript in the first place, but it was not called JavaScript, for two reasons. One is a trademark, and JavaScript itself has been registered as a trademark by Netscape. But to embody the language of the creator is the ECMA, not the Netscape, which helps to ensure the development of the language and neutrality.

Therefore, the relationship between ECMAScript and JavaScript is that the former is the specification of the latter, which is an implementation of the former.

2, the history of ECMAScript
Year Name Describe
1997 ECMAScript 1 First version
1998 ECMAScript 2 Version change
1999 ECMAScript 3

To add a regular expression

Add Try/catch

ECMAScript 4 Not published
2009 ECMAScript 5

Add "strict mode" strict modes

Add JSON support

2011 ECMAScript 5.1 Version change
2015 ECMAScript 6 adding classes and modules
2016 ECMAScript 7

Increase the exponential operator (* *)

Increase Array.prototype.includes

Note: ES6 means ECMAScript 6.

Although ECMAScript is an important standard, it is not the only part of JavaScript, and certainly not the only one that is standardized. In fact, a complete JavaScript implementation is made up of the following 3 different parts:

    • Core (ECMAScript)
    • Document Object Model (DOM) Documents object models (consolidated js,css,html)
    • Browser object models (BOM) Broswer object Model (integrated JS and browser)

Simply put, ECMAScript describes the content of the JavaScript language itself.

JavaScript is a scripting language
JavaScript is a lightweight programming language.

JavaScript is a programmatic code that can be inserted into an HTML page.

When JavaScript is inserted into an HTML page, it can be performed by all modern browsers.

JavaScript is easy to learn.

second, JavaScript introduction method1. Write code in script tag
<script>  //write your JS code here </script>
2. Introduction of additional JS files
<script src= "Myscript.js" ></script>
c. javascript Language Specification1. Comments
This is a single-line comment/* This is
Multi-line Comment */
2, Terminator

The statements in JavaScript are terminated with a semicolon (;).

Iv. JavaScript Language Basics1. Variable Declaration
    1. The variable name of JavaScript can be composed of _, number, letter, $, and cannot begin with a number.
    2. declaring variables using var variable names; The format to declare
var name = "Duoduo"; var age = 18;


Variable names are case-sensitive.

Camel-named rules are recommended.

Reserved words cannot be used as variable names.


ES6 has a new let command for declaring variables. The usage is similar to Var, but the declared variable is valid only within the block of code where the Let command resides. For example, a For loop counter is good for using the Let command.

for (let i=0;i<arr.length;i++) {...}

ES6 New Const is used to declare constants. Once declared, its value cannot be changed.

Const PI = 3.1415; Pi//3.1415PI = 3//TypeError: "PI" is read-only

Add again:

reserved word list

V. JavaScript data types

1. JavaScript has a dynamic type

var x;  At this point x is Undefinedvar x = 1;  At this point x is the number var x = "Duoduo"  
2. Value (number)

JavaScript does not differentiate between integral and floating-point types, there is only one numeric type.

var a = 12.34;var b = 20;var c = 123e5;  12300000var d = 123e-5;  0.00123

There is also a Nan, which indicates that it is not a number.

Common methods:

parseInt ("123") // returns 123
parseInt ("ABC") // returns NaN, the NaN attribute is a special value representing a non-numeric value. This attribute is used to indicate that a value is not a number.
parseFloat ("123.456") // returns 123.456
var a = "Hello"
var b = "world;
var c = a + b;
console.log (c); // get Helloworld
3. Strings (String)
var a = "Hello" var b = "World;var c = a + B; Console.log (c);  Get HelloWorld

Common methods:

Method Description
. length return length
. Trim () Remove whitespace
. Trimleft () Remove the left margin
. TrimRight () Remove the blank on the right
. CharAt (N) Returns the nth character
. concat (value, ...) Stitching
. indexOf (substring, start) Sub-sequence position
. substring (from, to) Get sub-sequences by index
. Slice (start, end) Slice
. toLowerCase () Lowercase
. toUpperCase () Capital
. Split (delimiter, limit) Segmentation

Splicing strings generally use "+"

string.slice (start, stop) and string.substring (start, stop):

Similarities between the two:
If start equals end, return an empty string
If the stop parameter is omitted, it is taken to the end of the string
If a parameter exceeds the length of the string, the parameter is replaced with the length of the string

substirng () features:
If start> stop, start and stop will be swapped
If the argument is negative or not a number, it will be replaced by 0

silce () features:
If start> stop will not swap the two
If start is less than 0, the abs (start) character from the end of the string (including the character at the position)
If stop is less than 0, the cut ends at the abs (stop) character from the end of the string 
the difference between slice and substring


A template string was introduced in ES6. The template string, which is an enhanced version of the string, is identified with an inverse quotation mark ('). It can be used as a normal string, or it can be used to define a multiline string, or to embed a variable in a string.

// ordinary string
`This is a normal string! `
// multi-line text
`This is multi-line
// embed variable in string
var name = "duoduo", time = "today";
`Hello $ {name}, how are you $ {time}?`


If you need to use anti-quotes in the template string, precede it with a backslash to escape.

Jshint Enable ES6 Syntax support:/* jshint Esversion:6 */

4, Boolean value (Boolean)

The difference between python,true and false is lowercase.

var a = True;var B = false;

"" (empty string), 0, null, undefined, Nan are all false.

5, null and undefined
    • Null indicates that the value is empty and is generally used when a variable needs to be specified or emptied, such as name=null;
    • Undefined indicates that when a variable is declared but not initialized, the default value of the variable is undefined. There is also the undefined that is returned when the function has no definite return value.

Null means that the value of the variable is empty, and undefined means that only the variable is declared, but it has not been assigned a value.

6. Objects (object)

All things in JavaScript are objects: strings, numbers, arrays, functions ... In addition, JavaScript allows custom objects to be customized.

JavaScript provides multiple built-in objects, such as String, Date, Array, and so on.

Objects are just special data types with properties and methods.

7. Arrays

The purpose of an array object is to use a separate variable name to store a series of values. Similar to the list in Python.

var a = [123, "ABC"];console.log (A[1]);  Output "ABC"

Common methods:

Method Description
. length The size of the array
. push (Ele) Trailing append Element
. Pop () Gets the trailing element
. Unshift (Ele) Head Insert Element
. Shift () Removing elements from the head
. Slice (start, end) Slice
. Reverse () Reverse
. Join (SEQ) Concatenate array elements into a string
. concat (Val, ...) Connection array
. Sort () Sort

Note about sort ():

If the method is called without parameters, the elements in the array are sorted alphabetically, more precisely, by the order in which the characters are encoded. To do this, you should first convert the elements of the array to a string, if necessary, for comparison.

If you want to sort by other criteria, you need to provide a comparison function that compares two values and returns a number that describes the relative order of the two values. The comparison function should have two parameters A and B with the following return values:

If a is less than B, a value that is less than 0 is returned if a should appear before B in the sorted array.
If a equals B, 0 is returned.
If a is greater than B, a value greater than 0 is returned.


function Sortnumber (A, b) {return A-b}var arr1 = [One, A, a, a, a,    44]arr1.sort (Sortnumber)

For iterating over the elements in an array, you can use the following method:

var a = [Ten, A, 40];for (Var i=0;i<a.length;i++) {  console.log (i);}


ES6 introduces a new primitive data type (Symbol) that represents a unique value. It is the 7th data type of the JavaScript language.

8. Type Inquiry
typeof "ABC"  //"string" typeof null  //"Object" typeof true  //"Boolean" typeof 123//"number"

typeof is a unary operator (like ++,--,! ,-the unary operator), is not a function, nor is it a statement.

Calling the TypeOf operator on a variable or value returns one of the following values:

    • Undefined-If the variable is of type undefined
    • Boolean-If the variable is of type Boolean
    • Number-If the variable is of type number
    • String-If the variable is of type string
    • Object-If the variable is a reference type or a Null type
VI, operator 1, arithmetic operators
+ - * / % ++ --
2. Comparison Operators
> >= < <= = = = = = = =!==


1 = = "1"  //true1 = = = "1"  //False
3. Logical Operators
&& | | !
4. Assignment Operators
= += -= *= /=
Seven, Process Control1, If-else
var a = 10;if (a > 5) {  Console.log ("Yes");} else {  Console.log ("No");}
2, If-else If-else
var a = 10;if (a > 5) {  Console.log ("a > 5");} else if (a < 5) {  Console.log ("A < 5");} else {  Console.log ("a = 5");}
3. Switch
var day = new Date (). GetDay (), switch (day) {case  0:  console.log ("Sunday");  break;  Case 1:  console.log ("Monday");  Break;default:  console.log ("...")}

The case clause in switch usually adds a break statement, or the program continues to execute the statements in the subsequent case.

4. For
for (Var i=0;i<10;i++) {  console.log (i);}
5. While
var i = 0;while (i <) {  console.log (i);  i++;}
6, ternary operation
var a = 1;var b = 2;var c = a > B? A:b
Viii. function 1, function definition

The functions in JavaScript are very similar to those in Python, but the way they are defined is somewhat different.

// ordinary function definition
function f1 () {
   console.log ("Hello world!");

// function with parameters
function f2 (a, b) {
   console.log (arguments); // built-in arguments object
   console.log (arguments.length);
   console.log (a, b);

// function with return value
function sum (a, b) {
   return a + b;
sum (1, 2); // call function

// anonymous function
var sum = function (a, b) {
   return a + b;
sum (1, 2);

// execute the function immediately
(function (a, b) {
   return a + b;
}) (1, 2);


ES6 allows you to define functions using the arrow (= =).

var f = v = v;//equals var f = function (V) {  return v;}

If the arrow functions do not require arguments or require multiple arguments, use parentheses to represent the parameter part:

var f = () = 5;//equals var f = function () {return 5};var sum = (NUM1, num2) = = Num1 + num2;//equals var sum = function (nu M1, num2) {  return num1 + num2;}
2. The arguments parameter in the function
function Add (A, b) {  console.log (a+b);  Console.log (Arguments.length)}add (ON)




A function can only return a value, and if you want to return more than one value, you can only return it in an array or object.

3. Global variables and local variables for functions

Local Variables :

A variable declared inside a JavaScript function (using VAR) is a local variable, so it can only be accessed inside the function (the scope of the variable is inside the function). As soon as the function is complete, the local variable is deleted.

Global variables:

Variables declared outside of a function are global variables, and all scripts and functions on a Web page can access it.

Variable life cycle:

The lifetime of JavaScript variables begins at the time they are declared.

Local variables are deleted after the function is run.

Global variables are deleted after the page is closed.

4. Scope

First, find the variable inside the function, find the outer function to find it, and find the outermost layer gradually.

A few examples:


var city = "Beijing", function f () {  var city = "Shanghai";  function inner () {    var city = "ShenZhen";    Console.log (city);  }  Inner ();} f ();  What is the output?


var city = "Beijing", function Bar () {  console.log (city);} function f () {  var city = "Shanghai";  return Bar;} var ret = f (); ret ();  What is the print result?

3. Closures

var city = "Beijing", function f () {    var city = "Shanghai";    function inner () {        console.log (city);    }    return inner;} var ret = f (); ret ();
Ix. Lexical analysis (try to understand)

In JavaScript, the lexical analysis is performed at the moment the function is called.

The process of lexical analysis:

When a function is called, an active object is formed first: Avtive object (AO), and analyzes the following 3 aspects:

1: function parameter, if any, assigns this parameter to AO, and the value is undefined. If not, no action is made.
2: Function local variable, if there is a value with the same name on the AO, no action is done. If not, the variable is assigned to AO, and the value is undefined.
3: function declaration, if there is on the AO, the object on the AO will be overwritten. If not, no action is made.

Inside the function, either use a parameter or use a local variable to find it on the AO.

See two examples:

var = 18;function foo () {  console.log (age);  var age =;  Console.log (age);} Foo ();  Q: What is the result of executing foo ()?

The second question:

var = 18;function foo () {  console.log (age);  var age =;  Console.log (age);  Function age () {    console.log ("hehe");  }  Console.log (age);} Foo ();  What is the result after execution?
Lexical analysis process:
1. Analyze the parameters. There is a parameter to form an AO.age = undefine;
2. Analyze the variable declaration. There is a var age, and it is found that there is already an AO.age on the AO, so no processing is done.
3. Analyze the function declaration. If there is a function age () {...} declaration, the original age will be overwritten with AO.age = function () {...};

In the end, the attribute on the AO has only one age, and the value is a function declaration

Implementation process:
Note: all values are searched from the AO object during execution

1. When the first console.log (age) is executed, AO.age at this time is a function, so the first output is a function
2. This sentence var age = 22; is the value assigned to the attribute of AO.age, at this time AO.age = 22, so in the second output is 2
3.Similarly, the third output is still 22, because there is no statement that changes the age value in the middle. 
Answer resolutionX. Built-in objects and methods

All things in JavaScript are objects: strings, numbers, arrays, dates, and so on. In JavaScript, objects are data that owns properties and methods.

We have learned about the basic data types, the number object in JavaScript, the string object, the array object, and so on.

Note the difference between var S1 = "abc" and var s2 = new String ("abc"): TypeOf S1--string and typeof S2--Object

Custom Objects

JavaScript objects (object) are essentially collections of key-value pairs (hash structures), but only strings can be used as keys.

var a = {' name ': ' Duoduo ', ' Age ': 18};console.log (; Console.log (a["age"]);

Iterate through the contents of the object:

var a = {' name ': ' Duoduo ', ' Age ': 18};for (var i in a) {  console.log (i, A[i]);}

To create an object:

var person=new Object ();  Create a Person object "Duoduo";  The Name property of the Person object person.age=18;  The age property of the person object


The map data structure is provided in the ES6. It is similar to an object and a collection of key-value pairs, but the scope of the key is not limited to strings, and various types of values (including objects) can be used as keys.

That is, the object structure provides a "string-value" correspondence, the map structure provides "value-value" correspondence, is a more perfect hash structure implementation.

var m = new Map () var o = {p: "Hello World"}m.set (o, "content"}m.get (o)  //"Content" M.has (o)  //Truem.delete (o)//Truem.has (O)//False


// parent class constructor
var Car = function (loc) {
   this.loc = loc;

// parent method
Car.prototype.move = function () {
   this.loc ++;

// subclass constructor
var Van = function (loc) { (this, loc);

// inherit the method of the parent class
Van.prototype = Object.create (Car.prototype);
// fix constructor
Van.prototype.constructor = Van;
// extension method
Van.prototype.grab = function () {
   / * ... * /
JavaScript Object-oriented inheritance2. Date Object

Create a Date Object

// Method 1: Do not specify parameters
var d1 = new Date ();
console.log (d1.toLocaleString ());
// Method 2: The parameter is a date string
var d2 = new Date ("2004/3/20 11:12");
console.log (d2.toLocaleString ());
var d3 = new Date ("04/03/20 11:12");
console.log (d3.toLocaleString ());
// Method 3: The parameters are milliseconds
var d3 = new Date (5000);
console.log (d3.toLocaleString ());
console.log (d3.toUTCString ());

// Method 4: The parameters are year, month, day, hour, minute, second, and millisecond.
var d4 = new Date (2004,2,20,11,12,0,300);
console.log (d4.toLocaleString ()); // milliseconds are not displayed directly

Method of the Date object:

var d = new Date ();
// getDate () get date
// getDay () Get weekday
// getMonth () Get the month (0-11)
// getFullYear () get full year
// getYear () get year
// getHours () get hours
// getMinutes () Get minutes
// getSeconds () get seconds
// getMilliseconds () Get milliseconds
// getTime () returns the accumulated milliseconds (from 1970/1/1 midnight) 

Detailed Date object method: Point Me

3. JSON object
var str1 = ‘{" name ":" duoduo "," age ": 18}’;
var obj1 = {"name": "duoduo", "age": 18};
// JSON string into object
var obj = JSON.parse (str1);
// Object is converted to JSON string
var str = JSON.stringify (obj1);
4. RegExp Object
// RegExp object

// Create regular object mode 1
// parameter 1 regular expression (no spaces)
// Parameter 2 Match mode: g (global match; find all matches instead of stopping after the first match) and i (ignore case)

// The user name can only be English letters, numbers, and _, and the first letter must be English letters. The length must be at least 6 digits and the longest cannot exceed 12 digits.

// Create RegExp object (do not add spaces after the comma)
var reg1 = new RegExp ("^ [a-zA-Z] [a-zA-Z0-9 _] {5,11} $");

// match the response string
var s1 = "bc123";

// The test method of the RegExp object tests whether a string conforms to the corresponding regular rule, and the return value is true or false.
reg1.test (s1); // true

// creation method 2
// / Fill in the regular expression / matching pattern (do not add spaces after the comma)
var reg2 = / ^ [a-zA-Z] [a-zA-Z0-9 _] {5,11} $ /;

reg2.test (s1); // true

// 4 methods of String object and regular combination
var s2 = "hello world";

s2.match (/ o / g); // ["o", "o"] find regular content in the string (/ h / g); // 0 find the content position in the string that matches the regular expression
s2.split (/ o / g); // ["hell", "w", "rld"] splits a string according to a regular expression
s2.replace (/ o / g, "s"); // "hells wsrld" replaces the string according to the regular

// About matching patterns: simple examples of g and i
var s1 = "name: duoduo age: 18";

s1.replace (/ a /, "hahaha"); // "nhahaha me: duoduo age: 18"
s1.replace (/ a / g, "hahaha"); // "nhahaha me: duoduo hahaha ge: 18" global match
s1.replace (/ a / gi, "hahaha"); // "nhahaha me: duoduo hahaha ge: 18" is not case sensitive

// Note 1:
// If regExpObject has a global flag g, the test () function does not search from the beginning of the string, but starts from the index specified by the property regExpObject.lastIndex.
// The attribute value defaults to 0, so the first time is still looking from the beginning of the string.
// When a match is found, the test () function will change the value of regExpObject.lastIndex to the next index position of the last character of this match in the string.
// When the test () function is executed again, it will search from this index position to find the next match.
// Therefore, after we perform a match using the test () function, if we want to use the test () function again to find from scratch, we need to manually reset the value of regExpObject.lastIndex to 0.
// If the test () function can no longer find matching text, the function will automatically reset the regExpObject.lastIndex property to 0.

var reg3 = / foo / g;
// now regex.lastIndex = 0
reg3.test (‘foo’); // returns true
// now regex.lastIndex = 3
reg3.test (‘xxxfoo’); // still returns true
// So when we use the test () method to check whether a string exactly matches, we must add ^ and $ symbols.

// Note 2 (speak out you may not believe the series):
// When we call the RegExpObj.test () method without parameters, it is equivalent to executing RegExpObj.test ("undefined"), and /undefined/.test () returns true by default.
var reg4 = / ^ undefined $ /;
reg4.test (); // returns true
reg4.test (undefined); // returns true
reg4.test ("undefined"); // returns true 
RegExp Related

Extended Reading

5. Math Object
abs (x) returns the absolute value of a number.
exp (x) returns the exponent of e.
floor (x) rounds down the logarithm.
log (x) returns the natural logarithm of a number (base e).
max (x, y) returns the highest value of x and y.
min (x, y) returns the lowest value of x and y.
pow (x, y) returns x to the power of y.
random () returns a random number between 0 and 1.
round (x) rounds the number to the nearest whole number.
sin (x) returns the sine of a number.
sqrt (x) returns the square root of a number.
tan (x) returns the tangent of the angle. 

Basic overview and syntax for front-end Foundation-javascript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.