Вы находитесь на странице: 1из 105

JavaScript Basics

JavaScript was initially created to “make web


pages alive”.

The programs in this language are called scripts.


They can be written right in a web page’s HTML
and executed automatically as the page loads.
JavaScript Basics
JavaScript can execute not only in the browser,
but also on the server, or actually on any device
that has a special program called the JavaScript
engine.

The browser has an embedded engine sometimes


called a “JavaScript virtual machine”.
JavaScript Basics
Different engines have different “codenames”. For
example:

V8 – in Chrome and Opera


SpiderMonkey – in Firefox
ChakraCore – in Microsoft Edge
Nitro & SquirrelFish – in Safari
JavaScript Basics
Different engines have different “codenames”. For
example:

V8 – in Chrome and Opera


SpiderMonkey – in Firefox
ChakraCore – in Microsoft Edge
Nitro & SquirrelFish – in Safari
How do engines work?
Engines are complicated. But the basics are easy.

● The engine (embedded if it’s a browser) reads


(“parses”) the script.
● Then it converts (“compiles”) the script to the
machine language.
● And then the machine code runs, pretty fast.
How do engines work?

The engine applies optimizations at each step of


the process. It even watches the compiled script
as it runs, analyzes the data that flows through it,
and applies optimizations to the machine code
based on that knowledge. When it’s done, scripts
run quite fast.
What can in-browser JavaScript do?
● Add new HTML to the page, change the existing content,
modify styles.
● React to user actions, run on mouse clicks, pointer
movements, key presses.
● Send requests over the network to remote servers,
download and upload files (so-called AJAX and COMET
technologies).
● Get and set cookies, ask questions to the visitor, show
messages.
● Remember the data on the client-side (“local storage”).
What CAN’T in-browser JavaScript do?
● JavaScript on a webpage may not read/write arbitrary
files on the hard disk, copy them or execute programs. It
has no direct access to OS system functions.
● Different tabs/windows generally do not know about each
other. Sometimes they do, for example when one window
uses JavaScript to open the other one. But even in this
case, JavaScript from one page may not access the other if
they come from different sites
● JavaScript can easily communicate over the net to the
server where the current page came from. But its ability to
receive data from other sites/domains is crippled.
What CAN’T in-browser JavaScript do?
● JavaScript on a webpage may not read/write arbitrary
files on the hard disk, copy them or execute programs. It
has no direct access to OS system functions.
● Different tabs/windows generally do not know about each
other. Sometimes they do, for example when one window
uses JavaScript to open the other one. But even in this
case, JavaScript from one page may not access the other if
they come from different sites
● JavaScript can easily communicate over the net to the
server where the current page came from. But its ability to
receive data from other sites/domains is crippled.
Lets checkout some examples.

Hello, World!
Script Tag
Importance of semicolon
"use strict"
1) The "use strict" directive switches the engine to the
“modern” mode, changing the behavior of some built-in
features
2) Strict mode is enabled by placing "use strict" at the top of
a script or function.
3) Strict mode is supported by all modern browsers.
4) We recommended always starting scripts with "use strict".
"use strict"

(function() {
"use strict"; 'use strict';
// this code works the // ...your code...
modern way
... })()
variables
let user = 'John'; const RED = "#F00";
let age = 25; const GREEN = "#0F0";
const BLUE = "#00F";
let message = 'Hello'; const ORANGE = "#FF7F00";

let user = 'John',


age = 25,
message = 'Hello';
variables
There are two limitations on variable names in
JavaScript:

● The name must contain only letters, digits, or


the symbols $ and _.
● The first character must not be a digit.
Let vs Var

var is function scoped and let is block scoped


var declarations are processed when the function starts
(or script starts for globals).
function sayHi() { function sayHi() {
phrase = "Hello"; var phrase;

alert(phrase); phrase = "Hello";

var phrase; alert(phrase);


} }
Data Types
typeof undefined // "undefined"

typeof 0 // "number"

typeof true // "boolean"

typeof "foo" // "string"

typeof Symbol("id") // "symbol"

typeof Math // "object" (1)


Type Conversion

let value = true;


alert(typeof value); // boolean

value = String(value); // now value is a string "true"


alert(typeof value); // string
Type Conversion

let str = "123";


alert(typeof str); // string

let num = Number(str); // becomes a number 123

alert(typeof num); // number


Type Conversion

