0% found this document useful (0 votes)
3 views136 pages

Angular

angular js
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views136 pages

Angular

angular js
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Web Development

Using Angular JS and


MONGO
Course Code : UCA20D03J
Year / Semester :2/3
Class : II BCA ‘A’
Instructor : [Link]
Unit 1
Need of Scripting Language, Difference between client and server side scripting,
Script tag in HTML, Java Script declaration, Output printing – document. Write,
innerHTML, window .alert, [Link], Java script statements, Comments and
Variables,
Lab 1 – Java Script Input and Output
Java script Operators -Logical, Bitwise, Arithmetic and Assignment operators, Java
Script Datatypes – numeric, Java Script Datatypes – non numeric, Conditional
statements, If else statements, Switch statements, Iteration statements,
Lab 2 – Java Script Operators and Conditions
Loop Controls – for loop, While loop, Do while Loop, For each loop, Arrays ,
Introduction and declaring, Accessing arrays, Array Properties : index, input length,
prototype, Array Methods :concat, every, forEach,
Lab 3 - Looping Statements
Topics
 Types of Applications
 Difference between windows and web

applications
 Web development
 Front end
 Back end
 Data server
 Client side scripting
 Server side scripting
3
Types of Applications
 Windows applications
 Web applications

4
Windows applications

5
Web Applications

6
Guess this?

7
What is this?

8
Website Vs Web applications

9
Windows Vs web applications

10
11
12
13
14
15
16
Introduction
 Web page uses
 HTML, for its content, layout and structure
 CSS for its presentation
 Script adds behavior to this web page.
 All
mentioned below are added to a web
page using a script / Common uses of script
 Customized content based on user input
 Dynamic content
 Form validation
17
What is a Script
A script is a set of instructions to be executed
by a computer
 A script needs an interpreter and is

interpreted at run-time
 A program that is first compiled and then

executed
 There are two types of scripts

1. Client-side script (front-end)


2. Server-side script (back-end)
18
Need of Scripting Language
 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.
19
Client-Side Scripting
 Let the client compute

20
Client-side scripting benefits
 client-side scripting (JavaScript) benefits:
 usability: can modify a page without having to
post back to the server (faster UI)
 efficiency: can make small, quick changes to
page without waiting for server
 event-driven: can respond to user actions like
clicks and key presses

21
Disadvantages of client-side
scripting
• There is no guarantee that the client has JavaScript
enabled .

• The idiosyncrasies between various browsers and


operating systems make it difficult to test for all potential
client configurations. What works in one browser, may
generate an error in another.

• JavaScript-heavy web applications can be complicated


to debug and maintain.

22
Server-side scripting benefits
 server-side programming (PHP) benefits:
 security: has access to server's private data;
client can't see source code
 compatibility: not subject to browser
compatibility issues
 power: can write files, open connections to
servers, connect to databases, ...

23
Difference between client and server
side scripting
[Link] Server-side Scripting Client-side Scripting
1 It helps work with the back end. It helps work with the front end.

2 It doesn’t depend on the user/client. It is visible to the user/client.

3 It runs on the web server. The scripts are run on the client browser.

It helps provide a response to every request that comes in


4 It runs on the user/client’s computer.
from the user/client.

5 This is not visible to the client side of the application. It depends on the browser’s version.

It requires the interaction with the server for the data to be It doesn’t interact with the server to process
6
process. data.
Server side scripting requires languages such as PHP, Client side scripting involves languages such
7
[Link], ColdFusion, Python, Ruby on Rails. as HTML, CSS, JavaScript.
It is considered to be a secure way of working with It is considered to be less secure in
8
applications. comparison to client side scripting.

9 It can be used to customize web pages. It helps reduce the load on the server.

10 It can also be used to provide dynamic websites.

24
Script tag in HTML
 The HTML <script> tag is used for declaring a
script (such as JavaScript) within your HTML
document.
 The <script> tag is used to embed a client-side
script (JavaScript).
 The <script> element either contains scripting
statements, or it points to an external script file
through the src attribute.
25
Script tag in HTML
 To select an HTML element, JavaScript most often
uses the [Link]() method.
<!DOCTYPE html>
Output:
<html>
<body>
The script element
<h1>The script element</h1>
Hello SRMite!
<p id="demo"></p>
You're visiting Unit-1 first example!
<script>
[Link]("demo").innerHTML = "Hello SRMite!";
[Link]("You're visiting Unit-1 first example!")
</script>

</body>
</html> 26
Popups
 Used for displaying information to the user outside of the
page.
 Typically as a warning or when an error has occured
 Ask user for additional information
 Confirmation
 alert(<text>); - Exits via an okay button
 confirm(<text>); - Returns true or false (ok or cancel)
 prompt(<text>, <default>); - Returns user's input

27
Java Script
“ can change the web site
content”
What is JavaScript
 JavaScript is the world's most popular scripting
language. (Programming language of the web)
 It is
1. object-based,
2. lightweight,
3. cross-platform translated language.
 It is widely used for client-side validation.
 The JavaScript Translator (embedded in the browser) is
responsible for translating the JS code for the web
browser.
 JavaScript is easy to learn.
29
Features of JavaScript
Some of the features of JavaScript are:
 Lightweight
 Interpreted programming language
 Good for the applications which are network-centric
 Complementary to Java
 Complementary to HTML
 Open source
 Cross-platform

