0% found this document useful (0 votes)
15K views

Javscript and Angular Js

Uploaded by

Saurabh Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15K views

Javscript and Angular Js

Uploaded by

Saurabh Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

UPCISS JavaScript & Angular JS

Video Tutorial
Full Playlist Available on
YouTube Channel UPCISS

Free Online Computer Classes on


YouTube Channel UPCISS
www.youtube.com/upciss

Copyright © 2021 UPCISS


Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Introduction
JavaScript Variables
JavaScript Reserved Words
JavaScript Output
JavaScript Statements
JavaScript Operators
JavaScript Data Types
JavaScript Functions
JavaScript Objects
Conditional Statements
JavaScript Popup Boxes
JavaScript Events
JavaScript Form Validation
AngularJS

1
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Introduction to Scripting Languages


All scripting languages are programming languages. The scripting language is
basically a language where instructions are written for a run time environment. They
do not require the compilation step and are rather interpreted. It brings new
functions to applications and glue complex system together. A scripting language is
a programming language designed for integrating and communicating with other
programming languages.

Advantages of scripting languages:

 Easy learning: The user can learn to code in scripting languages quickly, not
much knowledge of web technology is required.
 Fast editing: It is highly efficient with the limited number of data structures
and variables to use.
 Interactivity: It helps in adding visualization interfaces and combinations in
web pages. Modern web pages demand the use of scripting languages. To create
enhanced web pages, fascinated visual description which includes background
and foreground colors and so on.
 Functionality: There are different libraries which are part of different scripting
languages. They help in creating new applications in web browsers and are
different from normal programming languages.

There are two types of scripting language


Client-side scripting is performed to generate a code that can run on the client
end (browser) without needing the server side processing. Basically, these types of
scripts are placed inside an HTML document. The client-side scripting can be used
to examine the user’s form for the errors before submitting it and for changing the
content according to the user input. As I mentioned before, the web requires three
elements for its functioning which are, client, database and server.

Server-side scripting is a technique of programming for producing the code which


can run software on the server side, in simple words any scripting or programming
that can run on the web server is known as server-side scripting. The operations like
customization of a website, dynamic change in the website content, response
generation to the user’s queries, accessing the database, and so on are performed
at the server end.

2
Website: www.upcissyoutube.com YouTube Channel: UPCISS

BASIS FOR
SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING
COMPARISON

Basic Works in the back end which Works at the front end

could not be visible at the and script are visible

client end. among the users.

Processing Requires server interaction. Does not need interaction

with the server.

Languages PHP, ASP.net, Ruby on Rails, HTML, CSS, JavaScript,

involved ColdFusion, Python, etcetera. etc.

Affect Could effectively customize Can reduce the load to the

the web pages and provide server.

dynamic websites.

Security Relatively secure. Insecure

JavaScript Introduction
JavaScript is a cross-platform, object-oriented scripting language used to make
webpages interactive (e.g., having complex animations, clickable buttons, popup
menus, etc.). JavaScript contains a standard library of objects, such
as Array, Date, and Math, and a core set of language elements such as operators,
control structures, and statements.

3
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Can Change HTML Content


One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":

<html>
<body>

<h2>What Can JavaScript Do? </h2>

<p id="demo">JavaScript can change HTML content. </p>

<button type="button"
onclick='document.getElementById("demo").innerHTML = "Hello
JavaScript!"'>Click Me! </button>

</body>
</html>

JavaScript Can Change HTML Styles (CSS)


Changing the style of an HTML element, is a variant of changing an HTML attribute:

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'">Click
Me!</button>

JavaScript Can Hide HTML Elements


Hiding HTML elements can be done by changing the display style:

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button"
onclick="document.getElementById('demo').style.display='none'">Click
Me!</button>

4
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed:

// How to create variables:


var x;
let y;

// How to use variables:


x = 5;
y = 6;
let z = x + y;

JavaScript Values
The JavaScript syntax defines two types of values:

 Fixed values
 Variable values