let age = Number("an arbitrary string instead of a number");

alert(age); // NaN, conversion failed


Type Conversion
value becomes

undefined NaN

null 0

True and False 1 and 0

string Whitespaces from the start and end are


removed. If the remaining string is empty,
the result is 0. Otherwise, the number is
“read” from the string. An error gives NaN.
Type Conversion

alert( Boolean(1) ); // true


alert( Boolean(0) ); // false

alert( Boolean("hello") ); // true


alert( Boolean("") ); // false
Type Conversion

alert( Boolean("0") ); // true


alert( Boolean(" ") ); // spaces, also true (any non-empty string
is true)
Type Conversion

alert( Boolean("0") ); // true


alert( Boolean(" ") ); // spaces, also true (any non-empty string
is true)
Type Conversion

0, null, undefined, NaN, "" becomes false


any other value becomes true
Prompt, confirm & alert

alert("Hello");

The function prompt accepts two arguments:


result = prompt(title[, default]);

result = confirm(question);
While loop
let i = 0;

while (i < 3) {
alert( i );
i++;
}
for loop

for (let i = 0; i < 3; i++) {


alert(i);
}
Do while loop
let i = 0;

do {
alert( i );
i++;
} while (i < 3);
Break and Continue in loops
let sum = 0;

for (let i = 0; i < 10; i++) {


while (true) {
let value = +prompt("Enter a num", '');
if (!value) break; // (*) if (i % 2 == 0) continue;
sum += value;
} alert(i); // 1, then 3, 5, 7, 9
alert( 'Sum: ' + sum );
}
Break All Loop
outer: for (let i = 0; i < 3; i++) {

for (let j = 0; j < 3; j++) {


let input = prompt(`Value at coords (${i},${j})`, '');

// if an empty string or canceled, then break out of both loops


if (!input) break outer; // (*)
}
}
alert('Done!');
Switch Case
let a = 2 + 2;

switch (a) {
case 3:
alert( 'Too small' );
break;
case 4:
alert( 'Exactly!' );
break;
default:
alert( "I don't know such values" );
}
Functions
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable

alert( message );
}

showMessage(); // Hello, I'm JavaScript!


Function Parameters
function showMessage(from, text) {
from = '*' + from + '*';
alert( from + ': ' + text );
}

let from = "Ann";


showMessage(from, "Hello");
Function Expression
function sayHi() { // (1) create
alert( "Hello" );
}

let func = sayHi; // (2) copy

func(); // Hello // (3) run the copy (it works)!


sayHi(); // Hello // this still works too
Object
let user = {
name: "John",
age: 30,
"likes birds": true // multiword property name
must be quoted
};
Object
let user = new Object();

let user = {
name: "John",
age: 30
};
property of an Object

delete user.age;

user.likes birds = true

user["likes birds"] = true;


For..in loop
let user = {
name: "John",
age: 30,
isAdmin: true
};

for(let key in user) {


alert( key ); // name, age, isAdmin
alert( user[key] ); // John, 30, true
}
Primitive Methods

let str = "Hello";


alert( str.toUpperCase() ); // HELLO

let n = 1.23456;
alert( n.toFixed(2) ); // 1.23
Data Types: Number
let billion = 1000000000;
let billion = 1e9; // 1 billion, literally: 1 and 9
zeroes

let ms = 0.000001;
let ms = 1e-6; // six zeroes to the left from 1
Data Types: Number
alert( 0xff ); // 255
alert( 0xFF ); // 255 (the same, case doesn't matter)

let a = 0b11111111; // binary form of 255


let b = 0o377; // octal form of 255

alert( a == b ); // true, the same number 255 at both sides


Data Types: Number
The method num.toString(base) returns a string
representation of num in the numeral system with
the given base.

let num = 255;


alert( num.toString(16) ); // ff
alert( num.toString(2) ); // 11111111
Data Types: Number
Please note that two dots in 123456..toString(36)
is not a typo. If we want to call a method directly
on a number, like toString, then we need to place
two dots .. after it.

alert( 123456..toString(36) );
Data Types: Number

Math.floor
Rounds down: 3.1 becomes 3, and -1.1 becomes
-2.

Math.ceil
Rounds up: 3.1 becomes 4, and -1.1 becomes -1.
Data Types: Number
Math.round
Rounds to the nearest integer: 3.1 becomes 3,
3.6 becomes 4 and -1.1 becomes -1.