30
Advantages of JavaScript Disadvantages of JavaScript
 Server interaction is less  No support for multithreading
 Feedback to the visitors is  No support for multiprocessing
immediate  Reading and writing of files is
 Interactivity is high not allowed
 Interfaces are richer  No support for networking
applications.

31
JavaScript
1. JavaScript Can Change HTML Content
2. JavaScript Can Change HTML Attribute
Values
3. JavaScript Can Change HTML Styles (CSS)
4. JavaScript Can Hide HTML Elements
5. JavaScript Can Show HTML Elements

32
Program 1
<html>
<body>
<h2>Hello world !</h2>
<script>
[Link](“Welcome");
</script>
</body>
</html>
33
Add two numbers
<html>
<body>
<h2>ARITHMETIC OPERATOR</h2>
<script>
a=9;
b=12;
add=a+b;
[Link]("After addition:"+add);
[Link]("<br>");
</script>
</body>
</html> 34
<html>
<body> Add two numbers
<h2>ARITHMETIC OPERATOR</h2>
<script>
a=parseInt([Link]("enter the a value"));
b=parseInt([Link]("enter the b value"));
add=a+b;
[Link]("After addition:"+add);
[Link]("<br>");
</script>
</body>
</html> 35
1. JavaScript Can Change
HTML Content
1. <!DOCTYPE html>
2. <html>
3. <body>
4. <h2>What Can JavaScript Do?</h2>
5. <p id="demo">JavaScript can change HTML content.</p>
6. <button type="button"
onclick='[Link]("demo").innerHTML =
"Hello JavaScript!"'>Click Me!</button>
7. </body>
8. </html>

36
JavaScript Can Change
HTML Attribute Values
1. <!DOCTYPE html> <html> <body>
2. <h2>What Can JavaScript Do?</h2>
3. <p>JavaScript can change HTML attribute
values.</p>
4. <p>In this case JavaScript changes the value of
the src (source) attribute of an image.</p>

5. <button
onclick="[Link]('myImage').
src='pic_bulbon.gif'">Turn on the light</button>

6. <img id="myImage" src="pic_bulboff.gif"


style="width:100px">

7. <button
onclick="[Link]('myImage').
src='pic_bulboff.gif'">Turn off the light</button>
37
8. </body> </html>
JavaScript Can Change
HTML Styles (CSS)
 Changing the style of an HTML element, is a
variant of changing an HTML attribute
1. <!DOCTYPE html> <html>
2. <body>
3. <h2>What Can JavaScript Do?</h2>

4. <p id="demo">JavaScript can change the


style of an HTML element.</p>

5. <button type="button"
onclick="[Link]('demo')
.[Link]='35px'">Click Me!</button>

6. </body>
7. </html> 38
JavaScript Can Hide
HTML Elements
 Hiding
HTML elements can be done by
changing the display style
1. <!DOCTYPE html>
2. <html>
3. <body>
4. <h2>What Can JavaScript Do?</h2>

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


elements.</p>

6. <button type="button"
onclick="[Link]('demo').
[Link]='none'">Click Me!</button>

7. </body>
39
8. </html>
JavaScript Can Show
HTML Elements
1. <!DOCTYPE html>
2. <html>
3. <body>
4. <h2>What Can JavaScript Do?</h2>
5. <p>JavaScript can show hidden HTML
elements.</p>

6. <p id="demo" style="display:none">Hello


JavaScript!</p>

7. <button type="button"
onclick="[Link]('demo')
.[Link]='block'">Click Me!</button>

8. </body>
9. </html> 40
Java Script declaration
 JavaScript variables are containers for
storing data values.
 In this example, x, y, and z, are variables,

declared with the var keyword:


 Example

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

41
Java Script declaration: Eg
1. <!DOCTYPE html>
2. <html>
3. <body>
4. <h2>JavaScript Variables</h2>
5. <p id="demo"></p>
Output:
6. <script>
7. var price1 = 5; JavaScript Variables
8. var price2 = 6; The total is: 11
9. var total = price1 + price2;
10. [Link]("demo").innerHTML = "The total is: " +
total;
11. </script> Note:JavaScript accepts both
12. </body> </html> double and single quotes:
42
Note:
 Old JavaScript examples may use a type
attribute:

 <script type="text/javascript">.

 The type attribute is not required. JavaScript


is the default scripting language in HTML.

43
Output printing
 JavaScript can "display" data in different
ways:
1. Writing into an HTML element, using innerHTML
2. Writing into the HTML output, using [Link]()
3. Writing into an alert box, using [Link]()
4. Writing into the browser console, using [Link]()

44
document. Write
1. <!DOCTYPE html>
2. <html>
3. <body>
4. <h2>My First Web Page</h2>
5. <p>My first paragraph.</p>

6. <p>Never call [Link] after the document has finished loading. It


will overwrite the whole document.</p>

7. <script>
8. [Link](5 + 6);
9. </script>

10.</body>
11.</html> 45
document. Write
 Using [Link]() after an HTML document
is loaded, will delete all existing HTML
1. <!DOCTYPE html>
2. <html>
3. <body>
4. <h2>My First Web Page</h2>
5. <p>My first paragraph.</p>

6. <button type="button" onclick="[Link](5 + 6)">Try


it</button>

7. </body> 46

8. </html>
innerHTML
 To access an HTML element, JavaScript can
use the [Link](id)
method.
 The id attribute defines the HTML element.

The innerHTML property defines the HTML


content.
 Changing the innerHTML property of an

HTML element is a common way to display


data in HTML.
47
innerHTML
1. <!DOCTYPE html>
2. <html>
3. <body> My First Web Page
My First Paragraph.
4. <h2>My First Web Page</h2> 11
5. <p>My First Paragraph.</p>

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

7. <script>
8. [Link]("demo").innerHTML = 5 + 6;
9. </script>

10.</body>
11.</html>
48
window .alert
 Use an alert box to display data
 Window object is the global scope object
 Variables, Properties, and Methods by default

belong to the window object so can skip the


window keyword
 Specifying the window keyword is optional

49
window .alert
1. <!DOCTYPE html>
2. <html>
3. <body>

4. <h2>My First Web Page</h2>


5. <p>My first paragraph.</p>

6. <script>
7. [Link](5 + 6); or alert(5 + 6);
8. </script>

9. </body>
10. </html>

50
[Link]
 For debugging purposes, the [Link]()
method in the browser to display data. Web Page content
1. <!DOCTYPE html> Activate Debugging
2. <html> F12 on your keybord will activate debugging.
3. <body> Then select "Console" in the debugger menu.
4. <h2>Activate Debugging</h2> Then click Run again.
5. <p>F12 on your keybord will activate debugging.</p>
6. <p>Then select "Console" in the debugger menu.</p> Debugger Menu
7. <p>Then click Run again.</p>

8. <script>
9. [Link](5 + 6);
10. </script>

11. </body>
12. </html>
51
JavaScript Print
 JavaScript does not have any print object or
print methods.
 Cannot access output devices from

JavaScript.
 The only exception is that you can call the

[Link]() method in the browser to print


the content of the current window.

52
JavaScript Print
1. <!DOCTYPE html>
2. <html>
3. <body>

4. <h2>The [Link]()
Method</h2>

5. <p>Click the button to print the


current page.</p>

6. <button
onclick="[Link]()">Print
this page</button>

7. </body>
8. </html>
53
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. 54


Java script statements
 JavaScript statements are composed of:
1. Values
2. Operators
3. Expressions
4. Keywords, and
5. Comments
 Add a semicolon at the end of each executable statement.
var a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
 When separated by semicolons, multiple statements on one
line are allowed.
var a, b, c;
a = 5; b = 6; c = a + b; 55
Java script statements
 Ending statements with semicolon is not required, but highly
recommended.
 JavaScript ignores multiple spaces. You can add white space to
your script to make it more readable.
var person = "Hege";
var person="Hege";

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


var x = y + z;

 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.
56
Java script statements
 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.

[Link]("demo").innerHTML =
"Hello Dolly!";

 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
57
JavaScript Values
 The JavaScript syntax defines two types of
values:
1. Fixed values
2. Variable values
 Fixed values are called Literals.
 Variable values are called Variables.

58
JavaScript Literals
 Thetwo 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'

59
JavaScript Variables
 In a programming language, variables are used
to store data values.
 JavaScript uses the var keyword to declare variables.
 It's a good programming practice to declare all variables
at the beginning of a script.
 An equal sign is used to assign values to variables.
var x;
x = 6;

60
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:
1. Names can contain letters, digits, underscores, and dollar signs.
2. Names must begin with a letter
3. Names can also begin with $ and _
4. Names are case sensitive (y and Y are different variables)
5. Reserved words (like JavaScript keywords) cannot be used as names
 Used to name variables (and keywords, and functions, and labels). 61
Comments
 Not all JavaScript statements are "executed".
 Code after double slashes // or between /* and */ is treated as
a comment.
 Comments are ignored, and will not be executed
 Two categories
1. Single Line Comments //
// Change heading:
[Link]("myH").innerHTML = "My First Page";
// Change paragraph:
[Link]("myP").innerHTML = "My first paragraph.";
2. Multi-line Comments (a comment block) /* and */
/*
The code below will change
the heading with id = "myH“
*/
62
[Link]("myH").innerHTML = "My First Page";
Unit 1
Need of Scripting Language, Difference between client and server side scripting, Script tag
in HTML, Java Script declaration, Output printing – document. Write, innerHTML,
window .alert, [Link], Java script statements, Comments and Variables,
Lab 1 – Java Script Input and Output
Java script Operators -Logical, Bitwise, Arithmetic and Assignment operators, Java Script
Datatypes – numeric, Java Script Datatypes – non numeric, Conditional statements, If else
statements, Switch statements, Iteration statements,
Lab 2 – Java Script Operators and Conditions
Loop Controls – for loop, While loop, Do while Loop, For each loop, Arrays , Introduction and
declaring, Accessing arrays, Array Properties : index, input length, prototype, Array
Methods :concat, every, forEach,
Lab 3 - Looping Statements
Operators
 The numbers (in an arithmetic operation) are called operands.
 The operation (to be performed between the two operands) is
defined by an operator.

Operand Operator Operand


100 + 50

 Multiplication (*) and division (/) have higher precedence than


addition (+) and subtraction (-).
 When many operations have the same precedence (like addition
and subtraction), they are computed from left to right.
 Expressions in parentheses are fully computed before the value is
used in the rest of the expression.
64
Operator Precedence
Value Operator Description Example
21 () Expression grouping (3 + 4)
20 . Member [Link]
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
16 ** Exponentiation (ES2016) 10 ** 2
15 * Multiplication 10 * 5
15 / Division 10-May
15 % Division Remainder 10 % 5 65
Value Operator Description Example

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
8 | Bitwise OR x|y
7 && Logical AND x && y
6 || Logical OR x || y
5 ?? Nullish Coalescing x ?? y
4 ?: Condition ? "Yes" : "No"

66
Value Operator Description Example
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 67
Java script Operators -Logical,
Bitwise
 Comparison and Logical operators are used to
test for true or false.
Operator Description Comparing Returns
x == 8 FALSE
x == 5 TRUE
== equal to
x == "5" TRUE
x === 5 TRUE
=== equal value and equal type x === "5" FALSE

!= not equal x != 8 TRUE

x !== 5 FALSE
not equal value or not equal x !== "5" TRUE
!==
type
x !== 8 TRUE

> greater than x>8 FALSE

< less than x<8 TRUE

>= greater than or equal to x >= 8 FALSE

x <= 8 TRUE 68
<= less than or equal to
Java script Operators - Bitwise
 Bit operators work on 32 bits numbers.
 Any numeric operand in the operation is converted into a 32 bit number.

Operator Name Description Example

Operation Result Same as Result


& AND Sets each bit to 1 if both bits are 1
5&1 1 0101 & 0001 0001
| OR Sets each bit to 1 if one of two bits is 1
5|1 5 0101 | 0001 0101
^ XOR Sets each bit to 1 if only one of two bits is 1 ~5 10 ~0101 1010

NOT Inverts all the bits 5 << 1


~ 10 0101 << 1 1010

5^1 4 0101 ^ 0001 0100


Zero fill left Shifts left by pushing zeros in from the right
<<
shift and let the leftmost bits fall off 5 >> 1 2 0101 >> 1 0010

Shifts right by pushing copies of the leftmost 5 >>> 1


Signed right 2 0101 >>> 1 0010
>> bit in from the left, and let the rightmost bits
shift
fall off

Zero fill right Shifts right by pushing zeros in from the left,
>>> 69
shift and let the rightmost bits fall off
Java script Operators - Bitwise
 JavaScript stores numbers as 64 bits floating point numbers, but all bitwise
operations are performed on 32 bits binary numbers.
 Before a bitwise operation is performed, JavaScript converts numbers to 32
bits signed integers.
 After the bitwise operation is performed, the result is converted back to 64
bits JavaScript numbers.
<!DOCTYPE html>
<html>
Deci
mal
Binary <body>
<h2>JavaScript Bitwise AND</h2>
5 00000000000000000000000000000101 <p id="demo">My First Paragraph.</p>

1 00000000000000000000000000000001 <script>
[Link]("demo").innerHTML = 5 & 1;
5& 00000000000000000000000000000001 </script>
1 (1)
</body>
</html> 70
Java script Operators - Arithmetic
 Arithmeticoperators perform arithmetic on
numbers (literals or variables).
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement

71
Java script Operators - Assignment
Value Operator Description Example
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
72
Java Script Datatypes
 JavaScript variables can hold many data types:
numbers, strings, objects and more
 JavaScript has dynamic types. This means that the
same variable can be used to hold different data types
 To be able to operate on variables.
 Without data types, a computer cannot safely solve any
expressions
 Two classifications
1. Primitive types
2. Complex types
73
1. Primitive types
 A primitive data value is a single simple data value with no
additional properties and methods.
i. string typeof "John" // Returns "string"
ii. number typeof 3.14 // Returns "number"
typeof true // Returns "boolean"
iii. boolean typeof false // Returns "boolean"
iv. Undefined typeof x // Returns "undefined" (if x has no value)

2. Complex types
 The typeof operator returns "object" for objects, arrays, and null.
 The typeof operator does not return "object" for functions.

typeof {name:'John', age:34} // Returns "object"


i. Object typeof [1,2,3,4] // Returns "object" (not "array", see note below)
typeof null // Returns "object“

ii. function typeof function myFunc(){} // Returns "function"

Note : JavaScript arrays are objects 74


Java Script Datatypes - numeric
 The number type represents both integer and floating
point numbers.
 There are many operations for numbers, e.g.
multiplication *, division /, addition +, subtraction -, and
so on.
 Besides regular numbers, there are so-called “special
numeric values” which also belong to this data type:
1. Infinity, -Infinity and
2. NaN
3. BigInt

75
1. Infinity
 Infinity represents the mathematical Infinity ∞.
 It is a special value that’s greater than any

number.
1. We can get it as a result of division by zero:
 alert( 1 / 0 ); // Infinity

2. Just reference to it directly:


 alert( Infinity ); // Infinity

76
2. NaN
 NaN represents a computational error.
1. It is a result of an incorrect or an undefined
mathematical operation, for instance:
 alert( "not a number" / 2 ); // NaN, such division is erroneous

2. NaN is sticky. Any further operation


on NaN returns NaN:
 alert( "not a number" / 2 + 5 ); // NaN

77
3. BigInt
 The “number” type cannot represent integer values

1. larger than (253-1) (that’s 9007199254740991), or

2. less than -(253-1) for negatives.

 For cryptography or microsecond-precision timestamps, need really big


numbers.
 BigInt type was recently added to the language to represent integers of
arbitrary length.
 A BigInt value is created by appending n to the end of an integer

// the "n" at the end means it's a BigInt

const bigInt = 1234567890123456789012345678901234567890n;

Note: supported in Firefox/Chrome/Edge/Safari, but not in IE. 78


Java Script Datatypes – non numeric
1. String
 A string in JavaScript must be surrounded by quotes
 Double and single quotes are “simple” quotes. There’s
practically no difference between them in JavaScript.
 Backticks are “extended functionality” quotes. They
allow us to embed variables and expressions into a
string by wrapping them in ${…}
 In JavaScript, there are 3 types of quotes.
1. Double quotes: "Hello".
2. Single quotes: 'Hello'.
3. Backticks: `Hello`.
79
Java Script Datatypes – non numeric
1. String
 Double and single quotes:
1. let str = "Hello";
2. let str2 = 'Single quotes are ok too';
 Backticks:
1. // embed a variable
alert( `Hello, ${name}!` ); // Hello, John!
let phrase = `can embed another ${str}`;
2. // embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3

80
Java Script Datatypes – non numeric
2. Boolean
 The boolean type has only two values: true and false.
 This type is commonly used to store yes/no values: true means
“yes, correct”, and false means “no, incorrect”.

let nameFieldChecked = true; // yes, name field is checked

let ageFieldChecked = false; // no, age field is not checked

 Boolean values also come as a result of comparisons

let isGreater = 4 > 1;

alert( isGreater ); // true (the comparison result is "yes")


81
Java Script Datatypes – non numeric
3. The “null” value
 The special null value does not belong to any of the types described
earlier.
 It forms a separate type of its own which contains only the null value
let age = null; // age is unknown

 In JavaScript, null is not a “reference to a non-existing object” or a “null


pointer” like in some other languages.
 It’s just a special value which represents
1. “nothing”,
2. “empty” or
3. “value unknown”
82
Java Script Datatypes – non numeric
4. The “undefined” value
 The special value undefined also stands apart. It makes a type of its
own, just like null.
 The meaning of undefined is “value is not assigned”.
 If a variable is declared, but not assigned, then its value is undefined

let age; alert(age); // shows "undefined"


 Technically, it is possible to explicitly assign undefined to a variable.
 Normally, one uses null to assign an “empty” or “unknown” value to a
variable, while undefined is reserved as a default initial value for
unassigned things

let age = 100;


age = undefined; // change the value to undefined
alert(age); // "undefined" 83
Java Script Datatypes – non numeric
5. Objects and Symbols
 The object type is special.

 All other types are called “primitive” because their values can contain
only a single thing (be it a string or a number or whatever). In contrast,
objects are used to store collections of data and more complex entities.

 The symbol type is used to create unique identifiers for objects.

let user = new Object(); // "object constructor"


syntax let user = {}; // "object literal" syntax

key is a string (also called a “property name”) 84


value can be anything.
Conditional statements
 Conditional statements are used to decide the
flow of execution based on different conditions
 Different Types of Conditional Statements
 There are mainly three types of conditional statements
in JavaScript.
1. If statement
2. If…Else statement
3. If…Else If…Else statement

85
If statements
 UseIf statement if you want to check only a
specific condition

Syntax:
if (condition)
{
lines of code to be executed if condition is
true
}

86
If statements
<html>
<head>
<title>IF Statments!!!</title>

<script type="text/javascript">
var age = prompt("Please enter your age");
You are an adult
if(age>=18)
[Link]("You are an adult <br />");
if(age<18)
[Link]("You are NOT an adult <br />");
</script>
</head>
<body>
</body>
</html>

87
If else statements
 If….Else
statement checks two conditions
and execute a different set of codes.
Syntax:
if (condition)
{
lines of code to be executed if the condition
is true
}
else
{
lines of code to be executed if the condition
is false
} 88
If else statements
<html>
<head>
<title>If...Else Statments!!!</title>

<script type="text/javascript">
// Get the current hours Good Afternoon!!!
var hours = new Date().getHours();
if(hours<12)
[Link]("Good Morning!!!<br />");
else
[Link]("Good Afternoon!!!<br />");
</script>
</head>
<body>
</body>
</html>
89
If…Else If…Else statement
 Check more than two conditions
Syntax:
if (condition1)
{
lines of code to be executed if condition1 is true
}
else if(condition2)
{
lines of code to be executed if condition2 is true
}
Else
{
lines of code to be executed if both condition1
and condition2 are false 90

}
If…Else If…Else statement
<html>
<head>
<script type="text/javascript">
var one = prompt("Enter the first number");
var two = prompt("Enter the second number");
one = parseInt(one);
two = parseInt(two);

if (one == two)
[Link](one + " is equal to " + two + ".");
else if (one<two)
[Link](one + " is less than " + two + ".");
else
[Link](one + " is greater than " + two + ".");
20 is less than 40.
</script>
</head>
<body>
</body>
</html> 91
Switch statements
 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
}