Fixed values are called Literals.

Variable values are called Variables.

JavaScript Literals
The two most important syntax rules for fixed values are:

1. Numbers are written with or without decimals:

10.50

1001

2. Strings are text, written within double or single quotes:

"John Doe"

'John Doe'

5
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Where To
The <script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags.

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

JavaScript in <head> or <body>


You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in
both.

<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>
</head>
<body>

<h2>JavaScript in Head</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>
Placing scripts at the bottom of the <body> element improves the display speed,
because script interpretation slows down the display.

6
Website: www.upcissyoutube.com YouTube Channel: UPCISS

External JavaScript
Scripts can also be placed in external files:

External file: myScript.js


function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}

External scripts are practical when the same code is used in many different web
pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source)
attribute of a <script> tag:

<html>
<body>

<h2>External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

<script src="myScript.js"></script>

</body>
</html>

JavaScript Functions and Events


A JavaScript function is a block of JavaScript code, that can be executed when
"called" for.

For example, a function can be called when an event occurs, like when the user
clicks a button.

You will learn much more about functions and events in later chapters.

7
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Variables
Variables
Variables are containers for storing data (values).

In this example, x, y, and z, are variables, declared with the var keyword:

There are 3 ways to declare a JavaScript variable:

 Using var
 Using let
 Using const

You declare a JavaScript variable with the var keyword:

<body>

<h2>JavaScript Variables</h2>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>

Much Like Algebra


In this example, price1, price2, and total, are variables:

Example
var price1 = 5;
var price2 = 6;
var total = price1 + price2;

8
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Identifiers
All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter
 Names can also begin with $ and _
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names

JavaScript identifiers are case-sensitive.

JavaScript Reserved Words


In JavaScript you cannot use these reserved words as variables, labels, or function
names:

9
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Data Types


JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and
strings.

Strings are written inside double or single quotes. Numbers are written without
quotes.

If you put a number in quotes, it will be treated as a text string.

Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';

Declaring (Creating) JavaScript Variables


Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var keyword:

var carName;

After the declaration, the variable has no value (technically it has the value
of undefined).

To assign a value to the variable, use the equal sign:

carName = "Volvo";

You can also assign a value to the variable when you declare it:

var carName = "Volvo";

One Statement, Many Variables


You can declare many variables in one statement.

Start the statement with var and separate the variables by comma:

var person = "John Doe", carName = "Volvo", price = 200;

10
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Value = undefined
In computer programs, variables are often declared without a value. The value can
be something that has to be calculated, or something that will be provided later,
like user input.

A variable declared without a value will have the value undefined.

The variable carName will have the value undefined after the execution of this
statement:

Example
var carName;

Re-Declaring JavaScript Variables


If you re-declare a JavaScript variable, it will not lose its value.

The variable carName will still have the value "Volvo" after the execution of these
statements:

Example
var carName = "Volvo";
var carName;

JavaScript Let
The let keyword was introduced in ES6 (2015).

Variables defined with let cannot be Redeclared.

Variables defined with let must be Declared before use.

Variables defined with let have Block Scope.

Cannot be Redeclared
Variables defined with let cannot be redeclared.

You cannot accidentally redeclare a variable.

With let you can not do this:

11
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Example
let x = "John Doe";

let x = 0;

// SyntaxError: 'x' has already been declared

With var you can:

Example
var x = "John Doe";

var x = 0;

Block Scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.

ES6 introduced two important new JavaScript keywords: let and const.

These two keywords provide Block Scope in JavaScript.

Variables declared inside a { } block cannot be accessed from outside the block:

Example
{
let x = 2;
}
// x can NOT be used here

Variables declared with the var keyword can NOT have block scope.

Variables declared inside a { } block can be accessed from outside the block.

Example
{
var x = 2;
}
// x CAN be used here

12
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Redeclaring Variables
Redeclaring a variable using the let keyword can solve this problem.