Math.trunc (not supported by Internet Explorer)


Removes anything after the decimal point
without rounding: 3.1 becomes 3, -1.1 becomes -1.
Data Types: Number
The method toFixed(n) rounds the number to n
digits after the point and returns a string
representation of the result.

let num = 12.36;


num.toFixed(1); // "12.4"
Data Types: String

let single = 'single-quoted';

let double = "double-quoted";

let backticks = `backticks`;


Data Types: String

let single = 'single-quoted';

let double = "double-quoted";

let backticks = `backticks`;


Data Types: String
let guestList = `Guests:
* John
* Pete
* Mary
`;

alert(guestList); // a list of guests, multiple lines


Data Types: String

let guestList = "Guests:\n * John\n * Pete\n *


Mary";

alert(guestList); // a multiline list of guests


Data Types: String

The length property has the string length:

alert( `My\n`.length ); // 3

Please note that str.length is a numeric property, not a


function. There is no need to add parenthesis after it.
Data Types: String
let str = `Hello`;

// the first character


alert( str[0] ); // H
alert( str.charAt(0) ); // H

// the last character


alert( str[str.length - 1] ); // o
Data Types: String
let str = `Hello`;

alert( str[1000] ); // undefined


alert( str.charAt(1000) ); // '' (an empty string)
Data Types: String
Strings are immutable
let str = 'Hi';

str[0] = 'h';
alert( str[0] ); // doesn't work
Data Types: String
let str = 'Hi';

str = 'h' + str[1]; // replace the string

alert( str ); // hi

The usual workaround is to create a whole new string and


assign it to str instead of the old one.
Data Types: String

alert( 'Interface'.toUpperCase() ); // INTERFACE


alert( 'Interface'.toLowerCase() ); // interface
Data Types: String
Searching for a substring

let str = 'Widget with id';

alert( str.indexOf('Widget') ); // 0, because 'found at the beginning


alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive

alert( str.indexOf("id") ); // 1, "id" is found at the position 1 (..idget with id)


Data Types: String

str.lastIndexOf(substr, position)

There is also a similar method str.lastIndexOf(substr,


position) that searches from the end of a string to its
beginning.

It would list the occurrences in the reverse order.


Data Types: String

alert( "Widget with id".includes("Widget") ); // true


alert( "Hello".includes("Bye") ); // false

alert( "Midget".includes("id") ); // true


alert( "Midget".includes("id", 3) ); // false, from
position 3 there is no "id"
Data Types: String

alert( "Widget".startsWith("Wid") ); // true,


"Widget" starts with "Wid"

alert( "Widget".endsWith("get") ); // true, "Widget"


ends with "get"
Data Types: String

Getting a substring

There are 3 methods in JavaScript to get a


substring: substring, substr and slice.
Data Types: String

let str = "stringify";


alert( str.slice(0, 5) ); // 'strin', the substring from 0
to 5 (not including 5)
alert( str.slice(0, 1) ); // 's', from 0 to 1, but not
including 1, so only character at 0
Data Types: String
str.substring(start [, end])

Returns the part of the string between start and


end.

This is almost the same as slice, but it allows start


to be greater than end.
Data Types: String
let str = "stringify";

// these are same for substring


alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring"

// ...but not for slice:


alert( str.slice(2, 6) ); // "ring" (the same)
alert( str.slice(6, 2) ); // "" (an empty string)
Data Types: String
str.substr(start [, length])

Returns the part of the string from start, with the


given length.

In contrast with the previous methods, this one


allows us to specify the length instead of the ending
position:
Data Types: String
let str = "stringify";
alert( str.substr(2, 4) ); // ring, from the 2nd position get 4
characters

The first argument may be negative, to count from the end:

let str = "stringify";


alert( str.substr(-4, 2) ); // gi, from the 4th position get 2
characters
Data Types: String

truncate("Hi everyone!", 20) = "Hi everyone!"


Data Types: Array
let arr = new Array();
let arr = [];

let fruits = ["Apple", "Orange", "Plum"];


alert( fruits[0] ); // Apple
alert( fruits[1] ); // Orange
alert( fruits[2] ); // Plum
Data Types: Array

We can replace an element:

fruits[2] = 'Pear'; // now ["Apple", "Orange", "Pear"]


Data Types: Array
n array can store elements of any type.