1. The switch expression is evaluated once.


2. The value of the expression is compared with the values of each case.
3. If there is a match, the associated block of code is executed. 92

4. If there is no match, the default code block is executed.


<!DOCTYPE html>
<html>
<body>
<h2>JavaScript switch</h2>
<p id="demo"></p>
<script>
var text;
switch (new Date().getDay())
{ JavaScript switch
case 6:
text = "Today is Saturday"; Looking forward to the Weekend
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
[Link]("demo").innerHTML = text;
</script>
</body> 93
</html>
Unit 1
Need of Scripting Language, Difference between client and server side scripting, Script tag
in HTML, Java Script declaration, Output printing – document. Write, innerHTML,
window .alert, [Link], Java script statements, Comments and Variables,
Lab 1 – Java Script Input and Output
Java script Operators -Logical, Bitwise, Arithmetic and Assignment operators, Java Script
Datatypes – numeric, Java Script Datatypes – non numeric, Conditional statements, If else
statements, Switch statements, Iteration statements,
Lab 2 – Java Script Operators and Conditions
Loop Controls – for loop, While loop, Do while Loop, For each loop, Arrays , Introduction and
declaring, Accessing arrays, Array Properties : index, input length, prototype, Array
Methods :concat, every, forEach,
Lab 3 - Looping Statements
Iteration statements
 Run the same code over and over again, each time with a different
value
 JavaScript supports different kinds of loops:
1. for - loops through a block of code a number of times

2. for/in - loops through the properties of an object

3. for/of - loops through the values of an iterable object

4. while - loops through a block of code while a specified condition is true

5. do/while - also loops through a block of code while a specified condition


is true

95
Loop Controls – for loop
Syntax Example

for (statement 1; statement 2; statement 3) for (i = 0; i < 5; i++)


{ {
// code block to be executed text += "The number is " + i + "<br>";
} }

96
Loop Controls – for in
Syntax Example
for (key in object) var person = {fname:"John", lname:"Doe", age:25};
{ var text = "";
// code block to be executed var x;
} for (x in person) { text += person[x]; }
The for in loop iterates over a person object
Each iteration returns a key (x)
The key is used to access the value of the key
The value of the key is person[x]

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


for (variable in array) {
var txt = "";
code
var x;
}
for (x in numbers) { txt += numbers[x] + "<br>"; }
[Link]("demo").innerHTML = txt;
97
Do not use for in over an Array if the index order is important
Use a for loop, a for of loop, or [Link]() when the order is important
Loop Controls – forEach
 forEach() method calls a function (a callback function)
once for each array element.
<!DOCTYPE html>
<html> <body> JavaScript
[Link]()
Calls a function once
<h2>JavaScript [Link]()</h2>
for each array element.
<p>Calls a function once for each array element.</p>
45
<p id="demo"></p>
4
9
<script> 16
const numbers = [45, 4, 9, 16, 25]; 25
let txt = "";
[Link](myFunction);
[Link]("demo").innerHTML = txt;
function myFunction(value, index, array) { txt += value + "<br>"; } 98

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


For of loop
 for/of statement loops through the values of an iterable
object
 Iterable data structures such as
1. Arrays, Syntax
2. Strings,
for (variable of iterable)
3. Maps,
{
4. NodeLists, and more // code block to be executed
}
 variable - For every iteration the value of the next property is
assigned to the variable. Variable can be declared with const, let,
or var.
 iterable - An object that has iterable properties.
99
For of loop
Looping over an Array Looping over a String
let cars = ["BMW", "Volvo", "Mini"]; let language = "JavaScript";
let text = ""; let text = "";

for (let x of cars) for (let x of language)


{ {
text += x + "<br>"; text += x + "<br>";
} }
JavaScript For/Of Loop
J
JavaScript For/Of Loop a
v
The for/of statement loops through a
the values of an iterable object. S
c
BMW r
i
Volvo p
100
Mini t
While loop
 Loops through a block of code as long as a
specified condition is true

Syntax Example

while (condition) while (i < 10)


{ {
// code block to be executed text += "The number is " + i;
} i++;
}
Important Note:

If you forget to increase the variable used in the condition, the loop will never end.
101
This will crash your browser.
Do while Loop
 A variant of the while loop.
 This loop will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the condition
is true.
Syntax Example

do do
{ {
// code block to be executed text += "The number is " + i;
} i++;
while (condition); }
while (i < 10);

Important Note:

If you forget to increase the variable used in the condition, the loop will never end.
102
This will crash your browser.
What is an Array
 Arrays are complex variables.
 Store more than one value or a group of values under a
single variable name.
 Can store any valid value
 strings,
 numbers,
 objects,
 functions,
 other arrays
 Possible to create more complex data structures such as
an array of objects or an array of arrays
103
Arrays declaration/Creating an Array
 An ordered structure for storing multiple values or a group of values
 Enclosing a comma-separated list of values in square brackets ([])
Using Array literal
var myArray = [element0, element1, ..., elementN];

Using Array constructor


var myArray = new Array(element0, element1, ..., elementN);

Each value in an array is called an element,


104
Each element has a numeric position in an array, known as its
index
Example
3 Variables to store 3
values
var color1 = "Red";
var color2 = "Green";
var color3 = "Blue";

Using Array literal

var colors = ["Red", "Green",


"Blue "];
Using Array constructor

var arrayName = new Array();


var arrayName = new Array(Number length);
var arrayName = new Array(element1, element2, element3,...
elementN);
105
Adding New Elements to an Array
 Adding new elements in 4 ways
1. At the beginning of an array - unshift() method

2. At the end of an array - push() method

3. Multiple elements at once using


the push() and unshift() methods

4. Adding elements at any position -


splice() method

106
[Link] New - beginning of an array
 Toadd a new element at the beginning of an
array use the unshift() method

Example [Link]() method

var colors = ["Red", "Green", "Blue"];


[Link]("Yellow");
[Link](colors); // Prints: Yellow,Red,Green,Blue
[Link]([Link]); // Prints: 4

107
[Link] New - end of an array
 Toadd a new element at the end of an array,
simply use the push() method

Example [Link]() method

var colors = ["Red", "Green", "Blue"];


[Link]("Yellow");
[Link](colors); // Prints: Red,Green,Blue,Yellow
[Link]([Link]); // Prints: 4

108
[Link] - Multiple elements at once in
an array
 To add multiple elements at once using
the push() and unshift() methods

Example [Link]() and [Link]() method

var colors = ["Red", "Green", "Blue"];


[Link]("Pink", "Voilet");
[Link]("Yellow", "Grey");
[Link](colors); // Prints:
Yellow,Grey,Red,Green,Blue,Pink,Voilet
[Link]([Link]); // Prints: 7
109
[Link] New - any position of an array
 The splice() method is a very versatile array method that allows you to add
or remove elements from any index, using the
 Syntax: [Link](startIndex, deleteCount, elem1, ..., elemN).
1. First parameter is the index at which to start splicing
2. Second parameter is the number of elements to remove
3. Third parameter is a set of replacement elements

Example [Link]() method

var colors = ["Red", "Green", "Blue"];


[Link](colors + "<br>"); // Prints: Red,Green,Blue
// Insert two items at position one
var added = [Link](1, 0, "Pink", "Yellow");
[Link](colors + "<br>"); // Prints: Red,Pink,Yellow,Green,Blue 110
Removing Elements from an Array
 Removing elements in following ways
1. Removing Elements from End of a JavaScript Array
2. Removing Elements from Beginning of a JavaScript Array
3. Using Splice to Remove Array Elements
4. Removing Array Items By Value Using Splice
5. The Lodash Array Remove Method
6. Making a Remove Method
7. Explicitly Remove Array Elements Using the Delete Operator
8. Clear or Reset a JavaScript Array

111
Methods and Techniques - Removing
Elements from an Array
 Removing elements using 6 functions
1. pop - Removes from the End of an Array
var ar = [1, 2, 3, 4, 5, 6];
[Link](); // returns 6
[Link]( ar ); // [1, 2, 3, 4, 5]
2. shift - Removes from the beginning of an Array
var ar = ['zero', 'one', 'two', 'three'];
[Link](); // returns "zero"
[Link]( ar ); // ["one", "two", "three"]

112
Methods and Techniques - Removing
Elements from an Array
 Removing elements using 6 functions
3. splice - removes from a specific Array index
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
var removed = [Link](2,2);
[Link]( arr ); //[1, 2, 5, 6, 7, 8, 9, 0]

var list = ["bar", "baz", "foo", "qux"];


[Link]([Link](0, 2)); //["bar", "baz"]

Removing Array Items By Value Using Splice


var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
for( var i = 0; i < [Link]; i++) {
if ( arr[i] === 5) {
[Link](i, 1);
[Link](arr); //[1, 2, 3, 4, 6, 7, 8, 9, 0]
}
} 113
Methods and Techniques - Removing
Elements from an Array
 Removing elements using 6 functions
4. filter - allows you to programmatically remove elements from an
Array
 Unlike the splice method, filter creates a new array. filter() does not
mutate the array on which it is called, but returns a new array.
 filter() has a single parameter, a callback method. The callback is
triggered as the filter method iterates through the array elements.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];


