UNIT-3 Javascript: Introduction Java Script
UNIT-3 Javascript: Introduction Java Script
UNIT-3 Javascript: Introduction Java Script
JAVASCRIPT
INTRODUCTION JAVA SCRIPT:
Script means small piece of code. Java script you can easily create
interactive web pages. It is designed to add interactivity to HTML
pages. Scripting languages are two kinds one is client-side other one
is servers-side scripting. In general client-side scripting is used for
verifying simple validation at client side, server-side scripting is used
for database verifications. VBScript, java script and J script are
examples for client-side scripting and ASP,JSP, servlets etc. are
examples of server-side scripting.
Web pages are two types
1. Static web page
2. Dynamic webpage
Static web page where there is no specific interaction with the
client
Dynamic web page which is having interactions with client and as
well as
validations can be added.
Simple HTML script is called static web page, if you add script to
HTML page
it is called dynamic page. Netscape navigator developed java script.
Microsoft‟s version of java script is J script.
Java script code as written between <script> ----</script>tags
All java script statements end with a semicolon
Java script ignores white space
Java script is case sensitive language
Script program can save as either. Js or. html
Similarities between java script and java:
1. Both java script and java having same kind of operators
2. Java script uses similar control structures of java
3. Nowadays both are used as languages for use on internet.
4. Labeled break and labeled continue both are similar
1
Difference between java script and java:
1. Java is object –oriented programming language where as java
script is object-based
programming language.
2. Java is full –featured programming language but java script is not.
3. Java source code is first compiled and the client interprets the
code. Java script code
is not compiled, only interpreted.
4. Inheritance, polymorphism, threads are not available in JavaScript.
The syntax of the script tag is as follows:
<script language=‟‟scripting language name‟‟>
-----------------------------------------
</script>
The language attribute specifies the scripting language used in the
script. Both Microsoft internet explorer and Netscape navigator use
java script as the default scripting language. The script tag may be
placed in either the head or the body or the body of an HTML
document.
Ex: <script language=‟‟java script‟‟>
-------------
--------------
-----------
</script>
Variable declaration in java script:
Variables are declared with the var key word
Var variable name=value
Ex: var x=20
The variable is preceded by the var, it is treated as local variable
otherwise
variable is treated as global variable.
web technologies
Comments in java script:
Single line comment- //
Multi-line comment- /**/
operators in java script:
2
Arithmetic operators
Relational operators
Logical operators
Assignment operator
Increment decrement operators
Conditional operator (ternary)
Bitwise operators
Control structures:
If statement
Switch
While
Do-while
For
Break
Continue
Control structures syntax and working as same as java language.
Basics Of JavaScript:
Features of JavaScript
History of JavaScript
4
1995, the language was finally renamed to 'JavaScript'. From then,
JavaScript came into existence.
Application of JavaScript
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog
box, confirm dialog box and prompt dialog box),
o Displaying clocks etc.
JavaScript Example
1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and
method). For example: car, pen, bike, chair, glass, keyboard, monitor
etc.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
5
JavaScript Object by object literal
1. object={property1:value1,property2:value2.....propertyN:valueN}
1. var objectname=new Object();
Here, you need to create function with arguments. Each argument value
can be assigned in the current object by using this keyword.
6
attributes of the property.
found.
7
object.
non-configurable.
prototype of a specified
8
20 Object.values() This method returns an
array of values.
Primitives:
JavaScript allows us to work with primitives (strings, numbers, etc.) as if
they were objects. They also provide methods to call as such. We will
study those soon, but first we’ll see how it works because, of course,
primitives are not objects (and here we will make it even clearer).
Let’s look at the key distinctions between primitives and objects.
A primitive
Is a value of a primitive type.
There are 7 primitive
types: string, number, bigint, boolean, symbol, null and undefined.
An object
Is capable of storing multiple values as properties.
Can be created with {}, for instance: {name: "John", age: 30}. There are
other kinds of objects in JavaScript: functions, for example, are objects.
Objects are “heavier” than primitives. They require additional resources
to support the internal machinery.
A primitive as an object
Here’s the paradox faced by the creator of JavaScript:
There are many things one would want to do with a primitive like a string
or a number. It would be great to access them using methods.
Primitives must be as fast and lightweight as possible.
The solution looks a little bit awkward, but here it is:
1. Primitives are still primitive. A single value, as desired.
2. The language allows access to methods and properties of strings,
numbers, booleans and symbols.
3. In order for that to work, a special “object wrapper” that provides the
extra functionality is created, and then is destroyed.
9
The “object wrappers” are different for each primitive type and are
called: String, Number, Boolean and Symbol. Thus, they provide
different sets of methods.
For instance, there exists a string method str.toUpperCase() that returns
a capitalized str.
Here’s how it works:
let str = "Hello";
Assignment operators
Comparison operators
Arithmetic operators
Bitwise operators
Logical operators
String operators
Conditional (ternary) operator
Comma operator
Unary operators
Relational operators
JavaScript has both binary and unary operators, and one special ternary
operator, the conditional operator. A binary operator requires two
operands, one before the operator and one after the operator:
10
operand1 operator operand2
Copy to Clipboard
For example, 3+4 or x*y.
operator operand
Copy to Clipboard
or
operand operator
Copy to Clipboard
For example, x++ or ++x.
Assignment operators
An assignment operator assigns a value to its left operand based on the
value of its right operand. The simple assignment operator is equal (=),
which assigns the value of its right operand to its left operand. That is, x
= y assigns the value of y to x.
There are also compound assignment operators that are shorthand for
the operations listed in the following table:
11
Remainder Assignment x%=y x=x%y
Control Statement
Every programming language, basically, has two types of control
statements as follows:
YES or NO.
12
Iterative Statements (Loop): Until and unless the expression or
themselves.
1. Conditional Statements
This is where the flow of the execution in a program is decided.
condition is passed, if that is true, then the program moves to the next
step and if the condition is False, then the program moves to another
step. These statements are executed only once, unlike Loop statements.
IF
when you want to check for a specific condition. With the IF condition,
Syntax:
13
if (condition) {
IF-ELSE
and two
Syntax:
if (condition)
else {
As you can see, when the condition is satisfied in IF-ELSE, the first block
of code will be executed and if the condition isn’t satisfied, the second
14
SWITCH
execute one code out of the multiple code block execution possibilities,
Syntax:
switch (expression) {
case a:
Break;
case b:
Break;
case n:
Break;
default:
15
//default code to be executed if none of the above case is executed
check and compared with the cases included. If the expression passed
matches with the case a, the code block inside the case is executed.
The same applies for case b and n, and when the expression passed
matches with none of the cases mentioned, it code enters default case
2. Iterative Statement
Looping, for any programming language, is a powerful tool in order to
satisfied. A very basic example can be, to print “Hello World” for 10
times. Now, writing the same print statement with “Hello world“ for 10
straight times will be time-consuming and will impact the execution time.
And this is where looping comes handy. There are three Iterative
syntax.
WHILE
16
one of the control flow statement, which executes a code block when the
condition is satisfied. But unlike IF, while keeps repeating itself until the
executes code ‘if’ the condition is satisfied while the while keeps
Syntax:
while (condition)
DO-WHILE
Similar to a while loop, with a twist that keeps a condition at the end of
the loop. Also known as Exit Control Loop, DO-WHILE executes the
Syntax:
while
17
//code block to be executed when condition is satisfied
} (condition)
FOR
a for loop will execute a code block for a number of times. Compared to
Syntax:
With initialize, it starts the loop, here a declared variable is used. Then
the exit condition for the loop is checked in condition part. When this
condition returns true, the code block inside is executed. When, in case,
and the variable is assigned an updated value. Values are updated until
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1. var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by ,
(comma).
1. var arrayname=new Array();
Let's see the list of JavaScript array methods with their description.
Methods Description
19
merged arrays.
copywithin() It copies the part of the given array with its own
elements
array element.
20
find() It returns the value of the first element in the given
array
of an array.
element.
21
element
22
sort() It returns the element of the given array in a sorted
order.
specified array.
given array.
Functions:
JavaScript functions are used to perform operations. We can call
JavaScript function many times to reuse the code.
23
The syntax of declaring function is given below.
1. function functionName([arg1, arg2, ...argN]){
2. //code to be executed
3. }
JavaScript Functions can have 0 or more arguments.
Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
Method Description
arguments.
24
call() It is used to call a function contains this value and an
argument list.
Constructor:
A JavaScript constructor method is a special type of method which is
used to initialize and create an object. It is called when memory is
allocated for an object.
Points to remember
Expressions
Below is the example of the JavaScript Regular Expressions.
Example:
<script>
function GFGFun() {
var n = str.search(/GeeksforGeeks/i);
document.write(n);
25
}
GFGFun();
</script>
26
Expression
s Description
with |
Regular Expression Patterns :
Metacharacters are characters with a special meaning:
Examples:
Metacharacte
r Description
27
Quantif
ier Description
in a string:
Expression :
Use a case insensitive regular expression to replace gfG with
GeeksforGeeks in a string:
Example:
<script>
function myFunction() {
document.write(txt);
AngularJS Expressions
28
In AngularJS, expressions are used to bind application data to HTML.
AngularJS resolves the expression, and return the result exactly where
the expression is written.
1. ng-bind="expression".
Eg:{{ 5 + 5 }} or {{ firstName + " " + lastName }}
$eval:
The Angular JS $eval method is used to executes the AngularJS
expression on the current scope and returns the result.
29
In AngularJS,expressions are similar to JavaScript code snippets
that are usually placedin bindings such as {{expression}}.
Syntax:
$eval([expression], [locals]);
Strings:
The JavaScript String is an object that represents a sequence of
characers.
1. By string literal
1) By string Literal:
Example:
30
<script>
Document.write(str);
</script>
Example:
<script>
Document.write(stringname);
</script>
String Methods:
Methods Description
31
charAt() It provides the char value
present at the specified index.
32
assign positive as well negative
index.
The JavaScript String charAt() method returns the character at the given
index.
1. <script>
33
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>
Output: v
1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>
Output : javascript concat example
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>
Output : 11
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.lastIndexOf("java");
4. document.write(n);
34
5. </script>
Output : 16
1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>
Output : javascript tolowercase example
1. <script>
2. var s1="JavaScript toUpperCase Example";
3. var s2=s1.toUpperCase();
4. document.write(s2);
5. </script>
Output : JAVASCRIPT TOUPPERCASE EXAMPLE
1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>
Output : cde
35
8) JavaScript String trim() Method
1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>
Output : javascript trim
1. <script>
2. var str="This is JavaTpoint website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>
Form Validation:
AngularJS performs form validation on the client-side. AngularJS
monitors the state of the form and input fields (input, text-area, select),
and notify the user about the current state. AngularJS also holds
information about whether the input fields have been touched, modified,
or not.
Form input fields have the following states:
$untouched: It shows that field has not been touched yet.
$touched: It shows that field has been touched.
$pristine: It represents that the field has not been modified yet.
$dirty: It illustrates that the field has been modified.
$invalid:It specifies that the field content is not valid.
$valid:It specifies that the field content is valid.
These all are the properties of the input field which can be either true or
false.
Forms have the following states:
$pristine: It represents that the fields has not been modified yet.
$dirty: It illustrates that one or more fields has been modified.
$invalid:It specifies that the form content is not valid.
$valid:It specifies that the form content is valid.
$submitted:It specifies that the form is submitted.
36
These all are the properties of the form which can be either true or
false.
This states can be used to show meaningful messages to the user.
Custom validation:To create your own validation function add a new
directive to your application, and deal with the validation inside a
function with certain specified arguments.
Example:
AngularJS Forms:
The HTML form is a collection of input controls where user can
enter the data. Here, you will learn how to display AngularJS form
and submit the data.
37
Sample AngularJS Form
1. Create an HTML page and wrap all the necessary input controlls
into <form> tag.
2. Create the AngularJS application module in the <script> tag.
3. Create studentController in application module.
4. Create originalStudent object and attach to the $scope with
required properties. This will stay unchanged during entire life
cycle.
5. Create new student object and attach to the $scope and copy all
the properties and values from originalStudent. This student object
will be bound to the form using ng-model directive. Therefore, if
user changes form values then the student object will also get
changed.
6. Create submitStudnetForm function which will get called when
user submits the form using Submit button. Here, send http POST
request to the remote server to submit the data using $http
service.
38
7. Create resetForm() function, which will reset the form values to the
originalStudent values by copying it to student object.
8. Apply ng-app, ng-controller directives.
9. Apply ng-model directives to each HTML input element to bind
appropriate properties of student object.
10. Apply ng-submit directive to form which will call
submitStudentForm() on the form submit event.
11. Apply ng-click directive to reset button which will call
resetForm() on the button click event.
39
Team collaboration
Single-page applications are excellent when more than one developer
is working on the same project. It allows backend developers to focus
on the API, while the frontend developers can focus on creating the
user interface based on the backend API.
Caching
The application sends a single request to the server and stores all the
received information in the cache. This proves beneficial when the
client has poor network connectivity.
Fast and responsive
As only parts of the pages are loaded dynamically, it improves the
website’s speed.
Debugging is easier
Debugging single page applications with chrome is easier since such
applications are developed using like AngularJS Batarang and React
developer tools.
Linear user experience
Browsing or navigating through the website is easy.
Disadvantages:
SEO optimization
SPAs provide poor SEO optimization. This is because single-page
applications operate on JavaScript and load data at once server. The
URL does not change and different pages do not have a unique URL.
Hence it is hard for the search engines to index the SPA website as
opposed to traditional server-rendered pages.
Browser history
A SPA does not save the users’ transition of states within the website.
A browser saves the previous pages only, not the state transition.
Thus when users click the back button, they are not redirected to the
previous state of the website. To solve this problem, developers can
equip their SPA frameworks with the HTML5 History API.
Security issues
Single-page apps are less immune to cross-site scripting (XSS) and
since no new pages are loaded, hackers can easily gain access to
the website and inject new scripts on the client-side.
Memory Consumption
Since the SPA can run for a long time sometimes hours at a time, one
needs to make sure the application does not consume more memory
than it needs. Else, users with low memory devices may face serious
performance issues.
40
Disabled Javascript
Developers need to chalk out ideas for users to access the
information on the website for browsers that have Javascript disabled.
When to use SPA
SPAs are good when the volume of data is small and the website that
needs a dynamic platform. It is also a good option for mobile
applications. But businesses that depend largely on search engine
optimizations such as e-commerce applications must avoid single-page
applications and opt for MPAs.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js ">
</script>
</head>
<body>
<script type="text/ng-template"
id="first.html">
<h1>First Page</h1>
<h2 style="color:green">
Welcome to GeeksForGeeks
</h2>
41
<h3>{{message}}</h3>
</script>
<script type="text/ng-template"
id="second.html">
<h1>Second Page</h1>
<h2 style="color:green">
</h2>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template"
id="third.html">
<h1>Third Page</h1>
<h2 style="color:green">
Know about us
</h2>
<h3>{{message}}</h3>
</script>
pages dynamically-->
<a href="#/">First</a>
<a href="#/second">Second</a>
<a href="#/third">Third</a>
<div ng-view></div>
<script>
42
var app = angular.module('myApp', []);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'first.html',
controller : 'FirstController'
})
.when('/second', {
templateUrl : 'second.html',
controller : 'SecondController'
}}
.when('/third', {
templateUrl : 'third.html',
controller : 'ThirdController'
})
.otherwise({redirectTo: '/'});
});
app.controller('FirstController', function($scope) {
});
app.controller('SecondController', function($scope) {
43
});
app.controller('ThirdController', function($scope) {
});
</script>
</body>
</html>
Example :
44
45