Redeclaring a variable inside a block will not redeclare the variable outside the
block:

Example
let x = 10;
// Here x is 10

{
let x = 2;
// Here x is 2
}

// Here x is 10

Let Hoisting
Variables defined with var are hoisted to the top and can be initialized at any time.

Meaning: You can use the variable before it is declared:

Example
This is OK:

carName = "Volvo";
var carName;

Variables defined with let are also hoisted to the top of the block, but not
initialized.

Meaning: Using a let variable before it is declared will result in a Reference Error:

Example
carName = "Saab";
let carName = "Volvo";

13
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Output
JavaScript Display Possibilities
JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().

Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML
content:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>

14
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Using document.write()
For testing purposes, it is convenient to use document.write():

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

Using document.write() after an HTML document is loaded, will delete all existing
HTML:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html>

The document.write() method should only be used for testing.

Using window.alert()
You can use an alert box to display data:

15
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>

You can skip the window keyword.

In JavaScript, the window object is the global scope object, that means that
variables, properties, and methods by default belong to the window object. This
also means that specifying the window keyword is optional:

JavaScript Print
JavaScript does not have any print object or print methods.

You cannot access output devices from JavaScript.

The only exception is that you can call the window.print() method in the browser to
print the content of the current window.

Example
<!DOCTYPE html>
<html>
<body>

<button onclick="window.print()">Print this page</button>

</body>
</html>

16
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Statements
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a computer.

In a programming language, these programming instructions are


called statements.

A JavaScript program is a list of programming statements.

In HTML, JavaScript programs are executed by the web browser.

JavaScript Statements
JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":

Example
document.getElementById("demo").innerHTML = "Hello Dolly.";

Most JavaScript programs contain many JavaScript statements.

The statements are executed, one by one, in the same order as they are written.

JavaScript programs (and JavaScript statements) are often called JavaScript code.

Semicolons ;
Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

JavaScript White Space


JavaScript ignores multiple spaces. You can add white space to your script to make
it more readable.

17
Website: www.upcissyoutube.com YouTube Channel: UPCISS
The following lines are equivalent:

let person = "Hege";


let person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

let x = y + z;

JavaScript Line Length and Line Breaks


For best readability, programmers often like to avoid code lines longer than 80
characters.

If a JavaScript statement does not fit on one line, the best place to break it is after
an operator:

Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";

JavaScript Code Blocks


JavaScript statements can be grouped together in code blocks, inside curly
brackets {...}.

The purpose of code blocks is to define statements to be executed together.

One place you will find statements grouped together in blocks, is in JavaScript
functions:

Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}

In this tutorial we use 2 spaces of indentation for code blocks.


You will learn more about functions later in this tutorial.

Comments
Single line comments start with //.

Multi-line comments start with /* and end with */.

18
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Operators
JavaScript Arithmetic Operators

JavaScript Assignment Operators

19
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Comparison Operators

JavaScript Logical Operators

Operator Precedence
Operator precedence describes the order in which operations are performed in an
arithmetic expression.

let x = 100 + 50 * 3;

Is the result of example above the same as 150 * 3, or is it the same as 100 +
150?

Is the addition or the multiplication done first?

As in traditional school mathematics, the multiplication is done first.

20
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Multiplication (*) and division (/) have higher precedence than addition (+) and
subtraction (-).

And (as in school mathematics) the precedence can be changed by using


parentheses:

let x = (100 + 50) * 3;

When using parentheses, the operations inside the parentheses are computed first.

When many operations have the same precedence (like addition and subtraction),
they are computed from left to right:

let x = 100 + 50 - 3;

JavaScript Operator Precedence Values


Value Operator Description Example

21 () Expression grouping (3 + 4)

20 . Member person.name

20 [] Member person["name"]

20 () Function call myFunction()

20 new Create new Date()

18 ++ Postfix Increment i++

18 -- Postfix Decrement i--

17 ++ Prefix Increment ++i

