JavaScript programming learning notes -- the third chapter introduces the basic

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

2013-3-16 | Publisher:

My notes:

1.ECMAScript (German all variables, functions and operators) are case sensitive,

2 identifier must be underlined letters, or a dollar sign ($) as the first character,

3 rules: ECMAScript identifier by a camel case format:

Lowercase for the first word, with each word capitalized; example: doSomethingImportant ;

4 omit the VaR operator in the function, you can create a global variable. But this is not recommended, because the definition of global variables are difficult to maintain in the local scope, but if deliberately ignored the VaR operator, also because the corresponding variable does not immediately have caused unnecessary confusion,

5 you can use a statement to define multiple variables, only separated by commas.:

   var message="hi",



The 6 data types:

6.0: -----------------------------------------------------------------------------------

6.1: The use of undefined type ---------------------------------------------------------------

6.2: Null type --------------------------------------------------------------------------

6.3: Boolean type ----------------------------------------------------------------------

6.4: Number type ------------------------------------------------------------------------

6.5: Stringr type ------------------------------------------------------------------------

6.6: Object type ------------------------------------------------------------------------

7. Operator

7.1 unary operator: ++  --

7.2 Bitwise operators: according to non (~), and bitwise (&), safety or (|), bitwise XOR (^), shift left(<<),

A sign bit shift (> >), no sign bit shift right(>>>) 

7.3 The Boolean operators: logical not (!) , logic and (& &), logic or(||)

7.4 Multiplicative operator: multiplication, division, modulo (remainder%)


The result is NaN,

The results of Infinity%Infinity NaN,

Finite infinite  %; the result is the dividend (the finite number),

7.5 additive operators: addition, subtraction,




The relational operators: less than 7.6 (<(>), greater than, less than or equal to (<); =), greater than or equal to(>=),

Equal, not equal to (= =) ((= = =! =), etc.), not congruent(!==),

7.7 the conditional operator:

For example: var max=(num1>num2)? num1 : num2 ;

num1>Num2 (relationship is returning true), then max=num1; otherwise, max=num2,

The 7.8 assignment operator:

= , *= , /= , %= , += , -= , <<= , >>= , >>>= ;

7.9 A comma expression:

var num1=1, num2=2, num3=3;

var num=(1,4,8,4,0);

//The value of num is 0,

The 8 basic statements:

The 8.1 if statement

The 8.2 DO-WHILE statement

The 8.3 while statement

The 8.4 for statement

The 8.5 for-in statement

The for-in statement is a precise iterative statement, can be used for enumeration object properties,

[Grammar]: for(property in expression) statement ;

[Example]: use the for-in loop to display all properties of the window object in BOM:

