Common JavaScript Manual/Printable version
This is the print version of Common JavaScript Manual You won't see this message or any elements not part of the book's content when you print or preview 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
How read this book
Optional arguments
editOptinal variables enclosed in square brackets. For example Array.join([separator])
Variable in description
editIn function description variables are bolded. For example Math.sqrt(num) - square root of num
Undefined number of arguments
editUndefined 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 from Array and elements if elements[n] is array then to the array that returns are added all elements from elements[n].
Data types - Numbers
Numbers
editFor example, let's set the value for the variable 'a'
a = 46;
And for the variable 'b'
b = 7;
Arithmetic operations
editLet'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
Increment, Decrement, Unary operators
editFor 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 = 6
b = a--; // b = 6 , a = 5
b = -a; // b = -5
Standart library functions
editAlso we can apply some functions to numbers. We will consider only most important.
c = f.toFixed(b); //Rounding to 'b' digits after dot
d = Math.abs(-6); //Absolute value (module) of number
e = Math.round(f); //Rounding to integer
g = 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 constants
editStandart library include some math constants. We will consider only the most important.
a = Math.PI // π number
b = Math.E // e number
Special values
editNumbers in JavaScript also include two special values are Infinity and NaN(Not a Number)
a = 1/0 // Infinity
b = Math.sqrt(-1) // NaN
Data types - Arrays
Making Array
editFor making array it's better to use list literal because it's most popular and simple syntaxis
a = []; //Empty list
b = [1,2,3,4,5]; //List with 5 elements
Work with elements
editAnd so, we have an array 'b' with five numbers and the empty array 'a'.
a[0] = b[2]; //1
delete b[2]; //2
b[3] = 6; //3
- From array b - [1,2,3,4,5] get element with index 2 (Numeration in arrays starts from 0). Now array a = [2]
- We delete element with index 2 from array b. Now array b = [0,1,undefined,3,4].
- We change value of element with index 3 from array b. Now array b = [0,1,undefined,6,4].
Work with slices
editArray.slice(start,end) - returns array with elements of Array from start index to end index without element with index end.
a = [0,1,2,3,4,5,6,7];
b = a.slice(2,5); //2,3,4
If start or end is negative number then index of start or end equal (length of array + start or end).
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 with number of elements from Array from start and it deletes this elements from Array, and it replaces it's by elem
a = [0,1,2,3,4,5,6,7];
b = a.splice(2,3,0,1,0);
print(b); // 2,3,4
print(a); // 0,1,0,1,0,5,6,7
Stack and row
editYou can use any Array as stack or row for it there are 4 function.
Name | Action |
---|---|
Array.pop() | Delete and return last element of Array |
Array.push(elem...) | Insert elem to end of Array |
Array.shift() | Delete and return first element of Array |
Array.unshift(elem...) | Insert elem to start of Array |
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]
Sorting and reverse
editAlso Array.sort([predicate]) - If predicate not defined then sort elements in Array in lexicographical order else sort element in Array by results of function predicate that gets two arguements and returns -1 if first argument less then second or 1 if second argument less then first or 0 if arguments equal.
Array.reverse() - reverse elements in Array
arr = [5,3,1,4,2];
arr.sort();
print(arr); //1,2,3,4,5
arr.reverse();
print(arr); //5,4,3,2,1
Concatenate and joining
editArray.concat(elem1...) - returns array that containg elements from Array and elem 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,10
str = arr.join(';'); //0;1;2;3;4;5;6;7;8;9;10
print(str);
Length of Array
editArray.length - number of elements in Array
arr = [0,1,2,3,4,5]
print(arr.length); // 6
Data types - Strings
Strings
editLet'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, ";
Concatenation
editWe can concatenate strings using '+' operator. Let's add to string in variable 'a' string "world".
str = str + "world!"; // Hello, world!
Length of string
editAny string has a 'length' property that contains the number of chars in the string.
str.length; // 13
Split
editString.split([separator]) - returns array of substrings that was obtained by separating String by separator. If separator is not defined then separator = ","
names = "Artem,Michail,Nicholas,Alexander";
listOfNames = names.split(','); //Split string to list of strings
twoNames = names.split(',',2); //Split with limit
Getting substrings and char
editWe 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); //Hello
second = 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
Position of substring
editWe 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); // 7
c = a.lastIndexOf('l'); // 9
Conditional statements
If statements
editWe 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");
Else statements
editWe 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");
}
Else if statements
editAlso we can set any number conditions and blocks of code for this conditions.
n = 0;
if(n > 0){
print("n is positive");
}else if(n == 0){
print("n is zero");
}else{
print("n is negative");
}
While and For loops
While
editWhile 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
edit"For" cycle is a short form of while.
for(exp1;exp2;exp3){
code
}
//Equal for
exp1;
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
Do .. While and For .. in loops
Do .. While
editIn 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
editFor .. in loop using if need iterate over all properties of object. For example.
obj = {name:"Artem",
country:"Russia",
interests:"JavaScript"};
for(i in obj){
print(i + ':' + obj[i] + '\n')
}
In this code on every iteration to variable 'i' set value with key of property.
Break, continue, labels
Break
editBreak 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
editContinue 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
editLabels help use break and continue in nested loops.
glob:for(i=0;i<10;i++){
for(j=0;j<10;j++){
if(i==j)continue glob;
print(i*10 + j)
}
}
Logic and Comparison operators
Logic operators
editThere are three logical operators in JavaScript. It are "not","and","or". Let's see example.
Operator | Action |
---|---|
|| | or |
&& | and |
! | not |
!true; // False
!false; // True
false || true; // True
false && true;// False
Comparison operators
editIn 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; //True
5 === '5'; //False
5 != 3; //True
5 !== '3'; //True
5 > 3; //True
5 < 3; //False
5 <= 5; //True
5 >= 3; //True
XOR Hack
editIn 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){
return Boolean(a ^ b)
}
And let's use it.
xor(true,false); //True
xor(true,true); //False
xor(false,false); //False
Condition operator
Conditional operator
editIf 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 expression
if(cond){
name = "Tom";
}else{
name = "Artem";
}
//Conditional operator
name = cond?"Tom":"Artem";
Nested conditional operator
editAs 'if' expression so and Conditional operator can be multiple.
name = "Artiom";
cond1 = false;
cond2 = true;
//Conditional operator
name = cond1?"Tom":cond2?"Artem":"NoName"