17 -- Prefix Decrement --i

17 ! Logical not !(x==y)

17 typeof Type typeof x

21
Website: www.upcissyoutube.com YouTube Channel: UPCISS
16 ** Exponentiation (ES2016) 10 ** 2

15 * Multiplication 10 * 5

15 / Division 10 / 5

15 % Division Remainder 10 % 5

14 + Addition 10 + 5

14 - Subtraction 10 - 5

13 << Shift left x << 2

13 >> Shift right x >> 2

13 >>> Shift right (unsigned) x >>> 2

12 < Less than x<y

12 <= Less than or equal x <= y

12 > Greater than x>y

12 >= Greater than or equal x >= y

12 in Property in Object "PI" in Math

12 instanceof Instance of Object instanceof Array

11 == Equal x == y

11 === Strict equal x === y

11 != Unequal x != y

11 !== Strict unequal x !== y

10 & Bitwise AND x&y

9 ^ Bitwise XOR x^y

22
Website: www.upcissyoutube.com YouTube Channel: UPCISS
8 | Bitwise OR x|y

7 && Logical AND x && y

6 || Logical OR x || y

5 ?? Nullish Coalescing x ?? y

4 ?: Condition ? "Yes" : "No"

3 += Assignment x += y

3 /= Assignment x /= y

3 -= Assignment x -= y

3 *= Assignment x *= y

3 %= Assignment x %= y

3 <<= Assignment x <<= y

3 >>= Assignment x >>= y

3 >>>= Assignment x >>>= y

3 &= Assignment x &= y

3 ^= Assignment x ^= y

3 |= Assignment x |= y

2 yield Pause Function yield x

1 , Comma 5,6

23
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Data Types


JavaScript variables can hold different data types: numbers, strings, objects and
more:

let length = 16; // Number


let lastName = "Johnson"; // String
let x = {firstName:"John", lastName:"Doe"}; // Object

The Concept of Data Types


In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about the


type.

Without data types, a computer cannot safely solve this:

let x = 16 + "Volvo";

Result: 16Volvo

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it
produce a result?

JavaScript will treat the example above as:

let x = "16" + "Volvo";

When adding a number and a string, JavaScript will treat the number as a string.

JavaScript evaluates expressions from left to right. Different sequences can


produce different results:

let x = 16 + 4 + "Volvo";

Result: 20Volvo

let x = "Volvo" + 16 + 4;

Result: Volvo164

24
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Types are Dynamic


JavaScript has dynamic types. This means that the same variable can be used to
hold different data types:

Example
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String

JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:

You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

Example
let answer1 = "It's alright"; // Single quote inside double quotes
let answer2 = "He is called 'Johnny'"; // Single quotes inside double quotes
let answer3 = 'He is called "Johnny"'; // Double quotes inside single quotes

JavaScript Numbers
JavaScript has only one type of numbers.

Numbers can be written with, or without decimals:

Example
let x1 = 34.00; // Written with decimals
let x2 = 34; // Written without decimals

25
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Booleans
Booleans can only have two values: true or false.

Example
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false

JavaScript Arrays
JavaScript arrays are written with square brackets.

Array items are separated by commas.

The following code declares (creates) an array called cars, containing three items
(car names):

Example
const cars = ["Saab", "Volvo", "BMW"];

Array indexes are zero-based, which means the first item is [0], second is [1], and
so on.

JavaScript Objects
JavaScript objects are written with curly braces {}.

Object properties are written as name:value pairs, separated by commas.

Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

26
Website: www.upcissyoutube.com YouTube Channel: UPCISS

The typeof Operator


You can use the JavaScript typeof operator to find the type of a JavaScript variable.

The typeof operator returns the type of a variable or an expression:

Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"

Undefined
In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.

Example
let car; // Value is undefined, type is undefined
car = undefined; // Value is undefined, type is undefined

Empty Values
An empty value has nothing to do with undefined.

An empty string has both a legal value and a type.

