• No results found

Real Time Group JavaScript

N/A
N/A
Protected

Academic year: 2021

Share "Real Time Group JavaScript"

Copied!
198
0
0

Loading.... (view fulltext now)

Full text

(1)

JavaScript

Real Time Group

(2)
(3)

Course Overview

JavaScript was initially created to “make webpages alive”.

JS is the programming language of the web.

The programs in this language are called scripts. They can be written right in the HTML or in outsource file and execute automatically as the page loads.

Mostly JS code is responsible for the interaction of the website to the visitor, making the website dynamic. Meaning the website reacting and changing when user does something - we can look at it as a conversation.

Furthermore JS is capable of more actions like adding and removing content, downloading new content after the page loaded with AJAX.

Modern JS frameworks and libraries extends JS capabilities once more to reach the hard drive files, execute and run other programs and much more.

(4)

About Javascript

Javascript in-browser capabilities:

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 (AJAX).

Get and set cookies, ask questions to the visitor, show messages.

Remember the data on the client-side (“local storage”).

(5)

About Javascript

Javascript in-browser limitations:

Javascript on a webpage cannot read or write to the hard disk or to execute other programs.

There are ways to interact with camera/microphone and other devices, but they require a user’s explicit permission.

Different browser windows generally do not know about each other and run

separately. Meaning different windows cannot interact between them. This is because of a security concern “Same Origin Policy”. This will help us stop other websites to mess with our own. To enable interaction special JS code needed.

Javascript can easily communicate with other server over the web, but for security reasons we must strictly allow these connections.

(6)

About Javascript

Such limits do not exist if JavaScript is used outside of the browser, for example on a

server. Modern browsers also allow installing plugin/extensions which may get extended permissions.

When using Javascript outside the webpage like on a server, these restrictions does not exist, allowing us to extend our application capabilities.

(7)

About Javascript

What makes javascript so widely used?

JS is the only language that is supported by all major browsers and enabled by default.

Furthermore it is fully integration with HTML and CSS and very simple to learn and use.

All these make JS the only fully working solution.

JS has some other languages wrapping around to change some of the way it works like syntax. Some may prefer to use them as an alternate option.

(8)

Code Structures

(9)

Code Structures

Statements:

Are JS commands that perform actions. As JS is a scripting language, most of it built with code blocks of commands to perform actions.

For example :

alert(“Im a command”);

This is a statement = command to alert a user with some data. In our case it will print the user with the text: ‘I’m a command’.

JS file will contain blocks of statements that return some results. We will see a more complicated code soon.

(10)

Code Structures

Semicolons:

Even though semicolons are not necessary have to present at the end of the command it is a good practice. First we should use semicolons to prevent situations of unpredicted results when commands merge one to each other.

Second, usually we won't be the only one touching this code. Others would better understand where some command ends if we will keep the semicolons there.

And of course the main reason to use them is because js requires them to present to read a command properly.

(11)

Code Structures

Comments:

Comments is a good friend of every developer to explain some of the code or how it works inside our JS file. Commenting may reduce time remembering where you stopped, what was your last thought about the code or to give credits to a file.

Commands usage:

let a = 5; // Im a comment /*

Hi,

Im a block of comments

*/

let a = 5;

JS will skip those lines and will not execute its content, which is another use for comments

(12)

Variables and Data

(13)

Variables and Data

Most of the time, JS will have to save data and reuse it somewhere else.

Variables are named storages to keep our data at and then use it in different even multiple different places.

To create a variable we use the let keyword.

let a;

In the example we have created a variable a.

Now we can put some data in it with =.

For example:

a = 5;

(14)

Variables and Data

Now the variable a has a value of 5. And if we multiply it by 2 we will get:

let a = 5;

alert(a * 2); // 10

Note that we don’t have to use the keyword let each time. Only at the creation process.

Assigning another value to the variable.

let a = 5;

a = 10;

alert(a * 2); // 20

Note that the result now is 20 because we assigned a new value to variable a.

(15)

Variables and Data

We can also declare two variables and copy their values between each other.

let a = 5, b;

b = a;

alert(a * 2); // 10 alert(b * 2); // 10

Now both variables a and b will have same value;

(16)

Variables and Data

Variables names may contain almost any character, and still there are some restrictions.

First, variables must contain only letters, digits and two symbols $ and _.

Second the variable name cannot start with a digit.

let 1a; // cannot start with digit

let my-name; // a hyphen ‘-’ is not allowed

Next note on variable naming is case sensitivity.

let name;

let Name;

The above variables are not the same.

(17)

Variables and Data

Another important note is reserved names. We cannot name a variable with the keyword

“let” for example.

let let = 5;

We must create new names for our variables so we will not break any existing JS native code.

(18)

Variables and Data

Constants:

If you want to create a variable which value you wont need to change later, you can use constant variable.

Usage:

const a = 10;

This variable now will not let you change its value.

UpperCase constants is widely used to declare prior development constants for easier work-flow.

const COLOR_RED = ‘#347522’;

It is easier to remember COLOR_RED than #347522.

It is good practice to name your variables in human readable syntax to better understand what is going on in the code.

(19)

Variables and Data

More on Data and Types:

Variable in JS can contain any data. You can assign a text to a variable and then receive a numeric value.

let words = “hello”;

