0% found this document useful (0 votes)
23 views

C6 JavaScript

Uploaded by

michaeljohn9808
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

C6 JavaScript

Uploaded by

michaeljohn9808
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 66

JAVASCRIPT

• ORIGIN OF JAVASCRIPT
– JavaScript originated with Netscape and it is
invented by Brendan eich, it was initially named
mocha.
– Then it is renamed as liveScript.
– In late 1995 LiveScript became a joint venture of
Netscape and Sun Microsystems, and its name
again was changed, this time to JavaScript.
– A language standard for JavaScript was developed
in the late 1990s by the European Computer
Manufacturers Association (ECMA) as ECMA-262.
– The official name of the standard language is
ECMAScript.
• Components of JavaScript
– JavaScript can be divided into three parts: the
core, client side, and server side.
– The core is the heart of the language, including its
operators, expressions, statements, and
subprograms.
– Client-side JavaScript is a collection of objects that
support the control of a browser and interactions
with users.
– Server-side JavaScript is a collection of objects
that make the language useful on a Web server.
• Difference between object based and object oriented.
– Object-oriented languages do not have the inbuilt objects

– whereas Object-based languages have the inbuilt objects,

– Examples of object-oriented programming are Java, C#,


Smalltalk, etc. whereas the examples of object-based
languages are JavaScript, VBScript, etc.
• JavaScript is a cross platform, object based scripting language
invented specifically for use in web browsers to make websites
more dynamically and attractive. JavaScript is mainly used as a
client side scripting language.

• Where JavaScript is used?


– JavaScript is used to create interactive websites. It is mainly
used for:
• Client-side validation

• Dynamic drop-down menus

• Displaying data and time

• Displaying popup windows and dialog boxes (like alert dialog box,
confirm dialog box and prompt dialog box)

• Displaying clocks etc.


• Why JavaScript?
– JavaScript is present in most web pages today.

– It helps in data form validation.

– JavaScript allows them to make the page dynamic.


• For example, HTML allows for making text bold, creating text
boxes, and creating buttons, whereas JavaScript allows for
changing text on the page, creating pop-up messages, and
validating text in text boxes to make sure required fields have
been filled.

– JavaScript makes web pages more dynamic by allowing


users to interact with web pages, click on elements, and
change the pages.
• Features of JavaScript:
– A great programming tool for html:
• JavaScript is powerful scripting languages that help
HTML designers to effectively and interactively design
websites.
– Handles Dynamic behavior:
• JavaScript is such a powerful scripting language which
has features to achieve dynamic behavior in web
pages.
– Browser detection:
• One of the powerful features of JavaScript is its ability
to detect client browser. Browser detection features of
JavaScript helps to achieve independent platforms.
– Saves time:
• This helps in saving the processing time of the server
because JavaScript initially creates the validation on the
client side.
– DOM:
• Client side JavaScript is embedded inside XHTML and this
embedded in JavaScript is used along with DOM for
control over the browser by means of objects.
– Popular Scripting Language:
• JavaScript has a simple rules and procedures that make it
easier to use and learn for programmers. This has made
JavaScript a popular client-side scripting languages.
– Interpreted languages:
• It is interpreted language, meaning that it can be used or
executed with ease without pre compilation.
• Advantages of JavaScript
– Less server interaction − You can validate user input
before sending the page off to the server. This saves server
traffic, which means less load on your server.

– Immediate feedback to the visitors − They don't have to


wait for a page reload to see if they have forgotten to
enter something.

– Increased interactivity − You can create interfaces that


react when the user hovers over them with a mouse or
activates them via the keyboard.

– Richer interfaces − You can use JavaScript to include such


items as drag-and-drop components.
• Disadvantages/Limitations of JavaScript

– Client-side JavaScript does not allow the reading


or writing of files. This has been kept for security
reason.

– JavaScript cannot be used for networking


applications because there is no such support
available.

– JavaScript doesn't have any multithreading or


