Program flow and Data collections

Содержание

Слайд 2

Agenda

Program flow control
- conditions
- loops
- switch statement
Collections
- array

Agenda Program flow control - conditions - loops - switch statement Collections
- hash table

[1]

[2]

Слайд 3

Program Flow Control

Program Flow Control

Слайд 4

Program flow

Operators in a program processed in linear order: from top to

Program flow Operators in a program processed in linear order: from top
bottom and from left to right.
Such sequence is called Program flow.
There are several methods intended to change standard flow. You already know about function. Also JavaScript has conditions, loops and switch statement.

[1]

[2]

Слайд 5

Conditions: if-else

Most of algorithms have situation when next step related of some

Conditions: if-else Most of algorithms have situation when next step related of
conditions depended on previous steps. It's a reason to use if-else statement.

if (condition) {
true branch;
} else {
false branch;
}

if (condition) {
true branch;
}

[1]

[2]

[3]

Слайд 6

Conditions: if-else

Example:

function discount (type) {
if (type === “silver”) {
price

Conditions: if-else Example: function discount (type) { if (type === “silver”) {
*= 0.9;
}
if (type === “gold”) {
price *= 0.85;
}
return price;
}

Function get a parameter with a information about discount. And if discount is "silver" or "gold“, function modifies global variable price.
In this example a shortened form of operator was used.

Слайд 7

Conditions: ?:

Sometimes if-else too bulky. If we need to initialize a variable

Conditions: ?: Sometimes if-else too bulky. If we need to initialize a
modifying it by simple conditions; or we need to return a value from function and this value is dependent on something, we can use ternary
Ternary operator like ?:.

result = (condition)? true action: false action;

Let’s rewrite the last example using ternary operator.

[1]

Слайд 8

Conditions: ?:

function discount (type) {
if (type === “silver”) {
price *=

Conditions: ?: function discount (type) { if (type === “silver”) { price
0.9;
}
if (type === “gold”) {
price *= 0.85;
}
return price;
}

function discount (type) {
price *= (type === “silver”)? 0.9: 1;
price *= (type === “gold”)? 0.85: 1;
return price;
}

We get a more compact but a less readable code. So be careful!

Слайд 9

Loops: for

Loops are used when algorithm requires repeating of statements.
First of them:

Loops: for Loops are used when algorithm requires repeating of statements. First
for - loop with counter

for (start position; repeat condition; step) {
body of loop; // will be repeated
}

One processing of loop’s body is called iteration.

[1]

[2]

[3]

Слайд 10

Loops: while and do-while

Two others types of loops: while and do-while

while (condition)

Loops: while and do-while Two others types of loops: while and do-while
{
body of loop;
}

do {
body of loop;
} while (condition);

The main difference between these loops is the moment of condition calculation. While calculates condition, and if the result is true, while does iteration. Do-while initially does iteration and after that calculates a condition.

[1]

[2]

Слайд 11

Loops: examples

Example 1:

for (var i = 0; i < 5; i++)

Loops: examples Example 1: for (var i = 0; i console.log(“Iteration #
{
console.log(“Iteration # %d”, i + 1);
}

Text with number of current iteration will be print 5 times

Example 2:

while (accumulation < 100) {
accumulation += doSomething();
}

This loop will be repeated until accumulation reaches 100 or gets grater value.

[1]

[2]

Слайд 12

Which type of loop to use?

It may be not so simple to

Which type of loop to use? It may be not so simple
decide which type of loops to use in some specific conditions.
There is a simple rule for loop selection: if we know exact counts of iterations, we use for, if we know only exiting condition we use while or do-while.
While loop we use in most cases when we need to check for condition for each iteration, but sometimes we know that at least one iteration should be executed, so we us do-while in such case.

Слайд 13

Loops: break and continue

There are two keywords for loops control :
break

Loops: break and continue There are two keywords for loops control :
– aborts loop and moves control to next statement after the loop;
continue – aborts current iteration and immediately starts next iteration.
Try not to use this keywords. A good loop have one entering point, one condition and one exit.

Слайд 14

Switch

Switch statement allows to select one of many blocks of code to

Switch Switch statement allows to select one of many blocks of code
be executed. If all options don’t fit, default statements will be processed

switch (statement) {
case value1: some body;
break;
case value2: some body;
break;
. . .
default: some body;
}

Слайд 15

Switch

Example:

This switch looks for the word equivalent for a mark in

Switch Example: This switch looks for the word equivalent for a mark
the 5-point system
Default statement is not used.

switch (mark) {
case 5: result = “excellent”;
break;
case 4: result = “good”;
break;
case 3: result = “satisfactorily”;
break;
case 2: result = “bad”;
break;
}

Слайд 16

Collections

Collections

Слайд 17

Collections

Collection is a set of variables grouped under common name.
Usually elements of

Collections Collection is a set of variables grouped under common name. Usually
collections are grouped according to some logical or physical characteristic.
Collections help to avoids situations when we have to declare multiple variables with similar names::
var a1, a2, a3, a4…
There are two types of collections that are typical for JS: arrays and hash tables.

Слайд 19

Array: creation

There are two ways to create an array:

var name = [

Array: creation There are two ways to create an array: var name
]; // preferrable
and
var name = new Array()

First way (with using indexer [ ]) is modern and strongly recommended for use.
Second way (with new and Array constructor) is deprecated and not recommended.

[1]

[2]

Слайд 20

Array: processing

Usage of arrays:
var array = [] // declaration of

Array: processing Usage of arrays: var array = [] // declaration of
empty array
var array = [5, 8, 16] // declaration of predefined array
array[0] = 4; // writing value with index 0
tmp = array[2]; // reading value by index (in tmp - 16)
array.length // getting length of array

Слайд 21

Array: processing

In the sample below we output all elements of the array

Array: processing In the sample below we output all elements of the
to the console:

var array = [4, 8, 16, 32], i;
for (i = 0; i < array.length; i++) {
console.log(array[i]);
}

Note: this works only for numerical indexes.

[1]

Слайд 22

Array: features

Arrays in JavaScript differ from arrays in classical languages.
Arrays in

Array: features Arrays in JavaScript differ from arrays in classical languages. Arrays
JS are instances of Object.
So Array in JS can be easily resized, can contain data of different types and have string as an index.
And more: if we create empty array it is real empty. And if we insert element with index 5 into this empty array, we get array with only one element but with length equal to 6!

Слайд 23

Array: length calculation

Let's discuss length calculation.
It’s a virtual property.
Arrays don't review

Array: length calculation Let's discuss length calculation. It’s a virtual property. Arrays
own elements. It takes biggest index, increments it and returns it.
So, if we insert element into an empty array with index 6, property length will take false value – 7!
Avoid such errors to help special methods to insert and delete elements in the array. They correctly handle indexes and do not allow free spaces between them.

Слайд 24

Array: useful methods

Some useful methods of array:
array.push(value) – add element to

Array: useful methods Some useful methods of array: array.push(value) – add element
the end of an array
array.pop() – extract element from end of an array
array.unshift(value) – insert element before first
array.shift() – extract first element
array.join() – concatenate all elements into a string
array.split() – split a string into an array of substrings
array.sort() – built-in method to sort array

Слайд 25

Array: forEach

Not so long ago array received very comfortable method forEach. This

Array: forEach Not so long ago array received very comfortable method forEach.
method circulates around array elements and executes your callback function for each of them.

var array = [4, 8, 16, 32];
array.forEach(function (element, i) {
console.log(element);
});

Слайд 26

Hash Table

Hash Table

Слайд 27

Hash Table: creation

Sometimes we need an Array with string indexes (keys). There

Hash Table: creation Sometimes we need an Array with string indexes (keys).
is a special data structure for such case: hash table.

var name = { };

Hash table is an usual JavaScript object without methods.
To access elements use array syntax with string index instead of numerical index.

Слайд 28

Hash Table: creation

We can create hash and initialize it at the same

Hash Table: creation We can create hash and initialize it at the
time. For this we should write values separated by a comma like in array. But for all values we have to set key:

var name = {
key: value,
key: value
};

This format of describing of JS object has its own name: JavaScript Object Notation or short JSON.

[1]

[2]

Слайд 29

Hash Table: usage

Usage of hash tables is very similar to arrays:
hash[“good”] =

Hash Table: usage Usage of hash tables is very similar to arrays:
4; // writing value in element with key “good”
tmp = hash[“excellent”]; // reading value by key “excellent”
The difference is in usage of for-in statement:

for (key in hash) {
console.log(hash[key]);
}

[1]

Слайд 30

Array vs Hash

Use Array for collections with digital indexes.
Use Hash if you

Array vs Hash Use Array for collections with digital indexes. Use Hash
want use string keys.
Don't look for property length in Hash.
Don't look for forEach and other Array methods in Hash.
Always explicitly declare Array otherwise you get a Hash.
Don't use for with hash, use for-in instead.
At finally : use collection – be cool :)
Имя файла: Program-flow-and-Data-collections.pptx
Количество просмотров: 161
Количество скачиваний: 0