75% developed

Common JavaScript Manual/Printable version

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Common JavaScript Manual

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

How read this book

Optional arguments[edit | edit source]

Optinal variables enclosed in square brackets. For example Array.join([separator])

Variable in description[edit | edit source]

In function description variables are bolded. For example Math.sqrt(num) - square root of num

Undefined number of arguments[edit | edit source]

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 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[edit | edit source]

For example, let's set the value for the variable 'a'

a = 46;

And for the variable 'b'

b = 7;

Arithmetic operations[edit | edit source]

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

Increment, Decrement, Unary operators[edit | edit source]

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 = 6
b = a--; // b = 6 , a = 5
b = -a; // b = -5

Standart library functions[edit | edit source]

Also 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[edit | edit source]

Standart library include some math constants. We will consider only the most important.

a = Math.PI // π number
b = Math.E // e number

Special values[edit | edit source]

Numbers 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

Data types - Arrays

Making Array[edit | edit source]

For 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[edit | edit source]

And 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
  1. From array b - [1,2,3,4,5] get element with index 2 (Numeration in arrays starts from 0). Now array a = [2]
  2. We delete element with index 2 from array b. Now array b = [0,1,undefined,3,4].
  3. We change value of element with index 3 from array b. Now array b = [0,1,undefined,6,4].

Work with slices[edit | edit source]

Array.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[edit | edit source]

You 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[edit | edit source]

Also 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];
print(arr); //1,2,3,4,5
print(arr); //5,4,3,2,1

Concatenate and joining[edit | edit source]

Array.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

Length of Array[edit | edit source]

Array.length - number of elements in Array

arr = [0,1,2,3,4,5]
print(arr.length); // 6

Data types - Numbers · Data types - Strings

Data types - Strings

Strings[edit | edit source]

Let's make variable with string as value, we will use string literal. Strings can be enclosed in double and single quotes but I advise using double quotes because in most laguages strings enclosed in double quotes and chars in single quotes.

str = "Hello, ";

Concatenation[edit | edit source]

We can concatenate strings using '+' operator. Let's add to string in variable 'a' string "world".

str = str + "world!"; // Hello, world!

Length of string[edit | edit source]

Any string variable have 'length' property that containg number of chars in string.

str.length; // 13

Split[edit | edit source]

String.split([separator]) - returns array of substrings that was obtained by separate String by separator. If separator 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[edit | edit source]

We can get substring from string using functions substr(index,len) and substring(indexA,indexB). First return substring from 'index' with length equal to len. Second return 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[edit | edit source]

We can also get a position of some substring in string using indexOf and lastIndexOf functions. Both functions give two arguments but only first required it's a string that function search and second argument it's position from that function search string. indexOf return first position of substring and lastIndexOf return las position of substring. If substring not found both functions return -1

a = "Hello world";
b = a.indexOf('o',5); // 7
c = a.lastIndexOf('l'); // 9
Data types - Arrays · Data types - Objects

Conditional statements

If statements[edit | edit source]

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");

Else statements[edit | edit source]

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");
  print("n is negative or zero");

Else if statements[edit | edit source]

Also 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");
  print("n is negative");

Data types - Objects · While and For loops

While and For loops

While[edit | edit source]

While expression looks so:


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){
print(nums); //2,3,4,5,6,7,8,9,10,11,12,13,14,15

For[edit | edit source]

"For" cycle is a short form of while.

//Equal for

Let's rewrite our code.

print(nums); // 2,3,4,5,6,7,8,9,10,11,12,13,14,15
Conditional statements · Do .. While and For .. in loops

Do .. While and For .. in loops

Do .. While[edit | edit source]

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;
  name = names[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[edit | edit source]

For .. in loop using if need iterate over all properties of object. For example.

obj = {name:"Artem",
for(i in obj){
  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, continue, labels

Break[edit | edit source]

Break statement can interrupt the cycle. For example.

str = "";
i = 0;
j = 100;
  str = str + i + ':' + j + ',';

This code makes string with list of pairs of numbers while they are not equal.

Continue[edit | edit source]

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];
  if((Math.sqrt(arr[i])%1) > 0)continue;

This script output numbers from array which square roots is integer.

Labels[edit | edit source]

Labels help use break and continue in nested loops.

    if(i==j)continue glob;
    print(i*10 + j)

Do .. While and For .. in loops · Logic and Comparison operators

Logic and Comparison operators

Logic operators[edit | edit source]

There 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[edit | edit source]

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; //True
5 === '5'; //False
5 != 3; //True
5 !== '3'; //True
5 > 3; //True
5 < 3; //False
5 <= 5; //True
5 >= 3; //True

XOR Hack[edit | edit source]

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){
  return Boolean(a ^ b)

And let's use it.

xor(true,false); //True
xor(true,true); //False
xor(false,false); //False

Break, continue, labels · Condition operator

Condition operator

Conditional operator[edit | edit source]

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 expression
  name = "Tom";
  name = "Artem";

//Conditional operator
name = cond?"Tom":"Artem";

Nested conditional operator[edit | edit source]

As 'if' expression so and Conditional operator can be multiple.

name = "Artiom";
cond1 = false;
cond2 = true;

//Conditional operator
name = cond1?"Tom":cond2?"Artem":"NoName"

Logic and Comparison operators · Switch expression