var filtered = [Link](function(value, index, arr) { return value > 5; });
//filtered => [6, 7, 8, 9]
//array => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
114
Methods and Techniques - Removing
Elements from an Array
 Removing elements using 6 functions
5. The Lodash Array Remove Method
 Lodash provides a rich set of array manipulation methods, one being
remove.
 Works much like the array filter method, but sort of in reverse.
 It does not save the original array values, but removes matching
elements. It returns the matching elements as a new array.

var array = [1, 2, 3, 4];


var evens = _.remove(array, function(n) { return n % 2 === 0;});
[Link](array); // => [1, 3]
[Link](evens); // => [2, 4]
115
Methods and Techniques - Removing
Elements from an Array
 Removing elements using 6 functions
6. Explicitly Remove Array Elements Using the Delete
Operator
 Remove specific array elements using the delete operator
 Deleted item is not removed but becomes undefined.
 It does not affect the length property.(element is not actually
removed from the array)
 The memory is freed when there are no more references to the
value
var ar = [1, 2, 3, 4, 5, 6];
delete ar[4]; // delete element with index 4
[Link]( ar ); // [1, 2, 3, 4, undefined, 6]
alert( ar ); // 1,2,3,4,,6 116
Accessing arrays
 Array elements can be accessed by their index
 An index is a number that represents an element's