For instance:

// mix of values
let arr = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ];

// get the object at index 1 and then show its name


alert( arr[1].name ); // John

// get the function at index 3 and run it


arr[3](); // hello
Data Types: Array
pop

Extracts the last element of the array and returns it:

let fruits = ["Apple", "Orange", "Pear"];

alert( fruits.pop() ); // remove "Pear" and alert it

alert( fruits ); // Apple, Orange


Data Types: Array
push

Append the element to the end of the array:

let fruits = ["Apple", "Orange"];

fruits.push("Pear");

alert( fruits ); // Apple, Orange, Pear


Data Types: Array
shift

Extracts the first element of the array and returns it:

let fruits = ["Apple", "Orange", "Pear"];

alert( fruits.shift() ); // remove Apple and alert it

alert( fruits ); // Orange, Pear


Data Types: Array
unshift

Add the element to the beginning of the array:

let fruits = ["Orange", "Pear"];

fruits.unshift('Apple');

alert( fruits ); // Apple, Orange, Pear


Data Types: Array
Methods push and unshift can add multiple elements at once:

let fruits = ["Apple"];

fruits.push("Orange", "Peach");
fruits.unshift("Pineapple", "Lemon");

// ["Pineapple", "Lemon", "Apple", "Orange", "Peach"]


alert( fruits );
Data Types: Array
let fruits = ["Banana"]

let arr = fruits; // copy by reference (two variables reference the same array)

alert( arr === fruits ); // true

arr.push("Pear"); // modify the array by reference

alert( fruits ); // Banana, Pear - 2 items now


Data Types: Array
let arr = new Array(2); // will it create an array of
[2] ?

alert( arr[0] ); // undefined! no elements.

alert( arr.length ); // length 2


Data Types: Array

So, the simplest way to clear the array is:


arr.length = 0;
Data Types: Array
splice

How to delete an element from the array?

The arrays are objects, so we can try to use delete:

let arr = ["I", "go", "home"];


delete arr[1]; // remove "go"
alert( arr[1] ); // undefined
// now arr = ["I", , "home"];
alert( arr.length ); // 3
Data Types: Array
The arr.splice(str) method is a swiss army knife
for arrays. It can do everything: add, remove and
insert elements.

The syntax is:

arr.splice(index[, deleteCount, elem1, ..., elemN])


Data Types: Array
arr.splice(index[, deleteCount, elem1, ..., elemN])

It starts from the position index: removes


deleteCount elements and then inserts elem1, ...,
elemN at their place. Returns the array of
removed elements.
Data Types: Array
Let’s start with the deletion:

let arr = ["I", "study", "JavaScript"];

arr.splice(1, 1); // from index 1 remove 1 element

alert( arr ); // ["I", "JavaScript"]


Data Types: Array
we remove 3 elements and replace them with the other two:

let arr = ["I", "study", "JavaScript", "right", "now"];

// remove 3 first elements and replace them with another


arr.splice(0, 3, "Let's", "dance");

alert( arr ) // now ["Let's", "dance", "right", "now"]


Data Types: Array
Here we can see that splice returns the array of removed elements:

let arr = ["I", "study", "JavaScript", "right", "now"];

// remove 2 first elements


let removed = arr.splice(0, 2);

alert( removed ); // "I", "study" <-- array of removed elements


Data Types: Array
The splice method is also able to insert the elements without any removals. For
that we need to set deleteCount to 0:

let arr = ["I", "study", "JavaScript"];

// from index 2
// delete 0
// then insert "complex" and "language"
arr.splice(2, 0, "complex", "language");

alert( arr ); // "I", "study", "complex", "language", "JavaScript"


Data Types: Array
The method arr.concat joins the array with other
arrays and/or items.

The syntax is:

arr.concat(arg1, arg2...)
Data Types: Array
let arr = [1, 2];

// merge arr with [3,4]


alert( arr.concat([3, 4])); // 1,2,3,4

// merge arr with [3,4] and [5,6]


alert( arr.concat([3, 4], [5, 6])); // 1,2,3,4,5,6

// merge arr with [3,4], then add values 5 and 6


alert( arr.concat([3, 4], 5, 6)); // 1,2,3,4,5,6
Data Types: Array
let arr = [1, 2];

let arrayLike = {
0: "something",
length: 1
};

alert( arr.concat(arrayLike) ); // 1,2,[object Object]