for (var propName in window){


The 8.6 label statement

8.7 break and continue statements,

The 8.8 with statement,

The 8.9 switch statement,

9 function


 Extended reading:

  “JavaScript advanced programming (Third Edition) study notes 2— — basic grammar”

This article review the basic syntax of ECMAScript specification, English good friends can directly read the official document. JavaScript is essentially a language like C, familiar with C friends, can read this article very easily, even can skip, but I suggest you had better look, in the meanwhile, I might use the self that is not easy to understand and more popular.

Basic grammar

1,The so-called identifier: identifier, actually refers to a certain standard, can be engine to identify the name, can be used to represent a constant, variable, function name, function parameters, object, object attribute all the named object name.

(1)Case sensitive.

(2)With the letter, underscore (_) or a dollar sign ($) at the beginning, the other characters can be letters, underline, dollar symbols or numbers. This letter contains extended or Unicode characters in ASCII.

(3)The identifier must not be keywords, reserved words, true, false, null. (some browsers allow the use of undefined, some not).

(4)If the object attributes contain spaces or other special characters, can use parentheses as a whole.

2,Keywords: for specific purposes in the language itself.

break   case  catch  continue  Debugger (new in ES5)  default  delete  do  else   finally  for  function  if  in  instanceof  new  return  switch  this   throw  try  typeof  var  void  while  with

3,Reserved words: language itself will be retained, as a key.

The reserved word ES3.:

abstract   boolean  byte  char  class  const  debugger  doubleenum  export   extends  final  float  goto  implements  importint  interface  long   native  package  private  protected  publicshort  static  super   synchronized  throws  transient  volatile

The reserved word non strict mode in ES5:

class  const  enum  export  extends  import  super

The reserved word strict mode under ES5:

implements  interface  Let (new in ES5 package private protected public) static yield (new in ES5)

4,In strict mode: the introduction of strict mode in ES5, by using the "use strict" to open the strict mode, can open the global strict mode at the top, can also open local strict mode in the function scope.

"use strict"//Open global strict mode, in ES3, will not have any impact

function fn(){  "use strict"//To open local strictly mode}

5,Note: in ECMAScript, supports two format comments, comment and block level annotation:

// Single line comments begin with a slash //, two

/* * Multi line (block) notes, with a forward slash / and an asterisk * at the beginning, a star and a slash at the end of the asterisk * here, middle row is not necessary */

Remarks: with the JS code more complex, Notes also becomes more and more important, Document automation becomes more important than ever, There are many open source JS library for automatic generation of Javadoc is similar to the JS document, Such as JSDoc, YUIDoc etc., (2)The VaR operator: variables using the VaR statement, For uninitialized variables, The default is undefined, Can also use the variable without statement (in my opinion, This is also a no reason characteristics), The most important difference between them is to use the VaR statement, A variable declared effective only in the current scope, Instead of using the VaR, Variables can be defined at global scope. Through the following example to understand the difference between:

var name = 'linjisong';  //The definition of global variables and the assignment of age = 29;

//The direct use of variable, equivalent to the definition of global variables and assignment//sal;

//Error var salary;

//The definition of global variables, not initialized at this time, also will have the corresponding format requirements of annotation, interested friends can find relevant information research.

6,Variables: variables in its essence is but a memory space at the language level of the external image.

(1)Dynamic type: in ECMAScript, variables are dynamically typed, you can then define when initialized with a Number type,, you can put a string value is assigned to it:

var age = 29;

age = 'twenty-nine';  //Although this flexibility, but I suggest you unless you know what you are doing, otherwise don't do this.

(2)The VaR operator: variables using the VaR statement, for uninitialized variables, will default to undefined, but also can be directly used variables without the statement (in my opinion, this is also a no reason for existing features), the most important difference between them is to use the VaR statement, statement of variables only in effective current scope, instead of using the VaR, variables can be defined at global scope. The difference can be the example below.:

var name = 'linjisong';  //The definition of global variables and assignment

age = 29;

//The direct use of variable, equivalent to the definition of global variables and assignment



var salary;

//The definition of global variables, not initialized

//Here is a function declaration, not the actual call, so the internal definition of variables will not take effect

function fn(){

var name = 'oulinhai';//Declare a local variable and assign

age = 23;

//To the global variable assignment

work = 'it';      //Do not use VaR, even in the variables local to the function, will also become a global variable


//Before the actual call function;    //undefined;

  // linjisong;

// 29

try{;//Because work is not defined in the global environment, it will throw an exception


fn();//The actual call, code for variable change will appear;

// linjisong, As the function of internal use of the VaR, so it will not change the overall name value;

// 23;

// it

(3)Statement: this problem will enhance again talked about function declarations and function expression, mention here, look at the code:




4 try{ 


6 }catch(e){


8 }




12 }catch(e){


14 }


16var name = 'linjisong';//Variable declaration, improve

17 age = 29;//The direct use of global variables, not to ascend

18function getName(){//Declare function, improve

19return name;

20 }

21var getAge = function(){//The variable getAge statement, lifting; anonymous function expression for age, not to ascend

22return age;

23 }






29;//An anonymous function to obtain the age


Do you have inferred from the above? If it has been inferred, can be skipped, if in doubt, then have a look described below statement about ascension, then go back and prove the above:

A,Engine in the resolution, will first analytic function declarations, and analytical variable declaration (resolution does not cover type), then execute the code,

B,Analytic function declaration, can also resolve the type (function), but not executed, analytical variable declaration, only analytical variables, not initialize.

Here it is the global scope, the function scope and function is related to the parameters and statement are discussed later in ascension, then tells the function.

The code, will be the first eighteenth lines of the function declaration and line 16,21 variable declaration to the beginning, and then perform. The line 1,9 for variable declaration promotion but has not been initialized, so the output of undefined, and eleventh could not be determined because is a function type and type of the exception thrown; line 2,3 for function declaration lifting and analytic function type, so the second line of the output function, the third line to call a function, but the return value of an uninitialized undefined output; the fifth line because it has not yet declared variables, throws reference exception.

(4)You can use a statement to define multiple variables, can be separated with a comma. Such as: var name='linjisong',



(5)In strict mode on ES5, we cannot define named Eval or arguments variables.


(1)Statement: with a semicolon; “ ” at the end, if omitted semicolon, by the parser to determine the end of a statement.

  For the characteristics of JS statements can be omitted semicolon, I can't think of any reason for each statement, strongly suggest using a semicolon to clear to the end, don't let the parser takes time to guess the “ ” your program, and, more importantly, in many compression tools, speculation can not guarantee 100% the correct.

(2)The code block: a left brace ({), the right brace (}) end.

  In JS while the concept of code blocks, but no block level scope corresponding, this is a general class of C language and the different. The control statement (such as if), not because there is only one statement does not use the code block, it will give you guys a maintenance program under the wrong seed.

for(var i=0; i<10; i++){};//The output of 10, in the code blocks can still access I, indicating that JS does not block level scope if (I <10) // (I);   do not use the code block, at the time of maintenance (such as adding 1 statements) easy to make mistakes{;}

The curly braces ({}) except as a block of code to use, there is a very important use is to define object literals, which will be discussed in the back.

“JavaScript advanced programming (Third Edition) study notes 3— — simple data types”

Data type is a programming language of brick, is all that you can imagine the complex foundation, in modern programming languages, except for some types of simple data language built-in, basically provide a mechanism for language custom data types (in C can also be achieved by using the structure) the mechanism, to a certain extent determines the popularity and vitality of the language. ECMAScript is a dynamically typed language, based on 5 simple data types (Undefined, Null, Boolean, Number, String) and a complex data types (Object) on the basis of. This article is to review the simple data types, I will try to describe the programming from practical point of view, the following code operating environment for the FireFox 14.0.1.

Simple data types

First, there is a need to explain, in ECMAScript, the 5 simple data types, including Boolean, Number, String have built-in packaging object with that name, and a simple data type literals (variables) will automatically package box according to the situation, which can directly call the method, but the specific can invoke methods, in the discussion the built-in objects and details:;//true,Equivalent to using the Boolean (then called) packaging;//false, Convert false to Boolean type value Boolean(false).toString());//false, Using Boolean (false) packaging;//false, Equivalent to using the Boolean (then called) packaging'test'.toString());//test, Equivalent to using the String (then called) packaging

try{;//There is no corresponding packaging types, throw an exception



try{;//There is no corresponding packaging types, throw an exception



var num = 4;;//4, Can directly call in simple numerical variables method, equivalent to the use of Number (then called) packaging

//;//SyntaxError,Syntax error try cannot be used to capture, can not directly call the numeric literals.

Then said the most used data conversion:  

(1)Conversion to Boolean: !!value

(2)Conversion to Number: +value

(3)Conversion to String: ''+value

Next, specify 5 simple data types:

1,Undefined type

The Undefined data type with only one value: undefined.

(1)All uninitialized values are undefined (it is not necessary to pass a variable display initialization for undefined).

(2)In the function field, the function parameter has no incoming actual parameters for undefined.

(3)Has no clear function returns or return; when, the return value is undefined.

(4)In ECMAScript, null==undefined returns true, and null===undefined returns false.

(5)Undefined the corresponding Boolean value is false.

(6)The use of typeof in undefiend, the returned string'undefined', acting on a never declared “ variable &rdquo, will return;'undefined'.

(7)Undefined conversion value is NaN, convert the string to'undefined'.;//true undefined);//undefined noDefined);//undefined, Identifier is not defined, typeof returns undefined, which is not defined identifier is the only available.!undefined);//true, Here to return to the true, is the fundamental variables are initialized judge a lot of conditional statements!!undefined);//Any value, the use of double negative!! will be converted to the corresponding Boolean value, the corresponding Boolean value for the false undefiend;//Specified in the ES, null and undefined equality test returns true;//But undefined and null are two types of data, the use of congruent comparison, return false undefined==undefined);//false, Typeof undefined returns a string'undefined', so here the output false;//NaN,Conversion value for NaN''+undefined);//undefined, Converted to a string'undefined'

2,Null type

The Null type is only one value: null.

(1)The use of typeof for the null value, the returned string'object'.

(2)Null the corresponding Boolean value is false.

(3)If a variable for the preservation of an object, that is initialized to the null.

(4)Null conversion value is 0, convert string to'null'.; //;//!null); //!!null);//false,Null the corresponding Boolean value is false;//true;//false;//0, Converted to a value of 0''+null);//null, Converted to a string'null'

3,Boolean type

Boolean type has only two values: true and false.

(1)Although only two values, but any one of the values of the data type can be converted to the corresponding Boolean value, there are three main types of conversion:

A,Through the transformation function Boolean (conversion)

Note that, when Boolean () as the transfer function, will be converted to a corresponding Boolean value, when used as a constructor, will create an object, and the arbitrary non empty object Boolean values are true, sometimes it will cause misunderstanding, suggestion is not to use Boolean (). For the String (), Number () has a similar situation.

B,The double negation operator conversion!!

C,Through implicit conversion, such as the number of conditional statements

(2)Boolean type true and false, using typeof, return the string'boolean'.

(3)In the conversion of value, true and false were converted to 1 and 0, converted to a string, respectively'true'and'false'.

var value = 'test';

var empty = '';!!value);//true!!empty);//false;//true;//false!!value === Boolean(value));//true, The equivalence of two different methods!!empty === Boolean(empty));//true Boolean(value));//The Boolean object, note the use of the new, will create an object Boolean(empty));//The Boolean object

if(value){//Implicit conversion to true;//test


if(empty){//Implicit conversion to false, do not execute brackets internal statement'empty');


if(new Boolean(empty)){//You create the object, then the implicit conversions to true, executes the statement within parentheses'empty');//empty

} == 'boolean');//true;//1, Unary operators, converted to a value of 1;//0''+true);//true, After loading the + operator, is converted to a string'true'''+false);//false

The conversion rules are as follows:

4,Number type

   In ECMAScript, there is no separate integer, floating point, only one type of Number, use the IEEE754 format (this notation will have a rounding error in the calculation), here is not to discover the underlying implementation, these things to learn the C language in the school have been very headache, do not want to have a headache a time. Now I put the actual programming most used on the front, which generally have enough trouble for, do not want to be too the edge details of friends, you can skip the discussion on the Number at any time.

(1)Numerical conversion: mainly three conversion functions below

Note: the use of Number (+) and conversion, true— > false— 1, > 0, undefined— > NaN, null— > 0, the empty string — > 0, a non empty string — > according to numerical analysis.

var trueVal = true;

var falseVal = false;

var undef = undefined;

var nullVal = null;

var intVal = '1';

var floatVal = '1.0';

var strVal = 'test';

var empty = '';;//1;//0;//NaN;//0;//1;//1;//NaN;//0;//1;//0;//NaN;//0;//1;//1;//NaN;//0;//;//NaN;//NaN;//NaN;//1;//1;//NaN;//NaN;//;//NaN;//NaN;//NaN;//1;//1;//NaN;//NaN

Remarks: the conversion function behavior may be due to the different browsers and different, in practice the programming process of questionable to write test. In the "JavaScript advanced programming (Third Edition)", described in this section there are a lot of places and the actual operation results, such as the original parseInt () can only parse the string, but the following code can run:

var object = {






(2) Integer and floating point numbers: C language influence people, must be some integer and floating point numbers to distinguish the stubborn! In ECMAScript, they do not seem so different, simple point, contains a decimal point after the decimal point and at least one not 0 numerical is floating point, otherwise it is an integer, such as 1.01 floats, 1, 1 because it is not the number of 0 is not after the decimal point, the engine will resolve to the integer 1. You might imagine two integer division results are rounded, such as 3 / 2 = 1, but in the ECMAScript, don't worry about these, has reduced its mathematical properties, you'll find out 3 / 2 = 1.5, this point, then mentioned in the operator related part will.

(3)Hex: also known as binary system, is actually carry (low to high) method, each band has a base, when the low value reaches the base, to high into the 1. In daily life, with the largest number of nature is 10 m, such as the 10 angle will carry 1 yuan, at the time of measurement, there are 24 m (24 hours to 1 days), 60 m (60 seconds for 1 points), in ancient times, there are 16 hexadecimal (think just about the same.). But in the computer processing, because the current only through and through two states, so can only handle 2 hexadecimal data for a natural person, but it is not well understood, and the use of 8 hexadecimal, 16 hexadecimal as intermediate state 10 hex and 2 hex conversion.

  In ES3, you can use 8 hexadecimal, 10 hexadecimal, 16 hexadecimal, but in ES5, 8 band has been disabled.

  8 - to 1 digits: 0, is behind the 8 hexadecimal digit sequence (0~7), if the number exceeds 7, will ignore the leading 0 as the 10 band processing, such as 08 will be parsed as 10 hexadecimal number 8.

  16 hex: start with 1 digit 0 and 1 letter X, is behind the 16 hexadecimal digit sequence(0-9a-fA-F).

  10 hex: can direct all digital one one is written, can also use scientific notation (do not understand? To find a middle school mathematics textbooks to have a look.) to represent.

(3) The special value: in ECMAScript, there are 2 special value NaN and Infinity need attention, the former represents not a numeric (Not a Number), who said not in numerical range, can also use positive and negative direction. For the two special value, here is not to examine the specific operational rules (if you are interested, can be self testing, I will cite some examples in the following), only the following two description:

  A,Val==NaN can't be used to judge whether a variable is NaN, and to use the global isNaN () function, the function receives a parameter, when the parameters can be converted to a value to return true, otherwise it returns false.

   B,Try not to use val==Infinity to determine whether out of range, and the use of global isFinite () function, the function receives a parameter, when the parameters representing the return true range in, otherwise it returns false. What say here that range is from Number.MIN_VALUE to Number.MAX_VALUE, in addition, in the Number, and the properties of Number.NEGATIVE_INFINITY and Number.POSITIVE_INFINITY, its value is Infinity and respectively. -Infinity.;


var notNumber = NaN;;//false;//true;




var inf = Infinity;;//true!isFinite(inf));//true!isFinite(NaN));//true;//false

Note: the in the "JavaScript advanced programming (Third Edition)" in the twenty-ninth page of any numerical divided by 0 will return NaN, in fact is not true.

5,String type

And the general class of C language is different, in the ECMAScript, not the character type, and the string type String as a simple type, its literal use quotation marks (single quotes' or double quotation marks enclose “).

(1)The string type operation, plus “ +” be overloaded, an arbitrary numerical and string together, will first be converted to a string using String (), and then the two strings.

(2) The use of String (undefined&mdash) conversion,'undefined', null— >'null'; > true—, >'true', false— >'false', > Number&mdash numerical type; according to the numerical visible character conversion, object Object— > call toString.''+1+1);//11, Instead of 2''+true);//true''+undefined);//undefined''+null);//null

(3)String using the backslash “ \” to escape, some escape characters are common:

Well, on the simple data types, tidy up to.

If the data type is a programming language tile, so operators and operator is the programming language of lime and cement, it is the value of combining agent of the combination of various data types, the data values are not only an isolated value, and with the spirit of a dynamic. In ECMAScript, a very rich operators and operators, in this article, according to the usual classification to tidy up a bit, but in finishing before, to explain to you:

1,Although the title is the operator and the operator, but not many distinguish strictly necessary in my opinion, in English, it is expressed as a Operator, so in the following I will mix. Even, some do not belong to the operator and the operator category, I finish here, as long as I feel necessary.

2,For operators of priority, you don't need to keep in mind that the &mdash one one; — I'm sure you know the most simple ” after the first division, addition and subtraction, ” for the rest, if you're not sure, in parentheses. In ECMAScript, the same priority operation from left to right.

3,For some programming language generic operators, such as common arithmetic operators (+ - * /), I will only a simple list, will not start, but please note, is not to say that these are not important, on the contrary, these generic operators even in a very basic position, but I think you should already be familiar with, no need in the take the time to emphasize here.

4,So, here to focus on what? Some in the ECMAScript special operator, or I think some places worth spending time on.

Operator and operator

[Click to enlarge]

To illustrate several:

1,This classification is not very strict, such as by non (~), non logic (!), delete, void, typeof, can be considered a unary operator, and the increment (+ +) in many data has been classified as an arithmetic operator. I make the arrangement is the main reference book classification, but also take into account the nature.

2,The plus sign (+) usage is flexible, should pay attention to, especially for the calculation, ignore the string, will be very easy to make mistakes.

3,Typeof is generally used to determine the simple data types, if the object type, because most return object, there is not much practical use, and the judgment of instanceof also need to meet the same context conditions, otherwise it would be wrong, for object category judgment will tell the object behind again when the details of another more reliable method.

4,Look at the following code:

var numVal = 10.00,

strVal = '10',

strObj = new String('10'); == strVal);//true (strVal+strObj));//string

The first output is actually true, is it right? Surprise you? Here, the comparison operator = = the implicit type conversion, the Number conversion to String to 10, and then type Number because after the decimal point not is the 0 value, will be parsed into the integer 10, when compared with the. The second output is string, it is still relatively easy to understand, strVal is a string, strObj is a string object, the two together, the object is converted to a string, so the end result is a string type.

5,A symbol, repeat several popular usage (not a regular expression usage involved here):

(1)Use unary plus (+) into a Number type.

(2)The use of dual logic non (!!) is converted to Boolean type.

(3)The use of logic and (& &) to detect the existence of an object and the subsequent operation.

(4)The use of logical or (||) to function parameters provide default values.

(5)Using packet () () to explicitly specify the expression.

(6)Use curly braces ({}) to define object literals, JSON data format, the code block.

(7)Use the brackets ([]) to define the array literal, JSON data format, array access, access is the name attribute variables or special characters.

6,A bitwise operations, although the results are not very intuitive, but high efficiency, also has many interesting applications, such as not using intermediate variables directly exchange two numerical, judgment of odd and even numbers, MD5 encryption and so on, interested friends can find relevant information research.

Source: blog

Reference books:

  [1]Professional JavaScript for Web Developers 3rd Edition: JavaScript advanced programming (Third Edition) []Nicholas C.Zakes   Li Songfeng   Cao Li   people's Posts and Telecommunications Press.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Corrine at November 12, 2013 - 2:01 PM