position in an array
 First item of an array is stored at index 0
 Last item stored at number of elements minus 1
 It’s a special type of objects which has numeric indexes
as keys. The typeof operator will return "object" for arrays.
Example
var fruits = ["Apple", "Banana", "Mango", "Orange",
"Papaya"];
[Link](fruits[0]); // Prints: Apple
[Link](fruits[1]); // Prints: Banana
[Link](fruits[2]); // Prints: Mango 117
[Link](fruits[[Link] - 1]); // Prints:
Array Properties : index
 An array elements (values) can be accessed using zero based
index (key). e.g. array[0].
 An array index must be numeric.
Example: Access Array Elements
var stringArray = new Array("one", "two", "three",
"four");
stringArray[0]; // returns "one"
stringArray[1]; // returns "two"
stringArray[2]; // returns "three"
stringArray[3];
Example: // using
Access Array returns "four"
for Loop
var stringArray = new Array("one", "two", "three",
"four");
for (var i = 0; i < [Link] ; i++)
{
stringArray[i]; 118

}
Array Properties : indexof
 The indexOf() method searches the array for the specified item, and
returns its position.
 Returns the position of the first occurrence if the item is found.
 Returns -1 if the item is not found.

Syntax

[Link](item, start)

Example :Search an array for the item "Apple“

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