words = 123;

alert(words); // 123

Every variable can store any type of data, and there is 4 of types to know:

Integer - as a full number - (like: 5)

Float - as a number with floating point - (like: 1.5) Boolean - as a true or false - (like: false)

Object - is the main data type of JS. it can be used in many ways:

String - as a text data - (like: ‘example’)

Function - as a block of commands - (like function myFunc() {}) Array - as a list of items - (like [1,2,3,4])

Object - as a list of items and their values - (like: { name: ‘John’, last: ‘Doe’}) More on Data and Types:

Variable in JS can contain any data. You can assign a text to a variable and then receive a numeric value.

(20)

Variables and Data

Each data type has its own built-in methods in JS that can help us work with them.

Important Note: JS will try to convert data types for you if you will try to execute some command with them if needed. For example:

let magic = “5”;

let num = 2;

alert(magic * num); // 10

Note that JS converted the string to a number and executed math operation on both numbers. Writing a clean and understandable code is very important in JS to avoid unwanted results from JS.

Converting data types manually is straightforward:

let num = 5;

num = String(num);

This will convert the number to a string. You can convert it same way to any type:

(21)

Operators

(22)

Operators

Operators known to us all as a mathematical addition +, multiplication *, division / and a subtraction -.

Simple example:

let num = 5;

let num2 = 3;

num * num2; // 15 num + num2; // 8 num - num2; // 2

num / num2; // 1.6666

Note that the last operator result is a float because of JS conversion.

(23)

Operators

You can use operator + on strings as-well. This way we will merge the two strings to one.

let text = “Hello”;

let text2 = “ World”;

text + text2; // Hello World

Note that other operators will convert the string to a number or will not work at all.

(24)

Operators

Remainder %

Using this operator we are receiving the remaining number of an operation.

For example:

alert(8 % 3); // remainder is 2 alert(6 % 3); // remainder is 0

Note the result will be only the remainings of the operation.

(25)

Operators

Exponentiation **

Using this operator we will multiply the number given n number of times.

alert(5 ** 2); // 25

alert(10 ** 3); // 1000

(26)

Operators

Increment/decrement:

In JS it is really simple to increment or decrement value of a variable. To accomplish the result all we need is a double operator ++ or --.

For example:

let num = 2;

alert( num++ ); // 3 alert( num-- ); // 1

These operations is widely used in many projects for example to iterate some list of data, or to control a loop.

(27)

Operators

Bitwise operators:

Bitwise operators treat arguments as 32-bit integer numbers and work on the level of their binary representation.

These operators are not JavaScript-specific. They are supported in most programming languages.

The list of operators:

AND ( & ) OR ( | ) XOR ( ^ ) NOT ( ~ )

LEFT SHIFT ( << ) RIGHT SHIFT ( >> )

ZERO-FILL RIGHT SHIFT ( >>> )

These operators is used the same as in any other programming language and mostly will be found in a function and act as some check system to route the code flow.

(28)

Operators

Modify-in-place:

Using this method we can shorten our code to complete the same results.

For example:

let num = 2;

alert( num++ ); // 3 alert( num-- ); // 1

(29)

Comparisons

Most of the comparison operators we all already know:

Greater/Less than: a > b , a < b

Greater/Less Than or equals: a >= b , a <= b

Equality check is written with two == , because one = is used for assignment.

Not Equal is written with exclamation sign before != .

The result of these operators will be ea boolean type. Meaning it will return True or False.

Example:

alert(3 > 2); // true alert(1 > 2); // false

(30)

Comparisons

We can also compare strings. JS compares strings letter by letter to find the greater value in a string.

alert(“Z” > ”A”); // true

alert(“Be” > “Bee”); // false

In the second example, the comparison method checked the first two letter to be equal, but the third letter is missing from the second word meaning the first word is greater.

(31)

Comparisons

Comparing different types

When comparing different types, JS converts them to numbers.

Example:

alert(“2” > 1); // true alert(“01” > 1); // false alert(true == 1); // true

All data types here were converted to numbers to compare.

(32)

Comparisons

Strict Equality:

JS offers another equality operator === . this operator compares two values without letting JS to convert them. Meaning this will be the safest compare method if not intended

otherwise.

Example:

alert(0 === false); // false

In this case, JS does not convert the values leaving them two different types. Therefore we cannot compare them.

(33)

Comparisons

Comparing null and undefined:

Lets test them first: alert(null === undefined); // false alert(null == undefined); // true

In the first example, we can see that without converting the values are not same type and cannot be compared.

In the second example we see that JS knows how to compare them if it can convert them although the operands have no value at all.

As we stated before, JS will convert data types to numbers to compare them.

Null will be 0 and undefined will be NaN meaning it doesn't equal to nothing.

Special Note:

Don’t use comparisons >= > < <= with a variable which may be null/undefined, unless you are really sure what you’re doing. If a variable can have such values, then check for them

(34)

Conditional operators

Sometimes we need to perform different operations based on a condition.

There is two ways to check such conditions in JS.

The first one is IF statement:

If statement gets a condition, evaluates it and if the result is true executes the code.

Example:

if(month === “January”) alert(“its my birth month”)

In the example above, if the variable month will be equal to January it will show the alert otherwise nothing will happen.