multiprocessor capabilities.
• Three layers of web
– Structure or content layer
• The structure or content layer of a web page is the underlying HTML code
of that page.
– Style or presentation layer
• The style or presentation layer dictates how a structured HTML document
will look to a site's visitors. This layer is defined by CSS (Cascading Style
Sheets).
– Behavior
• The behavior layer is the layer of a Web page that can respond to different
user actions or make changes to a page based on a set of conditions.
• JavaScript Syntax:
– The syntax refers to a set of rules the language
will be written.

– The <script> tag alerts the browser program to


start interpreting all the text between these tags
as a script. A simple syntax of your JavaScript will
appear as follows.
• The script tag takes two important attributes −

– Language − This attribute specifies what scripting language


you are using. Typically, its value will be javascript. Although
recent versions of HTML (and XHTML, its successor) have
phased out the use of this attribute.

– Type − This attribute is what is now recommended to


indicate the scripting language in use and its value should be
set to "text/javascript".
• Where to put Javascript ?
• 3 Places to put JavaScript code
– Between the body tag of html
– Between the head tag of html
– In .js file (external javaScript)

• JavaScript Example : code between the body tag


– In the example, we have displayed the dynamic
content using JavaScript. Let’s see the simple
example of JavaScript that displays alert dialog
box.
<Body>
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
</body>
• JavaScript Example : code between the head tag
– In this example, we are creating a function msg(). To
create function in JavaScript, you need to write function
with function_name as given below.
– To call function, you need to work on event. Here we are
using onclick event to call msg() function.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/
> </form>
</body>
</html>
function msg(){
alert("Hello Javatpoint");
}
• Let’s include the JavaScript file into html page. It calls the
JavaScript function on button click.