var a = [Link]("Apple");
119
Array Properties : lastIndexOf
 Search from end to start, use the lastIndexOf() method.
 Returns the position of the last occurrence If the item to search for is
present more than once.
 Returns -1 if the item is not found.

Syntax

[Link](item, start)

Example :Search an array for the item "Apple“

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


var a = [Link]("Apple");
120
Array Properties : input length
 "length" property - returns number of elements in the
array.
 Array length is always greater than the index of any of its
element
<script>
// JavaScript to illustrate length property Syntax
function func()
Return the length of an array:
{
// length property for string [Link]
[Link]("GFG".length)
Set the length of an array:
// length property for array
[Link] = number
[Link]([1,2,3,4,5,6,7,8,9].lengt
h); 121

}
Looping Through Array Elements
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
[Link]([Link]); // Prints: 5

// Iterates over array elements using for loop


for(var i = 0; i < [Link]; i++)
{
[Link](fruits[i] + "<br>"); // Print array element
}

// Iterates over array elements using for of loop


for(var fruit of fruits)
{
[Link](fruit + "<br>"); // Print array element
}

// Iterates over array elements using for in loop


for(var i in fruits)
{
[Link](fruits[i] + "<br>");
} 122
Array Properties : prototype
 Make a new array method that transforms array values