We can write any amount of code to run if the result will be true inside {}.

(35)

Conditional operators

Another option is when the result is false to execute some other operations instead.

Example:

if(month === “January”) {

alert(“Its my birth month!”);

alert(“Such Fun”);

} else {

alert(“Waiting to January”);

}

In this example, if the month will not be equal to ‘January’ the else statement will execute its block of code instead.

(36)

Conditional operators

We can also write several if and else statements like so:

if(month === “January”) {

alert(“Its my birth month!”);

} else if(month === “December”) { alert(“January is close”);

} else {

alert(“January is far away”);

}

We can write as many conditions we want to get the correct results.

(37)

Conditional operators

Ternary operator ?:

Sometimes we want to assign a variable depending on some condition. We could do it with if and else statements but ternary condition is a shorter solution.

Example:

let birthday = month === “January” ? “Yes” : “No”;

Is this example we will get Yes if the month is January or No if anything else.

(38)

Logical operators

In JS we have three logical operators: | | OR, && AND, ! NOT.

OR operator is looking for the first result that is true. Meaning it will evaluate every

condition until it will find a result of true. Then it will stop and execute the code without carrying about the rest of the conditions.

let hour = 9;

if(hour < 10 || hour > 18) {

alert(“The office is closed.”);

}

As you can see, our variable does not fit in any of the conditions and therefore will not

(39)

Logical operators

Interesting rule about OR operator is whenever none of the conditions of OR operator is true, it will return the last parameter.

For example:

let user1 = null;

let user2 = 0;

let age = user1 || user2 || “unborn”;

alert(age);

Both user1 and user2 result to false so the result of age will be ‘unborn’ its last parameter.

(40)

Logical operators

AND operator is looking for the first false result. If it finds one, it will not execute the code otherwise if there is only true results the code will be executed.

For example:

alert(1 && 2 && null && 3); // null is returned alert(1 && 2 && 3); // last value is returned

We can see that the first false value is returned else it will return the last true value.

(41)

Logical operators

We can use those statements like so too: let num1 = 2; let num2 = 3;

if(num1 > 0 || num2 > 0) { alert(“Something”);

}

if(num1 > 0 && num2 > 0) { alert(“Something”);

}

if(num1 === 0 && num2 > 0) {

alert(“Something”);

} First example will return true for both

statements therefore will alert.

Second example will also be true and will alert.

Third example is not true which will stop alert from being fired.

(42)

Logical operators

NOT is a simple operator that converts the statement to be opposite of what it is.

Example:

alert( !true ); // false alert( !0 ); // true

We can use it as-well in a blockchain like so:

if( !0 && !false ) {

alert(“Everything is true”);

}

(43)

Loops

(44)

Loops

Loops are a way to repeat same block of code multiple times.

For example we can use loop to iterate some list of items and return each after another.

Sometimes we can use loops to search for a value in an object and so on.

While loop is a simple loop that will run until the condition set to false.

(45)

Loops

Example:

let count = 10;

while(count > 0) {

alert(“Working”);

count--;

}

In this example, we will see 10 alerts because each time it runs the same code, the value of count is decreased by 1. Meaning after 10 times count will be equal to 0 and return false in the upper statement.

(46)

Loops

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

}

For loop is more advanced loop that gets start value, condition and a step.

Lets see:

In this example, we declare a variable with a starting value of 0. Next the loop will check the condition which will be true because 0 < 10. Now the code block of the loop will be ran once. In the end it will step once with i++ to be 1.

It will repeat this code 10 times.

(47)

Loops

let i = 0;

for(; i<10; i++) { alert(i);

}

We can omit any of the for loop parts. For example:

let i = 0;

for(; i<10;) { alert(i++);

}

(48)

Loops

Normally loop end when the condition is set to false. But what if we want to stop it forcely?

With the use of break and continue we can.

If break is used, it will stop the loop and keep reading the code right after it.

If continue used, it will skip the following iteration and start the next one.

Example:

for(let i=0; i<10; i++) { if(i > 5) break;

alert(i);

}

(49)

Loops

for(let i=0; i<10; i++) { if(i > 5) continue;

alert(i);

}

In this example, we will skip all the iterations above 5th and still see only 5 alerts.

Loops are widely used and probably will present in your projects. There may be many uses for each loop, but understanding its parts will get you running.

(50)

Switch statement