<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
• JavaScript Comment:
– Standard java- style comment lines and blocks are
supported in JavaScript also.
– In general, any text inside a comment block is
ignored by the interpreter.
– Single-line comments are preceded by a double
forward-slash(//), and multiline comments are
enclosed by the symbols /* and */.
• JavaScript keywords:
– Keywords are the reserved and cannot be used as
identifiers. The complete list is:
• Primitive Data Types
– Every variable has a data type. Data type indicates
what kind of data the variable holds. In JavaScript,
the type of data variable hold can be grouped into
two categories:
• Primitive types
• Composite types

• Primitive types in JavaScript


– JavaScript supports five primitive Data types:
• Number
• Strings
• Booleans
• Undefined
• Null
Primitive Data types in JavaScript

Data Type Description

String represents sequence of characters e.g.


"hello"
Number represents numeric values e.g. 100

Boolean represents boolean value either false or


true
Undefined represents undefined value

Null represents null i.e. no value at all


• Composite types of JavaScript:
– From primitive types mentioned above, we can derive
composite types. A composite type can consist of
numbers, Booleans, undefined and null values. The tree
types of composite types available in JavaScript are
Objects, arrays and functions.

Data Type Description


Object represents instance through which we can access
members
Array represents group of similar values
RegExp represents regular expression
• Screen Output And Keyboard Input
– JavaScript is special from other languages because
it can accept input and produce output on the
basis of that input in the same page.
– That mean, we don’t have to go to other page or
refresh the page to see the output.

• Methods to show output


– Document. write() or document.writeln()
– Windows. alert()
– Window. Status
• Methods for taking input from user
– Window.prompt()
– Window.confirm()
• Document.write() and document.writeln()
• JavaScript provide two methods for displaying
text on a write page:
document.write(“expression”) ;
document.writeln(“expression”);

• Note we used a semicolon above in each of the two


statements. Any JavaScript statement must end with
a semicolon to mark the end of the statement.
• In object oriented language, document is an object
and both write and writeln are methods (action or
behavior). As noted earlier, both of these actions
print text.
• It print any text that is enclosed inside the double
quotation marks(“”)or single quotation mark(‘ ’);
• Difference between these two methods:
– The “write” method prints the text to the browser without
attaching a carriage return at the end of the text while the
“writeln” method adds a carriage return to the end of the
text.
– The document.writeln() method is similar to write(), only it
adds a newline character after each statement.
<script type=”text/javascript”>
document.write("<h3>Hello World!</h3>”);
document.write("<p>Have a nice day!</p>");
</script>

o/p: Hello World!


Have a nice day!
<script type=”text/javascript”>
document.writeln(“<pre>Line 1”);
document.writeln("Line 2</pre>");
</script>

o/p: Line 1
Line 2
• JavaScript Operators
– JavaScript operators are symbols that are used to perform
operations on operands. For example:

var sum=10+20;
– Here, + is the arithmetic operator and = is the assignment
operator.

– There are following types of operators in JavaScript.


– Arithmetic Operators
– Comparison (Relational) Operators
– Bitwise Operators
– Logical Operators
– Assignment Operators
• JavaScript Arithmetic Operators
– Arithmetic operators are used to perform arithmetic
operations on the operands. The following operators are
known as JavaScript arithmetic operators.

Operator Description Example


+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
• JavaScript Comparison Operators
– The JavaScript comparison operator compares the two
operands. The comparison operators are as follows:

Operator Description Example


== Is equal to 10==20 = false
=== Identical (equal and of 10==20 = false
same type)
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false
• JavaScript Bitwise Operators
– The bitwise operators perform bitwise operations on
operands. The bitwise operators are as follows:

Operator Description Example


& Bitwise AND (10==20 & 20==33) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift (10>>>2) = 2
with Zero
• JavaScript Logical Operators
– The following operators are known as JavaScript logical
operators.
Operator Description Example
&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true
• JavaScript Assignment Operators
– The following operators are known as JavaScript assignment operators.

Operator Description Example


= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0
• JavaScript If-else
– The JavaScript if-else statement is used to execute the code whether
condition is true or false. There are three forms of if statement in
JavaScript.
– If Statement
– If else statement
– if else if statement
• JavaScript If statement
– It evaluates the content only if expression is true. The signature of
JavaScript if statement is given below.
if(expression){
//content to be evaluated
}

Let’s see the simple example of if statement in javascript.


<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10"); }
</script>
• JavaScript If...else Statement
– It evaluates the content whether condition is true of false. The syntax
of JavaScript if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

<script>
var a=20;
if(a%2==0){
document.write("a is even number");
Output of the above example
}
a is even number
else{
document.write("a is odd number");
}
</script>
• JavaScript If...else if statement
– It evaluates the content only if expression is true from several
expressions. The signature of JavaScript if else if statement is given
below.

if(expression1){ <script>
//content to be evaluated if expression1 is true var a=20;
} if(a==10){
document.write("a is equal to 10");
else if(expression2){ }
//content to be evaluated if expression2 is true else if(a==15){
} document.write("a is equal to 15");
}
else if(expression3){ else if(a==20){
//content to be evaluated if expression3 is true document.write("a is equal to 20");
} }
else{ else{
document.write("a is not equal to 10, 15 or 20");
//content to be evaluated if no expression is true }
} </script>

Output of the above example


a is equal to 20
• JavaScript Switch
– The JavaScript switch statement is used to execute one code from multiple expressions.
It is just like else if statement that we have learned in previous page. But it is convenient
than if..else..if because it can be used with numbers, characters etc.
– The signature of JavaScript switch statement is given below.
<script>
switch(expression){ var grade='B';
case value1: var result;
code to be executed; switch(grade){
break; case 'A':
case value2: result="A Grade";
code to be executed; break;
break; case 'B':
...... result="B Grade";
break;
default: case 'C':
code to be executed if above values are not matched; result="C Grade";
} break;
default:
Output of the above example result="No Grade";
B Grade }
document.write(result);
</script>
• JavaScript Loops
– The JavaScript loops are used to iterate the piece of code
using for, while, do while loops. It makes the code
compact. It is mostly used in array.
– There are four types of loops in JavaScript.
• for loop

• while loop

• do-while loop
• JavaScript For loop
– The JavaScript for loop iterates the elements for the fixed
number of times. It should be used if number of iteration
is known. The syntax of for loop is given below.
for (initialization; condition; increment) <script>
{ for (i=1; i<=5; i++)
code to be executed {
} document.write(i + "<br/>")
}
Output: </script>

1
2
3
4
5
• JavaScript while loop
– The JavaScript while loop iterates the elements for the
infinite number of times. It should be used if number of
iteration is not known. The syntax of while loop is given
below.
<script>
while (condition) var i=11;
{ while (i<=15)
code to be executed {
} document.write(i + "<br/>");
i++;
}
Output: </script>

11
12
13
14
15
• JavaScript do while loop
– The JavaScript do while loop iterates the elements for the infinite
number of times like while loop. But, code is executed at least once
whether condition is true or false. The syntax of do while loop is given
below.
<script>
do{ var i=21;
code to be executed do{
}while (condition); document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Output:

21
22
23
24
25
• JavaScript Functions
– JavaScript functions are used to perform operations. We
can call JavaScript function many times to reuse the code.

• Advantage of JavaScript function


– There are mainly two advantages of JavaScript functions.
• Code reusability: We can call a function several times so it save
coding.

• Less coding: It makes our program compact. We don’t need to


write many lines of code each time to perform a common task.
• JavaScript Function Syntax
– The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){

//code to be executed
}
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

JavaScript Function Arguments


•We can call function by passing arguments. Let’s see the example of function
that has one argument.

<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
• Function with Return Value
– We can call function that returns a value and use it in our program.
Let’s see the example of function that returns value.
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</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.
– JavaScript is an object-based language. Everything is
an object in JavaScript.

• Creating Objects in JavaScript


– There are 3 ways to create objects.
• By object literal
• By creating instance of Object directly (using new
keyword)
• By using an object constructor (using new keyword)
• 1) JavaScript Object by object literal
– The syntax of creating object using object literal is
given below:
object={property1:value1,property2:value2.....propertyN:valueN}

<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Output of the above example


102 Shyam Kumar 40000
• By creating instance of Object
– The syntax of creating object directly is given below:
var objectname=new Object();

<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Output of the above example


101 Ravi 50000
• By using an Object constructor
– Here, you need to create function with
arguments.
– Each argument value can be assigned in the
current
<script> object by using this keyword.
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>

Output of the above example


103 Vimal Jaiswal 30000
• JavaScript Array
– JavaScript array is an object that represents a
collection of similar type of elements.
• JavaScript Array directly (new keyword)
– The syntax of creating array directly is given
below: var arrayname=new Array();
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
Output of the above example
emp[1] = "Varun";
emp[2] = "John";
Arun
Varun
for (i=0;i<emp.length;i++){
John
document.write(emp[i] + "<br>");
}
</script>
• JavaScript Array Methods
Methods Description

concat() It returns a new array object that contains two or more merged arrays.

indexOf() It searches the specified element in the given array and returns the index
of the first match.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

unshift() It adds one or more elements in the beginning of the given array.
Concat()

<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];