//[1, 2, arrayLike]
Data Types: Array
The arr.forEach method allows to run a function for every element of the array.
The syntax:

arr.forEach(function(item, index, array) {


// ... do something with item
});

For instance, this shows each element of the array:


// for each element call alert
["Bilbo", "Gandalf", "Nazgul"].forEach(alert);
Data Types: Array
Searching in array

These are methods to search for something in an array.


indexOf/lastIndexOf and includes

The methods arr.indexOf, arr.lastIndexOf and arr.includes have the same syntax and do
essentially the same as their string counterparts, but operate on items instead of characters:

arr.indexOf(item, from) looks for item starting from index from, and returns the index
where it was found, otherwise -1.
arr.lastIndexOf(item, from) – same, but looks from right to left.
arr.includes(item, from) – looks for item starting from index from, returns true if found.
Data Types: Array
find and findIndex

Imagine we have an array of objects. How do we find an object with the specific condition?

Here the arr.find method comes in handy.

The syntax is:

let result = arr.find(function(item, index, array) {


// if true is returned, item is returned and iteration is stopped
// for falsy scenario returns undefined
});
Data Types: Array
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];

let user = users.find(item => item.id == 1);

alert(user.name); // John
Data Types: Array
filter
The find method looks for a single (first) element that makes the function return
true.
If there may be many, we can use arr.filter(fn).
The syntax is similar to find, but filter continues to iterate for all array elements
even if true is already returned:

let results = arr.filter(function(item, index, array) {


// if true item is pushed to results and iteration continues
// returns empty array for complete falsy scenario
});
Data Types: Array
filter
The find method looks for a single (first) element that makes the function return
true.
If there may be many, we can use arr.filter(fn).
The syntax is similar to find, but filter continues to iterate for all array elements
even if true is already returned:

let results = arr.filter(function(item, index, array) {


// if true item is pushed to results and iteration continues
// returns empty array for complete falsy scenario
});
Data Types: Array
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];

// returns array of the first two users


let someUsers = users.filter(item => item.id < 3);

alert(someUsers.length); // 2
Data Types: Array
map
The arr.map method is one of the most useful and often used.
The syntax is:

let result = arr.map(function(item, index, array) {


// returns the new value instead of item
})

It calls the function for each element of the array and returns the array of results.
For instance, here we transform each element into its length:

let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length);


alert(lengths); // 5,7,6
Data Types: Array
sort(fn)
The method arr.sort sorts the array in place.

For instance:
let arr = [ 1, 2, 15 ];

// the method reorders the content of arr (and returns it)


arr.sort();

alert( arr ); // 1, 15, 2


Data Types: Array
The items are sorted as strings by default.

Literally, all elements are converted to strings and then compared. So, the lexicographic ordering is applied
and indeed "2" > "15".

To use our own sorting order, we need to supply a function of two arguments as the argument of arr.sort().
The function should work like this:

function compare(a, b) {
if (a > b) return 1;
if (a == b) return 0;
if (a < b) return -1;
}
Data Types: Array
function compareNumeric(a, b) {
if (a > b) return 1;
if (a == b) return 0;
if (a < b) return -1;
}

let arr = [ 1, 2, 15 ];

arr.sort(compareNumeric);

alert(arr); // 1, 2, 15
Data Types: Array
reverse

The method arr.reverse reverses the order of elements in arr.

For instance:

let arr = [1, 2, 3, 4, 5];


arr.reverse();

alert( arr ); // 5,4,3,2,1


Data Types: Array

let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ',


2);

alert(arr); // Bilbo, Gandalf


Data Types: Array
Split into letters

The call to split(s) with an empty s would split the string into
an array of letters:

let str = "test";

alert( str.split('') ); // t,e,s,t


Data Types: Array
The call arr.join(separator) does the reverse to split. It creates a string of arr
items glued by separator between them.

For instance:

let arr = ['Bilbo', 'Gandalf', 'Nazgul'];

let str = arr.join(';');

alert( str ); // Bilbo;Gandalf;Nazgul


Data Types: Array
The call arr.join(separator) does the reverse to split. It creates a string of arr
items glued by separator between them.

For instance:

let arr = ['Bilbo', 'Gandalf', 'Nazgul'];

let str = arr.join(';');

alert( str ); // Bilbo;Gandalf;Nazgul

Вам также может понравиться