switch(x) {

case “value1”:

break;

case “value2”:

break;

default:

...

Switch is a replacement of if statement if you need more descriptive option.

Switch has one or more case blocks. Each block is executed when its case meets the condition at the top.

For example:

(51)

Switch statement

switch(“1”) { case 1:

break;

}

Receiving a value, we can search for a case which meet its value to execute the wanted piece of block.

Switch statement is very strict about data types and if the value in switch will not exactly match any case the default will execute.

Example:

In this example, the given ‘1’ is a string which is not equals to 1 which is a number.

In this case the default code will execute.

(52)

Functions

(53)

Functions

function sayHi() { alert(“Hi”);

}

Often we need to execute the same block of code multiple times to show messages to the visitor, react to events and more. JS offers us functions for exactly this reason.

We already seen functions like alert(‘’) . for example:

First we give the function a name, then parameters if needed and then the body of the function.

Now whenever we want, we can call sayHi() from any place in the code to execute exactly those lines.

This way we also evade code duplication.

(54)

Functions

let name = “John”;

function sayHi() {

alert(“Hi” + name);

}

Variables created inside a function are only visible to it. Meaning that anything inside the function is private and only the return value of the function is visible.

Functions on the other hand can read outer variables for example:

The variable name in the example above called global variable because it was declared outside of all functions.

(55)

Functions

function sayHi(name, age) {

alert(“Hi” + name + “, is your age is“ + age +

“?”);

}

Functions can accept parameters before running, this way it works like a factory something gets in and the result going out. This way we can reuse our function from multiple places.

Example:

In this example, we passed two parameters to the function, now we can use them to execute with functions code.

As seen above we edited the sentence with the values given as parameters.

(56)

Functions

function sayHi(name, age = 30) {

alert(“Hi” + name + “, is your age is“ + age + “?”);

}

sayHi(name);

If we will call the function without providing the parameters, they will become undefined.

The function will not break, but the result may be unwanted.

In this case, we can use default values to parameters without values.

For example:

Once the function will be called with only the name parameter, the age parameter now will take the default value of 30.

(57)

Functions

function sayHi(name, age = 30) {

alert(“Hi” + name + “, is your age is“ + age + “?”);

return name + “is really ” + age;

}

sayHi(name);

Functions may return a result value of the body block. For example:

In this case, the function will return the string for use for anybody who will call the function.

(58)

Functions

function sayHi(name, age = 30) {

alert(“Hi” + name + “, is your age is“ + age + “?”);

if(age < 25) {

return name + “ is not qualified”;

} else {

return name + “ got to the next level”;

} }

sayHi(name);

Return will stop the execution of the function and pass the result. That’s why we can have multiple returns to stop the function when needed result is found.

Example:

As you can see, we can return different result on each condition.

Leaving the return empty will cause the function to return undefined.

Return; // = return undefined.

(59)

Functions

let func = function sayHi() { alert(“Hi”);

}

Function expressions and arrows

Functions we used before called function declaration. There is another syntax for creating functions called functions expression.

This way we declare a function to a variable to keep it.

Example:

Both functions work the same, create a function and assign it to a value.

Still those functions do differ in some way. When we declare a function, JS will heist it to the top of the page and run it first.

Meaning we will be able to use the function anywhere in the code where with function

(60)

Functions

let name = “John”;

function age() { return 30; } function sayHi(name, age) {

alert(“Hi” + name + “, is your age is ” + age() + “?”);

}

sayHi(name);

Callback functions

Function can also use other functions, this way we can create functions responsible for specific tasks for ease of code and readability. Furthermore there many other reasons like asynchronous flow.

For example:

In this example we received a function as parameter and executed it inside our code to get the value of it.

We can also return a function as a result.

(61)

Functions

let func = (arg1, arg2, ...argN) => expression

Arrow functions

Arrow functions are a shorter version of function expression but often a better approach.

Ist syntax:

We assign a function which receives any number or parameters and evaluates the code and returning the result.

Example:

let sum = (x,y) => x + y;

alert(sum(1,2)); // 3

As you can see its a compact version of:

let sum = function(x,y) { return x + y }

(62)

Functions

let sum = (num1, num2) => { return num1 + num2;

}

To execute a block of code we will use brackets and a regular return value.

Write between the brackets any amount of code you need.

(63)

Arrays

(64)

Arrays

let arr = [1,2,3];

let arr2 = [“John”, “Alex”, “Steve”];

let arr3 = [{ name: “John”, age: 30 }];

Array is a list of items positioned one right after another with an index.

Each item of an array receives an index where it lies.

Array example:

As you can see we can list any data type in our list.

(65)

Arrays

alert( arr2[1] );

To reach an item we need to use an index:

We selected the second element of arr2.

Note element 1 is the second because arrays start with an index of 0.

The total count of items can be reached with:

alert( arr2.length ); // 3

(66)

Arrays

Arrays in JS has some built in methods that help us work with them.

Push: add an item to the end of the list.

Pop: remove an item from the end of the list.

Shift: remove an item from the beginning of the list.

Unshift: add an item to the beginning of the list.

Pop and push working much faster and is more widely used because of their speed and resource management. Shifts has more tasks to do to reach a result therefore more resources and time.

For shift to work it has to delete the first element, then move all the other down 1 index and then update the length.

Arrays are stored in a contiguous memory area which enables it to read data very fast one after another. Although arrays are objects, they work a little different in that manner.

(67)

Arrays

Loop an array

To list all the items of an array we have to use a loop.

For loop example:

let arr = [1,2,3];

for(let i=0; i<arr.length; i++) { alert(arr[i]);

}

We set the starting point of 0 which is the first element of the array. Then we set the check to stop at the last array element by checking it size. And then execute the body to show the element of each index of that array.

(68)

Arrays

Arrays can store arrays too which make them a multidimensional.

For example:

let arr = [ [1,2,3], [4,5,6], [7,8,9]

];

To print 5 for example we now have to:

alert(arr[1,1]);

(69)

Arrays

We can also convert arrays to strings which will return us a comma separated string of the items. For example:

let arr = [1,2,3];

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

alert(String(arr) === “1,2,3”); // true

(70)

Objects

(71)

Objects

As we said earlier, there are seven data types in JS. Six of them are primitive, because their values contain only a single thing (string, number, boolean..)

The only other data type is an object.

Objects are the most widely used data types. Objects have been used in all built in methods and so will be in your code.

The reason why object is not considered a primitive, is because it can store collections of different data types. Meaning an object can store big amounts of data with any data type.

Every data we store inside an object has to get a key.

Then we can use that key to get the exact value we want.

To create an object we use brackets {...} with optional properties. A property is set of a key and its value where key must be a string called “property name”.

(72)

Objects

Think of an object like a cabinet with folders, where each folder contains its own data. And you can reach that data by pulling the folder with the right key(name).

(73)

Objects

There is two syntaxes for creating an empty object:

let user = new Object();

let user = {};

Usually we use the second way for its ease of use.

(74)

Objects

To create an object with data, we can insert it as we create the object:

let user = {

name: ‘John’

age: 30 }

We created new object with 2 properties, each property has a key(name) before the colon

‘:’ and the value after it.

Now we have a user object with two properties:

First property has the name “name” and a value “John”.

Second property has the name “age” and a value “30”.

(75)

Objects

Now you can imagine the cabinet looking like this:

Now we have a stored data that we can reach anytime.

Reaching a property of an object is straightforward:

alert( user.name ); // John alert( user.age ); // 30

(76)

Objects

Now to add another property after the object was created, we can use:

To delete a property, we use delete:

delete user.age;

user.isAdmin = true;

(77)

Objects

To create a property with a multi-word name we must use “”:

let user = {

name: ‘John’, age: 30,

“likes birds”: true }

To create a property with a multi-word name we must use “”:

alert(user.likes birds); // will give an error alert(user[‘likes birds’]); // true

(78)

Objects

We can also access a key with a variable.

let key = ‘likes birds’;

alert( user[key] ); // true

(79)

Objects

Existence Check:

We can check if there is a property in an object before performing some actions.

There will be no error if the property doesn’t exists. It will just return an “undefined”.

To check for a property we have special ‘in’ command:

“key” in object

let user = { name: ‘Diana’, age: 25 }

alert( “name” in user ); // true alert( “other” in user ); // false

(80)

Objects

For..in loop:

To walk over all properties of an object.

let user = {

name: ‘John’, age: 30,

isAdmin: true }

for( let key in user ) {

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

(81)

Objects

Are objects ordered?

To make the properties ordered we must use integer as keys. String keys will be saved by creation time.

Example:

let list = {

“5”: “Apple”,

“2”: “Orange”,

“1”: “Banana”

}

for ( let key in list) { alert( key ); // 1,2,5

let list2 = {

“name”: “John”,

“age”: 30 }

list2.new = “new”;

for (let key in list2) {

alert( key ); // name, age, new }

(82)

Objects

Copying Objects:

One of the fundumental differences of objects vs primitives is that they are stored and copied by reference.

When we copy a primitive it is copying the whole value.

let message = "Hello!";

let phrase = message;

As a result we have two independent variables.

(83)

Objects

Objects are not like that. A variable is saving the address of the object and points to it.

Then if we copy it to another variable, we copy the address to that object.

Leaving us with only one object actually created but two variables pointing to it.

Object is like a cabinet and the variables is the key to it. so when we copy a

variable(object) we actually will duplicate the key to it, but we still have only one cabinet.

(84)

Objects

let user = { name: “John” };

let admin = user;

Now we have two variables pointing to the same address of the object.

Now any of the variables can be used to modify its content.

(85)

Objects

let a = {};

let b = a;

alert( a === b ); // true

Comparison by reference:

Comparison of objects work the same. objects are equal only if they are the same object.

And here is an example for two different objects.

let a = {};

let b = {};

alert( a == b ); // false

(86)

Objects

Other comparisons will not return errors, we will not discuss it here, but you should know that most likely such comparisons are a mistake and are not intended.

obj1 > obj2 or obj == 5

(87)

Objects

Const object:

An object declared as const can be changed. That is working because the const fixes the value of the variable itself, but when we change something in an object, we refer to the address of that object and not the variable itself.

const user = { name: “John”

}

user.age = 25; // Not an error alert(age); // 25

(88)

Objects

As we are changing the value of the object and not the variable.

Now if we will try to set the variable to other object, we will get an error.

const user = { name: “John”

};

// Error, can’t re-assign const variable.

user = {

name: ”Pete”

};

(89)

Javascript and DOM

(90)

Javascript in a browser

Javascript language wan initially created for web browsers. Since then, it has evolved and become a language with uses and platforms.

A platform may be a browser, a web server, a dedicated machine or any other host. Each of the hosts provides platform specific functionality called “host environment”.

A host may provide platform specific objects and functions in addition to language core.

Web browsers give us such additions to control the web pages.

In a web browser we get window object. Window is the root of our every page and provides us methods to control it.

(91)

Javascript in a browser

Example:

function sayHi() {

alert( “Hello” );

}

window.sayHi(); // every global variable is accessible from the root object.

(92)

Javascript in a browser

Document Object Model (DOM)

The document object gives us access to the page content. Now we can create, edit or delete any content of the page.

Example:

document.body.style.background = ‘ brown ’;

Now the background of the whole page will be brown.

There is much more, you can find all of them at:

https://www.w3schools.com/

(93)

Javascript in a browser

Browser Object Model (BOM)

These additional object provide us further access to data that is not related to the document object. Popular object are navigator and location. We can use navigator to get the user

browser and operation system used or use the location to work with url.

example:

alert( location.href ); // show current URL

(94)

Javascript in a browser

Autocorrection

If the browser encounters malformed HTML, it automatically corrects it.

For example, the top tag must be html, even if it doesnt exist, HTML will create it.

Same goes for body.

Another example:

<p>Hello

<li>Mom

<li>and

<li>Dad

In this case, we will see how HTML will correct it and add the missing tags.

(95)

Working with DOM

DOM allows us to do anything with any element of the DOM. To start working we need to reach the desired element and then we can modify it.

On top we have the element and the body objects. We can access them directly with the document object.

<html> = document.documentElement

<body> = document.body

<head> = document.head

(96)

Working with DOM

Important Note:

JS script will have access to an element only if it was rendered after this element.

So for example:

<html>

<head>

<script>

alert( "From HEAD: " + document.body ); // null, there's no <body> yet

</script>

</head>

<body>

<script>

alert( "From BODY: " + document.body ); // HTMLBodyElement, now it exists

</script>

</body>

</html>

(97)

Working with DOM

Children:

Many elements may have childrens. Children elements are nested inside parent element.

For example head and body are children of html element.

Child nodes - elements that are direct children of an element.

Descendants - all elements that are nested inside a given element, including children and their children..

(98)

Working with DOM

Example:

<html>

<body>

<div>Begin</div>

<ul>

<li>

<b>Information</b>

</li>

</ul>

</body>

</html>

In the example above, div and ul are children of body.

(99)

Working with DOM

Now we can also reach all descendants of body:

for( let i = 0; i < document.body.childNodes.length; i++ ) {

alert( document.body.childNodes[i] ); // text, div, text, ul, li, b }

Shorthands:

We can choose the first or last child element with the following:

element.firstChild; //= element.childNodes[0]

element.lastChild; //= element.childNodes[element.childNodes.length - 1]

(100)

Working with DOM

Siblings and Parent:

Sibling are children of the same parent. For example <head> and <body> are siblings.

Choosing siblings and parent are straightforward:

Parent is also available as parentNode.

Choosing next element in the same parent - nextSibling, or the previous with - previousSibling.

(101)

Working with DOM

Example:

<html><head></head><body><script>

// parent of <body> is <html>

alert( document.body.parentNode ); // documentElement (html) // after <head> goes <body>

alert( document.head.nextSibling ); // HTMLBodyElement // before <body> goes <head>

alert( document.body.previousSibling ); // HTMLHeadElement

</script></body></html>

(102)

Working with DOM

Elements Only Navigation:

Navigation properties listed above refer to all nodes. If we want to get only the element siblings and parent we should mention it in our code with a special command:

children = all element children.

firstElementChild, lastElementChild = first and last element

previousElementSibling, nextElementSibling = next and prev elements.

parentElement = element only parent

for( let elem of document.body.children ) { alert( elem); // div, ul, li, b

}

(103)

Working with DOM

More Navigation:

JS has some advanced navigations for special elements like table and form.

Those elements contain many children elements, therefore have some advanced navigation options.

For example:

table.rows; table.tBodies; tbody.rows; tr.cells;

td.cellIndex;

(104)

Working with DOM

Searching an element:

The methods above work well when the elements we are looking for are close to the ones we are working with. But what if we need some arbitrary element of the page.

To search for an element by id:

This way we can reach some particular element: document.getElementById( id );

<div id="special">

<div id="special-content">Element</div>

</div>

<script>

let myElem =

document.getElementById(‘special’);

(105)

Working with DOM

getElementsBy*

Search element by tag name:

This way we get a collection of all elements with the given tag name:

element.getElementsByTagName(tag);

<div>

<h1>Welcome</h1>

<p>Section 1</p>

<p>Section 2</p>

<p>Section 3</p>

</div>

let list = document.getElementsByTagName(‘p’); // p,p,p

(106)

Working with DOM

There is similar way to reach elements by className and by name.

<div>

<form name=”myForm”>

<div class=”section private”></div>

<div class=”section details”></div>

</form>

</div>

let form = document.getElementsByName( “myForm” );

let sections = form.getElementsByClassName( “section” );

alert( sections.length ); // 2

element.getElementsByClassName( className );

element.getElementsByName( name );

(107)

Working with DOM

Another way to search is querySelector:

With this method we can search elements by any kind of css selector.

We have two ways of selecting in such manner:

select an element:

document.querySelector( css );

Select a collection of elements:

document.querySelectorAll( css );

(108)

Working with DOM

Lets see an example:

<ul>

<li>list 1</li>

<li>list 2</li>

</ul>

<script>

let myList = document.querySelector( “ul > li:first-child” ); // list 1 let elements = documents.querySelectorAll( “ul > li” ); // list 1, list 2

</script>

(109)

Working with DOM

matches:

With the previous methods we were searching the DOM for elements.

But what if we want to filter elements by some css values?

For example, we may have a list of elements, and we want to get all those with a class of

‘special’.

for( let elem of document.body.children ) { if( elem.matches(‘ li.special ’) ) {

alert( elem ); // will print all elements with class special }

}

(110)

Working with DOM

Closest:

We know already how to reach a list of all children element and to work with them.

But what is we want to search parents for element?

In such case, we have a method to walk over every parent of the given element to search for specific parent by its css.

Example: <p>Im a paragraph</p>

<div class=”content”>

<ul class=”list”>

<li class=”section”>Section 1</li>

<li class=”section”>Section 2</li>

</ul>

</div>

let section = document.querySelector( “.section” );

alert( section.closest( “.list” ) ); // ul

alert( section.closest( “.content” ) ); // div

(111)

Changing HTML Content

Once we reach the wanted element, we can work with it. We can edit the html of the elements content. To edit we use innerHTML.

Example:

<body>

<p>Im a paragraph<p/>

<div>Im div</div>

</body>

alert(document.body.innerHTML); // will print the code of body (like above) document.body.innerHTML = “Im new content”;

(112)

Changing HTML Content

We can use innerHTML += ‘content’; to overwrite the content with new one.

You may think it adds new content to the element, but it completely overwrites it.

Meaning the content will have to reload and it may be a bad idea because media, like video or image have to be reloaded and it may take a while.

Elements like input will reload as well, and with it their state will reset as well, meaning the text inside will be empty.

document.body.innerHTML += “ Im an addition to the old content ”;

JS comes with another similar way to edit element with outerHTML. This time we get the full html content and the element itself.

(113)

Changing HTML Content

Example:

alert(document.body.outerHTML); // <body> content </body>

Now if we use it to edit the content, it will be changed in the outer html, but will not affect the html used right now on the page.

(114)

Changing HTML Content

textContent, pure text:

Another property we can use to edit only the text of an element is textContent.

Now we can edit just the content of the element, and none of it will be converted to html elements.

Example: <div id=”div1”></div>

<div id=”div2”></div>

div1.innerHTML = “ <h1>New Content</h1> ”;

div2.textContent = “ <h1>New Content</h1> ”;

Result: <div id=”div1”><h1> “New content” </h1></div>

<div id=”div1”> “<h1>New content</h1>” </div>

(115)

Changing HTML Content

Hidden property:

The hidden property is used to specify whether the element is visible or not.

Example:

<p hidden>Paragraph</p>

<p id=”test”>Paragraph</p>

<p>Paragraph</p>

test.hidden = true;

In result we get only the last paragraph visible and 2 hidden ones.

hidden works the same as (css) display = none;

(116)

Changing HTML Content

More properties:

There is some DOM elements that have additional properties which they get by their class.

Examples:

value - gets the values of an <input> or a <textarea>

id - get the id of an element

href - get the address of an <a> element.

<input type=”text” id=”myInput” value=”something”>

alert( myInput.value ); // something alert( myInput.id ); // myInput

alert( myInput.type ); // text

You can see all the properties of an element by using:

(117)

HTML Attributes

In HTML every element may have attributes. We have been using some already like id and href.

Every element has some specific attributes of its own alongside general attributes that can work with all elements.

JS comes with some ways to work with HTML attributes.

Example:

element.hasAttribute(name); // check for existence

element.getAttribute(name); // get the value of the attribute

element.setAttribute(name, value); // sets the value of the attribute element.removeAttribute(name); // removes the attribute and its value element.attributes; // get a collection of attributes

<input id=”myInput”>

myInput.setAttribute(‘id’, 123); // <input id=”123”>

(118)

HTML Attributes

DOM property types:

properties may be other than strings. For example checked or required are of type boolean. style property in fact is an object.

<input id=”myInput” style=”color: red”>

alert( myInput.style ); // [object CSSStyleDeclaration]

(119)

Styles and Classes

ClassName and ClassList:

Changing a class of an element is widely used with JS. Changing a class name dynamically allows us to control better the style of elements.

className property allows us to modify the class of an element:

<div id=”myDiv” class=”special”></div>

alert(myDiv.className); // special

(120)

Styles and Classes

If we assign something to className, we will replace all the old content with new.

There is another way to modify part of element classes with classList.

classList gives us a methods to add/remove/toggle classes.

<div id=”myDiv” class=”first”></div>

myDiv.classList.add(‘second’);

alert(myDiv.className); // first second

(121)

Styles and Classes

Element Style:

Using element.style we can modify the style attribute of an element.

When we use styles with JS there is a little difference.

Both lines do the same, but we have to write it in a different way.

element.style.backgroundColor = ‘red’;

<element style=”background-color: red;”>

Example:

<div id=”myDIv”></div>

myDiv.style.color = ‘red’;

(122)

Styles and Classes

Reset a style:

Sometimes we set a style and may want to reset it, like setting a style to display = ‘none’

then we want to show the element back.

To do so we may delete the style with delete element.style.display but more proper way would be to set the value to “”.

This way the browser will apply its default settings as if no such style was applied.

(123)

Styles and Classes

Computed styles:

Now we seen a way to modify a style of an element, but how to read it?

Using the getComputedStyle( element ) we can see all the CSS cascade.

<body style=”color: green; background: black;”></body>

let computedStyle = getComputedStyle(document.body);

alert( computedStyle.background ); // black alert( compitedStyle.color ); // green

(124)

Modern JavaScript

(125)

use strict

"use strict" defines that the JavaScript code should be executed in "strict mode".

With strict mode you can, for example, not use undeclared variables.

You can use strict mode in all your programs. It helps you to write cleaner code, like preventing you from using undeclared variables.

"use strict" is just a string expression. Old browsers will not throw an error if they don't understand it.

(126)

String.trim()

String.trim() removes whitespace from both sides of a string.

Example

var str = " Hello World! ";

alert(str.trim());

(127)

Array.isArray()

Checks whether an object is an array.

Example

function myFunction() {

var fruits = ["Banana", "Orange", "Apple", "Mango"];

var x = document.getElementById("demo");

x.innerHTML = Array.isArray(fruits);

}

(128)

Array.forEach()

The forEach() method calls a function once for each array element.

Example var txt = "";

var numbers = [45, 4, 9, 16, 25];

numbers.forEach(myFunction);

function myFunction(value) { txt = txt + value + "<br>";

}

(129)

Array.map()

This example multiplies each array value by 2:

Example

var numbers1 = [45, 4, 9, 16, 25];

var numbers2 = numbers1.map(myFunction);

function myFunction(value) { return value * 2;

}

(130)

Array.filter()

This example creates a new array from elements with a value larger than 18:

Example

var numbers = [45, 4, 9, 16, 25];

var over18 = numbers.filter(myFunction);

function myFunction(value) { return value > 18;

}

(131)

Array.reduce()

This example finds the sum of all numbers in an array:

Example

var numbers1 = [45, 4, 9, 16, 25];

var sum = numbers1.reduce(myFunction);

function myFunction(total, value) { return total + value;

}

(132)

Array.reduceRight()

This example also finds the sum of all numbers in an array:

Example

var numbers1 = [45, 4, 9, 16, 25];

var sum = numbers1.reduceRight(myFunction);

function myFunction(total, value) { return total + value;

}

(133)

Array.every()

This example checks if all values are over 18:

Example

var numbers = [45, 4, 9, 16, 25];

var allOver18 = numbers.every(myFunction);

function myFunction(value) { return value > 18;

}

(134)

Array.some()

This example checks if some values are over 18:

Example

var numbers = [45, 4, 9, 16, 25];

var allOver18 = numbers.some(myFunction);

function myFunction(value) { return value > 18;

}

(135)

Array.indexOf()

Search an array for an element value and returns its position.

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];

var a = fruits.indexOf("Apple");

(136)

Array.lastIndexOf()

Array.lastIndexOf() is the same as Array.indexOf(), but searches from the end of the array.

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];

var a = fruits.lastIndexOf("Apple");

(137)

What is JSON

JavaScript Object Notation is a syntax for storing and exchanging data.

When exchanging data between a browser and a server, the data can only be text.

Using JSON is very convenient since converting it from text to a JavaScript object is simple.

This way we can work with the data as JavaScript objects, with no complicated parsing and translations.

(138)

What is JSON

JSON looks exactly like JS object to keep the transformation simple:

Example:

{“Name”: “John”,

“Age”: 30,

“City”: “Jerusalem”

}

(139)

JSON.parse()

A common use of JSON is to receive data from a web server.

Imagine you received this text string from a web server:

'{"name":"John", "age":30, "city":"New York"}'

The JavaScript function JSON.parse() is used to convert the text into a JavaScript object:

var obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

(140)

JSON.stringify()

A common use of JSON is to send data to a web server.

When sending data to a web server, the data has to be a string.

Imagine we have this object in JavaScript:

var obj = {"name":"John", "age":30, "city":"New York"};

Use the JavaScript function JSON.stringify() to convert it into a string.

var myJSON = JSON.stringify(obj);

(141)

JavaScript this Keyword

Example

var person = {

firstName: "John", lastName : "Doe", id : 5566,

fullName : function() {

return this.firstName + " " + this.lastName;

}

};

(142)

JavaScript this Keyword

What is this?

The JavaScript this keyword refers to the object it belongs to.

This has different values depending on where it is used.

In a method, this refers to the owner object.

Alone, this refers to the global object.

In a function, this refers to the global object.

In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Methods like call(), and apply() can refer this to any object.

References

Related documents

This approach is based on the well-known theory of real-valued stochastic integration, and the respective Itˆo integral is given by a series of Itˆo integrals with respect to

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and other web browser scripting languages to transfer and manipulate XML data to and

• Uses XML and XSLT for the interchange, and manipulation and display, of data, respectively • Uses XMLHttpRequest object for

In these industries, however, the greater initial adjustment of average hours in Germany appears to compensate for the slower adjustment of employment levels, and the adjustment

While methods of reading and writing in liberal arts education are supposed to be targeted at developing students' critical thinking skills and encouraging independent thinking, in

En tres subescalas (Baja autoestima, Alienación personal y Ascetismo), las adolescentes con RTA no se diferenciaron significativamente del grupo NTA, y tanto el grupo RTA como

Cornhill Road, Moorside Road, Woodsend Road, Irlam Road, Flixton Road, Station Road, Stretford Road, Urmston Lane, Barton Road, Chester Road, Cross Street, Washway Road,

Two aspects of eye behaviour are of special interest here: (1) ocular drift during number word presentation and up to the point of saccade launch and (2) parameters of