This is theprint version ofCommon JavaScript Manual You won't see this message or any elements not part of the book's content when you print orpreview this page. |
The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Common_JavaScript_Manual
Optinal variables enclosed in square brackets. For example Array.join([separator])
In function description variables are bolded. For example Math.sqrt(num) - square root ofnum
Undefined number of arguments in function written as name... and function description name are all these variables in general, and name[n] either name. For example Array.concat(elements...) - returns array that containg elements fromArray andelements ifelements[n] is array then to the array that returns are added all elements fromelements[n].
For example, let's set the value for the variable 'a'
a=46;
And for the variable 'b'
b=7;
Let's output results of arithmetic operations with these variables.
print(a+b);print(a-b);print(a*b);print(a/b);print(a%b);//Modulo
For enlarging or reducing some variable by one we can use increment and decrement operator. And we can change char of number by unary operator.Decrement and increment have two types of recording - postfix and prefix.Prefix - first the value is changed then the new value is returned.Postfix - first the value is returned then value is changed.
a=5;b=++a;// b = 6 , a = 6b=a--;// b = 6 , a = 5b=-a;// b = -5
Also we can apply some functions to numbers. We will consider only most important.
c=f.toFixed(b);//Rounding to 'b' digits after dotd=Math.abs(-6);//Absolute value (module) of numbere=Math.round(f);//Rounding to integerg=Math.max(a,b);//Maximum value of variables 'a' and 'b'h=Math.min(a,b);//Minimum value of variables 'a' and 'b'k=Math.pow(a,b);//Variable 'a' in power 'b't=Math.sqrt(a);//Square root of variable 'a'w=Math.random();//Random number from 0 to 1
Standart library include some math constants. We will consider only the most important.
a=Math.PI// π numberb=Math.E// e number
Numbers in JavaScript also include two special values are Infinity and NaN(Not a Number)
a=1/0// Infinityb=Math.sqrt(-1)// NaN
For making array it's better to use list literal because it's most popular and simple syntaxis
a=[];//Empty listb=[1,2,3,4,5];//List with 5 elements
And so, we have an array 'b' with five numbers and the empty array 'a'.
a[0]=b[2];//1deleteb[2];//2b[3]=6;//3
Array.slice(start,end) - returns array with elements ofArray fromstart index toend index without element with indexend.
a=[0,1,2,3,4,5,6,7];b=a.slice(2,5);//2,3,4
Ifstart orend is negative number then index of start or end equal (length of array +start orend).
a=[0,1,2,3,4,5,6,7];b=a.slice(2,-2);//2,3,4,5 because length = 8 and 8 + (-2) = 6
Array.splice(start,number,elem...) - return slice withnumber of elements fromArray fromstart and it deletes this elements fromArray, and it replaces it's byelem
a=[0,1,2,3,4,5,6,7];b=a.splice(2,3,0,1,0);print(b);// 2,3,4print(a);// 0,1,0,1,0,5,6,7
You can use any Array as stack or row for it there are 4 function.
| Name | Action |
|---|---|
| Array.pop() | Delete and return last element ofArray |
| Array.push(elem...) | Insertelem to end ofArray |
| Array.shift() | Delete and return first element ofArray |
| Array.unshift(elem...) | Insertelem to start ofArray |
For example:
Foo=[1,2,3,4,5];Bar=Foo.pop();//Bar = 5 , Foo = [1,2,3,4]Foo.unshift(Bar);// Foo = [5,1,2,3,4]
Also Array.sort([predicate]) - If predicate not defined then sort elements inArray in lexicographical order else sort element inArray by results of functionpredicate that gets two arguements and returns-1 if first argument less than the second or1 if the second argument is less than the first or0 if the arguments are equal.
Array.reverse() - reverse elements inArray
arr=[5,3,1,4,2];arr.sort();print(arr);//1,2,3,4,5arr.reverse();print(arr);//5,4,3,2,1
Array.concat(elem1...) - returns array that containg elements fromArray andelem if elem[n] is array then to the array that returns are added all elements from elem[n].
Array.join([separator]) - returns string with all elements and separator before every, if separator not defined then separator = ","
arr1=[0,1,2,3,4]arr2=[5,6,7,8,9]elem=10;arr=arr1.concat(arr2,elem);//0,1,2,3,4,5,6,7,8,9,10str=arr.join(';');//0;1;2;3;4;5;6;7;8;9;10print(str);
Array.length - number of elements inArray
arr=[0,1,2,3,4,5]print(arr.length);// 6
←Data types - Numbers · Data types - Strings →
Let's make a variable with a string as value; we will use string literal. Strings can be enclosed in double and single quotes (though in most languages strings are enclosed in double quotes and chars in single quotes).
str="Hello, ";
We can concatenate strings using '+' operator. Let's add to string in variable 'a' string "world".
str=str+"world!";// Hello, world!
Any string has a 'length' property that contains the number of chars in the string.
str.length;// 13
String.split([separator]) - returns array of substrings that was obtained by separatingString byseparator. Ifseparator is not defined thenseparator = ","
names="Artem,Michail,Nicholas,Alexander";listOfNames=names.split(',');//Split string to list of stringstwoNames=names.split(',',2);//Split with limit
We can get a substring from a string using the substr(index,len) and substring(indexA,indexB) methods. First returns the substring from 'index' with length equal to len. Second returns the substring from indexA to indexB.
a="Hello world!";first=a.substr(0,5);//Hellosecond=a.substring(6,11);// world
We can also get a char at some position using charAt function.
a="Hello world!";b=a.charAt(2);//e
We can also get a position of some substring in a string using the indexOf and lastIndexOf methods. Both functions have two arguments but only the first is required: the string to be searched and the position from that the string is searched. indexOf returns the first position of the substring and lastIndexOf returns the last position of the substring. If the substring is not found both functions return -1.
a="Hello world";b=a.indexOf('o',5);// 7c=a.lastIndexOf('l');// 9
←Data types - Arrays · Data types - Objects →
We can do so that some blocks of code should execute only if condition true. For it we should use "if" expression. Let's see example.
n=6;if(n>0)print("n is positive");
We also can make code block that should be executed only if condition false. For execute much commands just enclose it in '{' and '}'.
n=-5;if(n>0){print("n is positive");}else{print("n is negative or zero");}
Also we can set any number conditions and blocks of code for this conditions.
n=0;if(n>0){print("n is positive");}elseif(n==0){print("n is zero");}else{print("n is negative");}
←Data types - Objects · While and For loops →
While expression looks so:
while(condition){codeInCycle}
Here, if the condition is true then the code inside the loop and then the process goes first but if the condition is true then execution continues after the loop. Let's see example.
n=2;nums=[];while(n<16){nums.push(n++);}print(nums);//2,3,4,5,6,7,8,9,10,11,12,13,14,15
"For" cycle is a short form of while.
for(exp1;exp2;exp3){code}//Equal forexp1;while(exp2){code;exp3;}
Let's rewrite our code.
for(n=2,nums=[];n<16;n++){nums.push(n);}print(nums);// 2,3,4,5,6,7,8,9,10,11,12,13,14,15
←Conditional statements · Do .. While and For .. in loops →
In this cycle, executing the code in it and then check the condition and if it is true then the loop is executed again, otherwise terminate the loop. Let's see example.
names=["JavaScript","Python","Ruby"];i=0;do{name=names[i];i++;}while(print(name)||i<names.length);
Do .. while loop can be used if code inside a loop set some values and in condition you call some function.
For .. in loop using if need iterate over all properties of object. For example.
obj={name:"Artem",country:"Russia",interests:"JavaScript"};for(iinobj){print(i+':'+obj[i]+'\n')}
In this code on every iteration to variable 'i' set value with key of property.
←While and For loops · Break, continue, labels →
Break statement can interrupt the cycle. For example.
str="";i=0;j=100;while(true){i++;j--;if(j==i)break;str=str+i+':'+j+',';}
This code makes string with list of pairs of numbers while they are not equal.
Continue statement makes the transition to the next iteration of the loop.
arr=[0,2,4,5,6,1,24,36,12,531,42,49,81];for(i=0;i<arr.length;i++){if((Math.sqrt(arr[i])%1)>0)continue;print(arr[i])}
This script output numbers from array which square roots is integer.
Labels help usebreak andcontinue in nested loops.
glob:for(i=0;i<10;i++){for(j=0;j<10;j++){if(i==j)continueglob;print(i*10+j)}}
←Do .. While and For .. in loops · Logic and Comparison operators →
There are three logical operators in JavaScript. It are "not","and","or". Let's see example.
| Operator | Action |
|---|---|
| || | or |
| && | and |
| ! | not |
!true;// False!false;// Truefalse||true;// Truefalse&&true;// False
In parts of the previous file you've already seen some of these operators, and certainly understand their meaning but in anyway.There are 8 comparison operators in JavaScript.
| Operator | Condition |
|---|---|
| == | Equal |
| != | Not equal |
| === | Equal value and type |
| !== | Not equal value or type |
| > | More |
| < | Less |
| <= | Less or equal |
| >= | More or equal |
And for example:
5==5;//True5==='5';//False5!=3;//True5!=='3';//True5>3;//True5<3;//False5<=5;//True5>=3;//True
In JavaScript there is no operator XOR (also named Exclusive OR). But we can write function that use bitwise XOR and return booleadn XOR of two arguments.
xor=function(a,b){returnBoolean(a^b)}
And let's use it.
xor(true,false);//Truexor(true,true);//Falsexor(false,false);//False
←Break, continue, labels · Condition operator →
If we need just set value for any variable in depent of condition, we can use conditional operator. It's shorter than "if" expression many times. Let's see example.
name="Artiom";cond=true;//If expressionif(cond){name="Tom";}else{name="Artem";}//Conditional operatorname=cond?"Tom":"Artem";
As 'if' expression so and Conditional operator can be multiple.
name="Artiom";cond1=false;cond2=true;//Conditional operatorname=cond1?"Tom":cond2?"Artem":"NoName"
←Logic and Comparison operators · Switch expression →