into upper case
Syntax
[Link] = value

 The prototype constructor allows you to add new


properties and methods to the Array() object.
 When constructing a property, ALL arrays will be given
the property, and its value, as default.
 When constructing a method, ALL arrays will have this
method available.

123
Array Properties : prototype
 Note: [Link] does not refer to a single array,
but to the Array() object itself.
 Note: Prototype is a global object constructor which is
available for all JavaScript objects.
Make a new array method that transforms array values into upper case
[Link] = function() {
for (i = 0; i < [Link]; i++) {
this[i] = this[i].toUpperCase();
}
};

Make an array, then call the myUcase method


var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](); 124
Array Methods :concat
 The concat() method is used to join two or more arrays.
 This method does not change the existing arrays, but
returns a new array, containing the values of the joined
arrays.
Syntax

[Link](array2, array3, ..., arrayX)

Example : Join three arrays


var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var kai = ["Robin"];
var children = [Link](stale, kai);
125
Array Methods : every
 The every() method checks if all elements in an array
pass a test (provided as a function).
 The every() method executes the function once for each
element present in the array:
1. If it finds an array element where the function returns
a false value, every() returns false (and does not check the
remaining values)

2. If no false occur, every() returns true


Syntax

[Link](function(currentValue, index, arr), thisValue)