var result=arr1.concat(arr2);
document.writeln(result);
</script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;

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


fruits.pop();
• JavaScript String
– The JavaScript string is an object that represents a
sequence of characters.
• There are 2 ways to create string in JavaScript
– By string literal
– By string object (using new keyword)
• By string literal
• The string literal is created using double
quotes. The syntax of creating string using
string literal is given below:
<script>
var stringname="string value"; var str="This is string literal";
document.write(str);
</script>
• By string object (using new keyword)
– The syntax of creating string object using new
keyword is given below:
var stringname=new String("string literal");

<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
• JavaScript String Methods
Methods Description
charAt() It provides the char value present at the specified index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.
search() It searches a specified regular expression in a given string and returns its
position if a match occurs.
replace() It replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of the specified
starting position and length.
slice() It is used to fetch the part of the given string. It allows us to assign
positive as well negative index.
toLowerCase() It converts the given string into lowercase letter.
toUpperCase() It converts the given string into uppercase letter.
split() It splits a string into substring array, then returns that newly created array.

trim() It trims the white space from the left and right side of the string.
• JavaScript String charAt(index) Method
– The JavaScript String charAt() method returns the
character at the given index.
<script>
var str="javascript";
document.write(str.charAt(2));
</script>

• JavaScript String indexOf(str) Method