Example
let car = ""; // The value is "", the typeof is "string"

27
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

Example
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}

JavaScript Function Syntax


A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


// code to be executed
}

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

A Function is much the same as a Procedure or a Subroutine, in other programming


languages.

28
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

You will learn a lot more about function invocation later in this tutorial.

Function Return
When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.

Functions often compute a return value. The return value is "returned" back to
the "caller":

Example
Calculate the product of two numbers, and return the result:

let x = myFunction(4, 3); // Function is called, return value will end up


in x

function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}

Why Functions?
You can reuse code: Define the code once, and use it many times.

You can use the same code many times with different arguments, to produce
different results.

29
Website: www.upcissyoutube.com YouTube Channel: UPCISS

The () Operator Invokes the Function


Using the example above, toCelsius refers to the function object,
and toCelsius() refers to the function result.

Accessing a function without () will return the function object instead of the
function result.

Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;

Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.

Example
// code here can NOT use carName

function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}

// code here can NOT use carName

Since local variables are only recognized inside their functions, variables with the
same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is
completed.

30
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.

A car has properties like weight and color, and methods like start and stop:

Object Properties Methods

car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = 850kg car.brake()

car.color = white car.stop()

All cars have the same properties, but the property values differ from car to car.

All cars have the same methods, but the methods are performed at different
times.

JavaScript Objects
You have already learned that JavaScript variables are containers for data values.

Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to a variable named car:

const car = {type:"Fiat", model:"500", color:"white"};

The values are written as name:value pairs (name and value separated by a
colon).

It is a common practice to declare objects with the const keyword.

31
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Object Definition
You define (and create) a JavaScript object with an object literal:

Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Spaces and line breaks are not important. An object definition can span multiple
lines:

Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

Object Properties
The name:values pairs in JavaScript objects are called properties:

Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

Accessing Object Properties


You can access object properties in two ways:

objectName.propertyName or objectName["propertyName"]

JavaScript objects are containers for named values called properties.

32
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Object Methods
Objects can also have methods.

Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions.

Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

fullName function() {return this.firstName + " " + this.lastName;}

A method is a function stored as a property.

Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

The this Keyword


In a function definition, this refers to the "owner" of the function.

In the example above, this is the person object that "owns" the fullName function.

In other words, this.firstName means the firstName property of this object.

33
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Accessing Object Methods


You access an object method with the following syntax:

objectName.methodName()
name = person.fullName();

If you access a method without the () parentheses, it will return the function
definition:

Conditional Statements
Conditional statements are used to perform different actions based on different
conditions.

Very often when you write code, you want to perform different actions for different
decisions.

You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is


true
 Use else to specify a block of code to be executed, if the same condition is
false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a
condition is true.

Syntax
if (condition) {
// block of code to be executed if the condition is true
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a
JavaScript error.

34
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Example
Make a "Good day" greeting if the hour is less than 18:00:

if (hour < 18) {


greeting = "Good day";
}

The else Statement


Use the else statement to specify a block of code to be executed if the condition is
false.

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good
evening":

if (hour < 18) {


greeting = "Good day";
} else {
greeting = "Good evening";
}

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.

Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2
is true
} else {
// block of code to be executed if the condition1 is false and condition2
is false
}

35
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time is less
than 20:00, create a "Good day" greeting, otherwise a "Good evening":

if (time < 10) {


greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

The JavaScript Switch Statement


Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 If there is no match, the default code block is executed.

36
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Example
The getDay() method returns the weekday as a number between 0 and 6.

(Sunday=0, Monday=1, Tuesday=2 ..)

This example uses the weekday number to calculate the weekday name:

switch (3) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}

The break Keyword


When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution inside the switch block.

It is not necessary to break the last case in a switch block. The block breaks (ends)
there anyway.

Note: If you omit the break statement, the next case will be executed even if the
evaluation does not match the case.

37
Website: www.upcissyoutube.com YouTube Channel: UPCISS

The default Keyword