126
Array Methods : every
Parameter Description
function(currentValue, index, arr) Required. A function to be run for each element in the array.
Function arguments:
Argument Description
currentValue Required. The value of the current element
index Optional. The array index of the current element
arr Optional. The array object the current element belongs to
thisValue Optional. A value to be passed to the function to be used as
its "this" value.
If this parameter is empty, the value "undefined" will be
passed as its "this" value

127
Array Methods : every
<!DOCTYPE html> <html> <body>
<p>Click the button to check if every element in the array has a value above a
specific number.</p>
<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p>All ages above minimum? <span id="demo"></span></p>
<script>
var ages = [32, 33, 12, 40];
function checkAdult(age) {
return age >= [Link]("ageToCheck").value;
}
function myFunction() {
[Link]("demo").innerHTML = [Link](checkAdult);
}
</script> </body> </html>

128
Array Methods : every
<script>
var survey = [
{ name: "Steve", answer: "Yes"},
{ name: "Jessica", answer: "Yes"},
{ name: "Peter", answer: "Yes"},
{ name: "Elaine", answer: "No"}
];
function isSameAnswer(el, index, arr) {
if (index === 0){
return true;
} else {
return ([Link] === arr[index - 1].answer);
}
}
function myFunction() {
[Link]("demo").innerHTML = [Link](isSameAnswer);
}
129
</script>
Array Methods :forEach
 forEach() method calls a function (a callback function)
once for each array element.
<!DOCTYPE html>
<html> <body> JavaScript
[Link]()
Calls a function once
<h2>JavaScript [Link]()</h2>
for each array element.
<p>Calls a function once for each array element.</p>
45
<p id="demo"></p>
4
9
<script> 16
const numbers = [45, 4, 9, 16, 25]; 25
let txt = "";
[Link](myFunction);
[Link]("demo").innerHTML = txt;
function myFunction(value, index, array) { txt += value + "<br>"; } 130

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


Points to Remember
 An array is a special type of variable that stores multiple values
using a special syntax.
 An array can be created using array literal or Array constructor
syntax.
 Array literal syntax: var stringArray = ["one", "two", "three"];
 Array constructor syntax:var numericArray = new Array(3);
 A single array can store values of different data types.
 An array elements (values) can be accessed using zero based
index (key). e.g. array[0].
 An array index must be numeric.
 Array includes length property and various methods to operate on
array objects. 131
References
 [Link]
 [Link]
 [Link]

132
133
134
135
136

You might also like