– The JavaScript String indexOf(str) method returns
the index position of the given string.
<script>
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
• JavaScript Date Object
– The JavaScript date object can be used to get year, month and
day. We can display a timer on the webpage by the help of
JavaScript date object.

– Different Date constructors to create date object. It provides


methods to get and set day, month, year, hour, minute and
seconds.

• Constructor
– You can use 4 variant of Date constructor to create date object.
• Date()
• Date(milliseconds)
• Date(dateString)
• Date(year, month, day, hours, minutes, seconds, milliseconds)
• JavaScript Date Methods
Methods Description
getDate() It returns the integer value between 1 and 31
that represents the day for the specified date
on the basis of local time.
getHours() It returns the integer value between 0 and 23
that represents the hours on the basis of
local time.
getMilliseconds() It returns the integer value between 0 and
999 that represents the milliseconds on the
basis of local time.
getMinutes() It returns the integer value between 0 and 59
that represents the minutes on the basis of
local time.
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>

<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>
• JavaScript Math
– The JavaScript math object provides several
constants and methods to perform mathematical
operation.
• JavaScript Math Methods
Methods Description

abs() It returns the absolute value of the given number.


ceil() It returns a smallest integer value, greater than or equal to the
given number.
exp() It returns the exponential form of the given number.
floor() It returns largest integer value, lower than or equal to the given
number.
max() It returns maximum value of the given numbers.
min() It returns minimum value of the given numbers.
sqrt() It returns the square root of the given number
• JavaScript Regular Expressions
– A regular expression is a sequence of characters
that forms a search pattern.
– The search pattern can be used for text search and
text replace operations.

• Using String Methods


– In JavaScript, regular expressions are often used
with the two string methods: search() and replace().
• The search() method uses an expression to search for a
match, and returns the position of the match.
• The replace() method returns a modified string where the
pattern is replaced.
• Using String search() With a String
– The search() method searches a string for a specified
value and returns the position of the match:
let text = "Visit W3Schools!";
let n = text.search("W3Schools");

The result in n will be: 6

• Using String replace() With a String


– The replace() method replaces a specified value with
another value in a string:
let text = "Visit Microsoft!";
let result = text.replace("Microsoft", "W3Schools");
• Regular Expression Modifiers
– Modifiers can be used to perform case-insensitive more global
searches:

Modifier Description
i Perform case-insensitive matching

g Perform a global match (find all matches rather than stopping after the first
match)
m Perform multiline matching

• Regular Expression Patterns


– Brackets are used to find a range of characters:

Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
• Metacharacters are characters with a special meaning:

Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \
bWORD, or at the end of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal
number xxxx
• Using the RegExp Object
– In JavaScript, the RegExp object is a regular expression object with
predefined properties and methods.

– Using test()
• The test() method is a RegExp expression method.
• It searches a string for a pattern, and returns true or false, depending on the result.
• The following example searches a string for the character "e":

const pattern = /e/;


pattern.test("The best things in life are free!");

true

– Using exec()
• The exec() method is a RegExp expression method.
• It searches a string for a specified pattern, and returns the found text as an object.
• If no match is found, it returns an empty (null) object.
• The following example searches a string for the character "e":

/e/.exec("The best things in life are free!");


• Errors in JavaScript
– There are three types of errors in programming: (a)
Syntax Errors, (b) Runtime Errors, and (c) Logical Errors.
– Syntax Errors
• Syntax errors, also called parsing errors, occur at compile
time in traditional programming languages and at interpret
time in JavaScript.
– Runtime Errors
• Runtime errors, also called exceptions, occur during
execution (after compilation/interpretation).
– Logical Errors
• Logic errors can be the most difficult type of errors to track
down. they occur when you make a mistake in the logic.

You might also like