The default keyword specifies the code to run if there is no case match:

Example
The getDay() method returns the weekday as a number between 0 and 6.

If today is neither Saturday (6) nor Sunday (0), write a default message:

switch (3) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}

Common Code Blocks


Sometimes you will want different switch cases to use the same code.

In this example case 4 and 5 share the same code block, and 0 and 6 share
another code block:

Example
switch (new Date().getDay()) {
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}

38
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Popup Boxes


JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt
box.

Alert Box
An alert box is often used if you want to make sure information comes through to
the user.

When an alert box pops up, the user will have to click "OK" to proceed.

Syntax
window.alert("sometext");

The window.alert() method can be written without the window prefix.

Example
alert("I am an alert box!");

Confirm Box
A confirm box is often used if you want the user to verify or accept something.

When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.

Syntax
window.confirm("sometext");

The window.confirm() method can be written without the window prefix.

Example
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {

39
Website: www.upcissyoutube.com YouTube Channel: UPCISS
txt = "You pressed Cancel!";
}

Prompt Box
A prompt box is often used if you want the user to input a value before entering a
page.

When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.

If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.

Syntax
window.prompt("sometext","defaultText");

The window.prompt() method can be written without the window prefix.

Example
let person = prompt("Please enter your name", "Harry Potter");
let text;
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}

JavaScript Events
HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these


events.

HTML Events
An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

 An HTML web page has finished loading


 An HTML input field was changed
 An HTML button was clicked

40
Website: www.upcissyoutube.com YouTube Channel: UPCISS
Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to


a <button> element:

Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The time
is?</button>

In the example above, the JavaScript code changes the content of the element with
id="demo".

In the example above, the JavaScript code changes the content of the element with
id="demo".

In the next example, the code changes the content of its own element
(using this.innerHTML):

Example
<button onclick="this.innerHTML = Date()">The time is?</button>

JavaScript code is often several lines long. It is more common to see event
attributes calling functions:

Example
<button onclick="displayDate()">The time is?</button>

41
Website: www.upcissyoutube.com YouTube Channel: UPCISS

Common HTML Events


Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an


HTML element

onmouseout The user moves the mouse away from


an HTML element

onkeydown The user pushes a keyboard key

onkeyup The user pushes a keyboard key

onload The browser has finished loading the


page

onchange

<select id="mySelect" onchange="myFunction()">


<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>

onclick

<button onclick="myFunction()">Click me</button>


<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>

42
Website: www.upcissyoutube.com YouTube Channel: UPCISS
onmouseover / onmouseout

<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0"


src="smiley.gif" alt="Smiley" width="32" height="32">
<script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px";
}
function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
}
</script>

onkeydown / onkeyup

<input type="text" id="demo" onkeydown="keydownFunction()"


onkeyup="keyupFunction()">
<script>
function keydownFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}
function keyupFunction() {
document.getElementById("demo").style.backgroundColor = "green";
}
</script>

onkeyup

<input type="text" id="fname" onkeyup="myFunction()">


<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>

onload

<script>
function myFunction() {
alert("Page is loaded");
}
</script>

43
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Form Validation


HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns false,
to prevent the form from being submitted:

JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}

The function can be called when the form is submitted:

HTML Form Example


<form name="myForm" action="/action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Automatic HTML Form Validation


HTML form validation can be performed automatically by the browser:

If a form field (fname) is empty, the required attribute prevents this form from
being submitted:

HTML Form Example


<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

44
Website: www.upcissyoutube.com YouTube Channel: UPCISS

JavaScript Can Validate Numeric Input


<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
let x = document.getElementById("numb").value;
let text;
if (x>=1 && x<=10) {
text = "Input OK";
} else {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
}
</script>

Data Validation
Data validation is the process of ensuring that user input is clean, correct, and
useful.

Validation can be defined by many different methods, and deployed in many


different ways.

Server side validation is performed by a web server, after input has been sent to
the server.

Client side validation is performed by a web browser, before input is sent to a


web server.

45
Website: www.upcissyoutube.com YouTube Channel: UPCISS

AngularJS
AngularJS History
AngularJS version 1.0 was released in 2012.

Miško Hevery, a Google employee, started to work with AngularJS in 2009.

The idea turned out very well, and the project is now officially supported by
Google.

AngularJS Introduction
AngularJS is perfect for Single Page Applications (SPAs).

AngularJS is a JavaScript framework. It can be added to an HTML page with


a <script> tag.

AngularJS extends HTML attributes with Directives, and binds data to HTML
with Expressions.

AngularJS is a JavaScript Framework


AngularJS is a JavaScript framework written in JavaScript.

AngularJS is distributed as a JavaScript file, and can be added to a web page with a
script tag:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.mi
n.js"></script>

AngularJS Extends HTML


AngularJS extends HTML with ng-directives.

The ng-app directive defines an AngularJS application.

The ng-model directive binds the value of HTML controls (input, select, textarea)
to application data.

The ng-bind directive binds application data to the HTML view.

46
Website: www.upcissyoutube.com YouTube Channel: UPCISS
AngularJS Example
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.mi
n.js"></script>
<body>

<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1> (ng-bind="name")
</div>

</body>
</html>

Example explained:

AngularJS starts automatically when the web page has loaded.

The ng-app directive tells AngularJS that the <div> element is the "owner" of an
AngularJS application.

The ng-model directive binds the value of the input field to the application
variable name.

The ng-bind directive binds the content of the <p> element to the application
variable name.

AngularJS Directives
As you have already seen, AngularJS directives are HTML attributes with
an ng prefix.

The ng-init directive initializes AngularJS application variables.

AngularJS Example
<div ng-app="" ng-init="firstName='John'">

<p>The name is <span ng-bind="firstName"></span></p>

</div>

Alternatively with valid HTML:

You can use data-ng-, instead of ng-, if you want to make your page HTML valid.

47
Website: www.upcissyoutube.com YouTube Channel: UPCISS

AngularJS Applications
AngularJS modules define AngularJS applications.

AngularJS controllers control AngularJS applications.

The ng-app directive defines the application, the ng-controller directive defines
the controller.

AngularJS Example
<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>


Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>

AngularJS modules define applications:

AngularJS Module
var app = angular.module('myApp', []);

AngularJS controllers control applications:

AngularJS Controller
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});

48
Website: www.upcissyoutube.com YouTube Channel: UPCISS

AngularJS Expressions
AngularJS expressions are written inside double braces: {{ expression }}.

AngularJS will "output" data exactly where the expression is written:

AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.mi
n.js"></script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>

If you remove the ng-app directive, HTML will display the expression as it is,
without solving it:

You can write expressions wherever you like, AngularJS will simply resolve the
expression and return the result.

Example: Let AngularJS change the value of CSS properties.

Change the color of the input box below, by changing its value:

Example
<div ng-app="" ng-init="myCol='lightblue'">

<input style="background-color:{{myCol}}" ng-model="myCol">

</div>

AngularJS Numbers
<div ng-app="" ng-init="quantity=1; price=5">
<h2>Cost Calculator</h2>
Quantity: <input type="number" ng-model="quantity">
Price: <input type="number" ng-model="price">
<h3>Total in Rupee: <span ng-bind="quantity * price"></span></h3>
</div>

49
Website: www.upcissyoutube.com YouTube Channel: UPCISS

AngularJS Objects Looping


<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
<p>Looping with objects:</p>
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}</li>
</ul>
</div>

AngularJS Expressions vs. JavaScript Expressions


Like JavaScript expressions, AngularJS expressions can contain literals, operators,
and variables.

Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.

AngularJS expressions do not support conditionals, loops, and exceptions, while


JavaScript expressions do.

AngularJS expressions support filters, while JavaScript expressions do not.

Visit our Website

https://upcissyoutube.com/
50

You might also like