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

Client Side Scripting - 6thecture

The document provides an overview of JavaScript, explaining that it is a scripting language used widely in web pages to provide interactive and dynamic functionality, it describes JavaScript's syntax and basic features such as variables, data types, and functions, and covers why JavaScript is a useful skill for web development and some key advantages of using it.

Uploaded by

suyog lonsane
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
191 views

Client Side Scripting - 6thecture

The document provides an overview of JavaScript, explaining that it is a scripting language used widely in web pages to provide interactive and dynamic functionality, it describes JavaScript's syntax and basic features such as variables, data types, and functions, and covers why JavaScript is a useful skill for web development and some key advantages of using it.

Uploaded by

suyog lonsane
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 101

Client Side Scripting(CSS)

Client side Scripting


Chapter1
Basics of Javascript Programming
• What is JavaScript ?
• JavaScript is a dynamic computer programming language.
• It is lightweight and most commonly used as a part of
web pages,
• whose implementations allow client-side script to
interact with the user and make dynamic pages.
• It is an interpreted programming language with object-
oriented capabilities.
• JavaScript is very easy to implement because it is
integrated with HTML. It is open and cross-platform.
• JavaScript is a scripting or programming language that
allows you to implement complex features on web pages
• — every time a web page does more than just sit there and
display static information for you to look at
• — displaying timely content updates, interactive maps,
animated 2D/3D graphics, scrolling video jukeboxes, etc. —
• JavaScript is a scripting language that enables you to create
dynamically updating content, control multimedia, animate
images, and pretty much everything else.
What is JavaScript?

• JavaScript was initially created to “make web pages


alive”.
• The programs in this language are called scripts. They
can be written right in a web page’s HTML and run
automatically as the page loads.
• Scripts are provided and executed as plain text. They
don’t need special preparation or compilation to run.
• In this aspect, JavaScript is very different from
another language called Java.
Why is it called JavaScript?
• When JavaScript was created, it initially had
another name: “LiveScript”. But Java was very
popular at that time, so it was decided that
positioning a new language as a “younger
brother” of Java would help.
• But as it evolved, JavaScript became a fully
independent language with its own
specification called ECMAScript, and now it has
no relation to Java at all.
• Today, JavaScript can execute not only in the
browser, but also on the server, or actually on
any device that has a special program called 
the JavaScript engine.
• https://www.youtube.com/watch?v=nItSSTwBvSU
Why to Learn Javascript

• Javascript is a MUST for students and working professionals to become a great Software Engineer
specially when they are working in Web Development Domain. I will list down some of the key
advantages of learning Javascript
• Javascript is the most popular programming language in the world and that makes it a programmer’s
great choice. Once you learnt Javascript, it helps you developing great front-end as well as back-end
softwares using different Javascript based frameworks like jQuery, Node.JS etc.
• Javascript is everywhere, it comes installed on every modern web browser and so to learn Javascript
you really do not need any special environment setup. For example Chrome, Mozilla Firefox , Safari and
every browser you know as of today, supports Javascript.
• Javascript helps you create really beautiful and crazy fast websites. You can develop your website with a
console like look and feel and give your users the best Graphical User Experience.
• JavaScript usage has now extended to mobile app development, desktop app development, and game
development. This opens many opportunities for you as Javascript Programmer.
• Due to high demand, there is tons of job growth and high pay for those who know JavaScript. You can
navigate over to different job sites to see what having JavaScript skills looks like in the job market.
• Great thing about Javascript is that you will find tons of frameworks and Libraries already developed
which can be used directly in your software development to reduce your time to market.
Features of Javascript
JavaScript is divided into two main features, they are as follows –
General JavaScript Features
•JavaScript language consists of several different features. Some of the general
JavaScript features are as follows –
1. Validating User’s Input
•JavaScript is very useful while using forms. It has the capability to validate user
input for errors and also saves time. If the user leaves a required field empty or the
information is incorrect, JavaScript checks for them before sending the data over
to the server.
2. Simple Client-side Calculations
•Since JavaScript is a client-side technology, it can perform basic calculations on
the browser. The browser does not need to ask server time for every task. This is
especially helpful when a user needs to perform these calculations repeatedly. In
these cases, connecting to the server would take a lot more time than performing
the actual calculations.
3. Greater Control
• JavaScript provides greater control to the browser rather than being completely dependent
on the web servers. JavaScript provides various browsers with additional functionalities
that help reduce server load and network traffic.
4. Platform Independent
• Since browsers interpret JavaScript, it solves the problem of compilation and
compatibility. Thus it can run on Windows, Macintosh, and other Netscape-supported
systems. Also, it is possible to embed them in any other script like HTML that keeps
JavaScript into use.
5. Handling Dates and Time
Unlike other programming languages, JavaScript has built-in functions to determine the date
and time. Thus it is very easy to code only by using methods like .getDate().
6. Generating HTML Content
JavaScript has very handy features to dynamically generate HTML content for the web. It
allows us to add text, links, images, tables, etc after an event occurrence (eg – mouse
click).
7. Detecting the User’s Browser and OS
• JavaScript is very capable in the detection of the user’s browser and OS information.
Though JavaScript runs on every platform, there may occur a situation where we need the
user’s browser before processing. This can be helpful for writing code that results in
different outputs in different browsers.
• Client-Side JavaScript
• Client-side JavaScript is the most common form of the language. The script
should be included in or referenced by an HTML document for the code to be
interpreted by the browser.
• It means that a web page need not be a static HTML, but can include
programs that interact with the user, control the browser, and dynamically
create HTML content.
• The JavaScript client-side mechanism provides many advantages over
traditional CGI server-side scripts. For example, you might use JavaScript to
check if the user has entered a valid e-mail address in a form field.
• The JavaScript code is executed when the user submits the form, and only if
all the entries are valid, they would be submitted to the Web Server.
• JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
Javascript syntax
• JavaScript can be implemented using JavaScript
statements that are placed within the <script>...
</script> HTML tags in a web page.
• You can place the <script> tags, containing your
JavaScript, anywhere within your web page, but it is
normally recommended that you should keep it within
the <head> tags.
• 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.
• <script>
• Javascript code
• </script>
• 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".
First Javascript code
• <html>
• <body>
• <script language=“javascript”
type=“text/javascript”>
• Document.write(“hello”)
• </script>
• </body>
• </html>
Simple Hello program
<html>
<body>
<script language = "javascript" type ="text/javascript">
<!-- document.write("Hello World!") //-->
</script>
</body>
</html>
• Javascript look like
• <script language =“javascript”
type=“text/javascript”>
• Java code
• </script>
• https://www.youtube.com/watch?v=_GxpmQ
54aqg
Semicolons are Optional

• <script>
• Var a=10
• Var b=20
• </script>
• Simple statements in JavaScript are generally followed
by a semicolon character, just as they are in C, C++, and
Java. JavaScript, however, allows you to omit this
semicolon if each of your statements are placed on a
separate line. For example, the following code could be
written without semicolons.
Use semicolon
• <script>
• Var1=10;var2=20;
• </script>
• Case Sensitivity
• JavaScript is a case-sensitive language. This means that
the language keywords, variables, function names, and
any other identifiers must always be typed with a
consistent capitalization of letters.
• So the identifiers Time and TIME will convey different
meanings in JavaScript.
• JavaScript Variables
• Like many other programming languages,
JavaScript has variables. Variables can be
thought of as named containers. You can place
data into these containers and then refer to
the data simply by naming the container.
• Before you use a variable in a JavaScript
program, you must declare it. Variables are
declared with the var keyword as follows
• <script type=“text/javascript”>
• Var money;
• var name;
• </script>
• Variable initialization
• Storing a value in a variable is called variable
initialization. You can do variable initialization
at the time of variable creation or at a later
point in time when you need that variable.
• <script type=“text/javascript”>
• Var money=200.50;
• var name=“ali”;
• </script>
Document Object Model
• Every web page resides inside a browser window which
can be considered as an object.
• A Document object represents the HTML document that
is displayed in that window. The Document object has
various properties that refer to other objects which allow
access to and modification of document content.
• The way a document content is accessed and modified is
called the Document Object Model, or DOM. The Objects
are organized in a hierarchy. This hierarchical structure
applies to the organization of objects in a Web document.
• Window object − Top of the hierarchy. It is the
outmost element of the object hierarchy.
• Document object − Each HTML document that gets
loaded into a window becomes a document object.
The document contains the contents of the page.
• Form object − Everything enclosed in the
<form>...</form> tags sets the form object.
• Form control elements − The form object contains all
the elements defined for that object such as text fields,
buttons, radio buttons, and checkboxes.
Here is a simple hierarchy of a few important objects −
Methods of Document Object
• Methods of Document Object:
• write(“string”): writes the given string on the document.
• getElementById(): returns the element having the given
id value.
• getElementsByName(): returns all the elements having
the given name value.
• getElementsByTagName(): returns all the elements
having the given tag name.
• getElementsByClassName(): returns all the elements
having the given class name.
Dom in javascript
• What is DOM in JavaScript?
• JavaScript can access all the elements in a
webpage making use of Document Object
Model (DOM). In fact, the web browser
creates a DOM of the webpage when the page
is loaded. The DOM model is created as a tree
of objects like this:
getElementById, innerHTML Example
 getElementById:  To access elements and attributes whose id is
set.
 innerHTML: To access the content of an element.
• <html>
• <head>
• <title>DOM!!!</title>
• </head>
• <body>
• <h1 id="one">Welcome</h1>
• <p id=“two”>This is the welcome message.</p>
• <h2>Technology</h2>
• <p>This is the technology section.</p>
• <script type="text/javascript">
• var text = document.getElementById("one").innerHTML;
• document.write(text+”into Aissms poly”);
• Var text1=document.getElementById(“two”).innerHTML;
• document.write(text1+”given by syif”);
</script>
• </body>
• </html>
Example
• <html>
• <body>

• <h1 id="myH"></h1>
• <p id="myP"></p>

• <script>
• // Change heading:
• document.getElementById("myH").innerHTML = "JavaScript Comments";
• Document.write(“hello”);
• // Change paragraph:
• document.getElementById("myP").innerHTML = "My first paragraph.";
• </script>

• </body>
• </html>
Variable intialization
<html>
<body>
•<h2 id=“hello</h2>
•<p>In this example, x, y, and z are variables.</p>
•<p id="demo"></p>
•<script>
•var x = 5;
•var y = 6;
•var z = x + y;
•document.getElementById(“hello").innerHTML =
•"The value of z is: " + z;
•</script>
•</body>
•</html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
</body>
</html>
More Examples
<!DOCTYPE html>
•<html>
•<body>
<h2>JavaScript Variables</h2>
<p>Strings are written with quotes.</p>
•<p>Numbers are written without quotes.</p>

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

•<script>
•var pi = 3.14;
•var person = "John Doe";
•var answer = 'Yes I am!';
•document.getElementById("demo").innerHTML =
•pi + "<br>" + person + "<br>" + answer;
•</script>
</body>
•</html>
• https://www.youtube.com/watch?v=_GxpmQ
54aqg
If else statement

Syntax
The syntax for a basic if statement is as
follows −

If(expression)
{
Statement
}
Example
• <html>
• <body>
• <script type=“text/javascript”>
• Var age=20
• If(age>18)
• {
• document.write(“qualifying for drive”);
• }</script>
• </body>
• </html>
If else statement
• If(expression)
• {
• Statement
• }
• else
• {
• Statement
• }
• <html>
• <body>
• <script type=“text/javascript”>
• Var age=20
• If(age>18)
• {
• document.write(“qualifying for drive”);
• }
• else
• {
• document.write(“qualifying for drive”);
• }
• </script>
• </body>
• </html>
If else ladder
• If(expression1)
• {
• Statement1
• }else if(expression2)
• {
• Statement2
• }
• Else
• {
• }
<html>
<body>
<p id=“hello1”>
<script type=“text/javascript”>
Var books=“maths”
If(book==“history”)
{
document.write(“history book”);
}
Else if(book==“maths”)
{
document.write(“maths book”);
}
Else if(book==“English”)
{
Document.write(“English”);
}
Else
{
Document.write(“other book”);
}

</script>
</body>
</html>
While loop
• While writing a program, you may encounter a
situation where you need to perform an action over
and over again. In such situations, you would need to
write loop statements to reduce the number of lines.
• Syntax:
• While(expression)
• {
• Statement
• }
Example
• <html>
• <body>
• <script language = "javascript" type = "text/javascript">
• var i=1
• while(i<10)
• {
• document.write(i+"<br>");

• i++
• }
• </script>
• </body>
• </html>
• Syntax
• The syntax of for loop is JavaScript is as
follows −
• for(initialization,test condition;iteration
statement)
• {
• Statement
• }
Example
• <html>
• <body>
• <script language = "javascript" type = "text/javascript">
• for(var i=1;i<10;i++)
• {
• document.write(i+"<br>");
• }
• </script>
• </body>
• </html>
Switch Example
• Syntax
• The objective of a switch statement is to give
an expression to evaluate and several different
statements to execute based on the value of
the expression. The interpreter checks
each case against the value of the expression
until a match is found. If nothing matches,
a default condition will be used.
Switch syntax
• Swich (expression)
• {
• case condition1:statement(s)
• break;
• case condition2:statement(s)
• break;
• .
• .
• case condition n:statement(s)
• break;
• default:statement(s)
• }
• The break statements indicate the end of a particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.
If else statement

Syntax
The syntax for a basic if statement is as
follows −

If(expression)
{
Statement
}
Continue statement
• The continue statement breaks one iteration (in the loop) if a specified condition
occurs, and continues with the next iteration in the loop.
• The difference between continue and the break statement, is instead of "jumping out"
of a loop, the continue statement "jumps over" one iteration in the loop.
• Syntax
continue;
• Using the optional label reference:
• continue labelname;
• For(var i=1;i<=10;i++)
• {
• If(i==4)
• Continue;
• Document.write(i);
• }
• <html>
• <body>
• <p id="demo"></p>
• <script>
• var text = "";
• var i = 0;
• while (i < 5)
• {
• i++;
• if (i == 3)
• {
• continue;
• } output
• text += "<br>The number is " + i;
• }
• document.getElementById("demo").innerHTML = text;
• </script>
• </body>
• </html>
Do while Loop
• The do/while statement creates a loop that executes a block of
code once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
• The do/while statement is used when you want to run a loop at
least one time, no matter what.
• Syntax
• do {
  code block to be executed
}
while (condition);
Example
• <html>
• <body>
• <p id="demo"></p>
• <script>
• var text = "";
• var i = 0;
• do {
• text += "<br>The number is " + i;
• i++;
• }
• while (i < 5);
output
• document.getElementById("demo").innerHTML = text;
• </script>
• </body>
• </html>
Operators in javascript

• JavaScript operators are used to assign values, compare


values, perform arithmetic operations, and more.
• take a simple expression 4 + 5 is equal to 9. Here 4 and 5
are called operands and ‘+’ is called the operator.
JavaScript supports the following types of operators.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Arithmetic Operator
• (+)Addition
• (-)Subtraction
• (*)Multiplication
• (/)Division
• (%)Modulus
• (++)Increment
• (--)Decrement
Example
result = a - b;
• <html> document.write("a - b = “+result);
• <body> document.write(linebreak);

• <script type = document.write("a / b = ");


result = a / b;
"text/javascript"> document.write(result);
• var a = 33; document.write(linebreak);

• var b = 10; document.write("a * b = ");


• var result = a + b; result = a - b;
document.write(result);
• var linebreak = "<br />"; document.write(linebreak);
</script>
• document.write("a + b = </body> output
“+result); </html>
a + b = 43
• document.write(linebreak);
a - b = 23
a / b = 3.3
a * b = 330
Comparison operator Example
• ==(Equal
• != Not Equal
• >Greater than
• <Less Than
• >=greater than or equal to
• <=Less than equal to
Example
• <html> •
• <body> • document.write("(a != b) => ");
• <script type = "text/javascript"> • result = (a != b);
• • document.write(result);
• var a = 10; • document.write(linebreak);
• var b = 20; •
• var linebreak = "<br />"; • document.write("(a >= b) => ");
• • result = (a >= b);
• document.write("(a == b) => "); • document.write(result);
• result = (a == b); • document.write(linebreak);
• document.write(result); •
• document.write(linebreak); • document.write("(a <= b) => ");
• • result = (a <= b);
• document.write("(a < b) => "); • document.write(result);
• result = (a < b); • document.write(linebreak);
• document.write(result); • //-->
• document.write(linebreak); • </script>
• Set the variables to different values and
different operators and then try...
• document.write("(a > b) => ");
• </body>
• result = (a > b);
• </html>
• document.write(result);
• document.write(linebreak);
• Output:
Logical Operators
• &&Logical And
• ||Logical OR
• !Logical Not
• Bitwise Operator.
• https://www.tutorialspoint.com/javascript/jav
ascript_operators.htm
Logical Operator Example

• document.write("(a || b) => ");


• <html> • result = (a || b);
• <body> • document.write(result);
• document.write(linebreak);
• <script type = "text/javascript"> •
• document.write("!(a && b) => ");
• <!-- • result = (!(a && b));
• var a = true; • document.write(result);
• document.write(linebreak);
• var b = false; • //-->
• </script>
• var linebreak = "<br />"; • <p>Set the variables to different values and different
• operators and then try...</p>
• </body>
• document.write("(a && b) • </html>

=> "); • Output



• result = (a && b); •
(a && b) => false
(a || b) => true
• document.write(result); • !(a && b) => true
• Set the variables to different values and different operators
• document.write(linebreak); and then try...
Assignment Operator

• =Simple Assignment
• +=and and assignment
• -=subtract and assignement
• *=multiply and assignment
• /=divide and assignment
• %=Modulus and assignment
Example
• <html> • document.write("Value of a => (a *= b) => ");
• <body> • result = (a *= b); a=a*b
• <script type = "text/javascript"> • document.write(result);
• <!--
• document.write(linebreak);
• var a = 33;

• var b = 10;
• var linebreak = "<br />"; • document.write("Value of a => (a /= b) => ");
• • result = (a /= b);a=a/b
• document.write("Value of a => (a = b) => "); • document.write(result);
• result = (a = b); • document.write(linebreak);
• document.write(result); •
• document.write(linebreak); • document.write("Value of a => (a %= b) => ");

• result = (a %= b);a=a%b
• document.write("Value of a => (a += b) => ");
• document.write(result);
• result = (a += b);
• document.write(result); • document.write(linebreak);
• document.write(linebreak); • //-->
• • </script>
• document.write("Value of a => (a -= b) => "); • <p>Set the variables to different values and different
• result = (a -= b); operators and then try...</p>
• document.write(result); • </body>
• document.write(linebreak); • </html>
Javascript object
• objects in JavaScript • var person = {
may be defined as an • firstName: "John",
unordered collection of • lastName: "Doe",
related data, of • age: 50,
primitive or reference • eyeColor: "blue"
types, in the form of • };
“key: value” pairs. • In the above Example
• Firstname,lastname,age,eyec
olor are all keys
• John,doe,50,blue are its
values.
Real life
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:

object Properties Methods

car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = 850kg car.brake()

car.color = white car.stop()

Var car
{ name:”Fiat”,
Model:500,
Weight:850,
Color:”white”
JavaScript Objects

• JavaScript variables are


containers for data values. • <html>
• <body>
• This code assigns a simple
<h2>JavaScript Variables</h2>
value (Fiat) to
<p id="demo"></p>
a variable named car:
<script>
• // Create and display a variable:
• var car = "Fiat";
• document.getElementById("demo"
).innerHTML = car;
• Output:
• </script>
• JavaScript Variables </body>
• Fiat • </html>
• Objects are variables too. But • <html>
• <body>
objects can contain many values. • <h2>JavaScript Objects</h2>
• This code assigns many • <p id="demo"></p>
values (Fiat, 500, white) to • <script>
• // Create an object:
a variable named car:
• var car = {type:"Fiat", model:"500",
color:"white"};

• // Display some data from the object:


• document.getElementById("demo").innerHTML
= "The car type is " + car.type;
• Output: • </script>
• JavaScript Objects
• </body>
• The car type is Fiat • </html>
Object Definition
•<!DOCTYPE html>
•<html>
•<body>

•You define (and create) a <h2>JavaScript Objects</h2>


<p id="demo"></p>
JavaScript object with an <script>
•// Create an object:
object literal: •var person = {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};
// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years
old.";
</script>
</body>
</html>

•Output:JavaScript Objects
•John is 50 years old.
Example
•<!DOCTYPE html>
•<html> // Display some data from the object:
•<body> •document.getElementById("demo").i
<h2>JavaScript Objects</h2> nnerHTML =
<p id="demo"></p> •person.firstName + " is " + person.age
<script> + " years old.";
•// Create an object: •</script>
•var person = { </body>
• firstName: "John", •</html>
• lastName: "Doe",
• age: 50, •Output:JavaScript Objects
• eyeColor: "blue" •John is 50 years old.
•};
Accessing Object Properties
• <!DOCTYPE html>
• <html>
• You can access object properties in • <body>
<h2>JavaScript Objects</h2>
tw <p>There are two different ways to access an object
• o ways: property.</p>
<p>You can use person.property or
• objectName.propertyName person["property"].</p>
<p id="demo"></p>
• or <script>
• objectName["propertyName"] • // Create an object:
• var person = {
• Output: • firstName: "John",
• lastName : "Doe",
• JavaScript Objects • id : 5566
• There are two different ways to • };
• // Display some data from the object:
access an object property. • document.getElementById("demo").innerHTML
• You can use person.property or •
=person.firstName + " " + person.lastName;
</script>
person["property"]. </body>
• </html>
• John Doe • Output:
• Example • The this Keyword
• var person = { • In a function definition, this
  firstName: "John", refers to the "owner" of the
  lastName : "Doe", function.
  id       : 5566,
  fullName : function() { • In the example above, this is
    return this.firstName + " the person object that "owns"
" + this.lastName; the fullName function.
  }
}; • In other words, this.firstName
means the firstName property
of this object.
• fullName : function() {
• <!DOCTYPE html> • return this.firstName + " " + this.lastName;
• <html> • }
• };
• <body> • // Display data from the object:
• document.getElementById("demo").innerHTML =
<h2>JavaScript Objects</h2> person.fullName();
<p>An object method is a function • </script>

definition, stored as a property • </body>


value.</p> • </html>

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


• An object method is a function definition, stored as a
<script> property value.
• // Create an object: • John Doe

• var person = {
• Accessing Object Methods
• firstName: "John", • You access an object method with the following syntax:
• lastName : "Doe", • objectName.methodName()

• id : 5566,
Array in javascript
• What is an Array? • var car1 = "Saab";
• An array is a special var car2 = "Volvo";
variable, which can hold var car3 = "BMW";
more than one value at
a time.
• If you have a list of items
(a list of car names, for
example), storing the
cars in single variables
could look like this:
Creating array
• <!DOCTYPE html>
• Creating an Array • <html>
• Using an array literal is • <body>

the easiest way to • <h2>JavaScript Arrays</h2>


create a JavaScript
var array_name =
[item1, item2, ...];     • <p id="demo"></p>
Array.
• Syntax: • <script>
• var cars = ["Saab", "Volvo", "BMW"];
Output:
• document.getElementById("demo").inner
JavaScript Arrays
HTML = cars;
Saab,Volvo,BMW
• </script>
</body>
• </html>
• <!DOCTYPE html>
• <html>
• JavaScript Arrays
• <body> • Saab,Volvo,BMW
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
• var cars = [
• "Saab",
• "Volvo",
• "BMW"
• ];
• document.getElementById("demo").inner
HTML = cars;
• </script>

• </body>
• </html>
Using the JavaScript Keyword new

• The following example also creates an Array, and


assigns values to it: • JavaScript Arrays
• <!DOCTYPE html>
• <html> • Saab,Volvo,BMW
• <body>

• <h2>JavaScript Arrays</h2>

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

• <script>
• var cars = new Array("Saab", "Volvo", "BMW");
• document.getElementById("demo").innerHTML =
cars;
• </script>

• </body>
• </html>
Access the Elements of an Array

• <!DOCTYPE html>
• You access an array element by • <html>
referring to the index number. • <body>

• var name = cars[0]; • <h2>JavaScript Arrays</h2>

• <p>JavaScript array elements are accessed using


numeric indexes (starting from 0).</p>

• Output: • <p id="demo"></p>


• JavaScript Arrays
• <script>
• JavaScript array elements are • var cars = ["Saab", "Volvo", "BMW"];
accessed using numeric • document.getElementById("demo").innerHTML =
cars[0];
indexes (starting from 0). • </script>

• Saab • </body>
• </html>
Changing an Array Element

• <!DOCTYPE html>
• cars[0] = "Opel"; • <html>
• <body>
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accessed
• Output: using numeric indexes (starting from 0).</p>
<p id="demo"></p>
• JavaScript Arrays <script>
• var cars = ["Saab", "Volvo", "BMW"];
• JavaScript array elements • cars[0] = "Opel";
are accessed using • document.getElementById("demo").inner
HTML = cars;
numeric indexes (starting • </script>
from 0).
• </body>
• Opel,Volvo,BMW • </html>
Access the full array
• <!DOCTYPE html>
• With JavaScript, the full • <html>
array can be accessed • <body>

by referring to the array • <h2>JavaScript Arrays</h2>


name:
• <p id="demo"></p>

• <script>
• var cars = ["Saab", "Volvo", "BMW"];

• Output: • document.getElementById("demo").innerHT
ML = cars;
• JavaScript Arrays • </script>

• Saab,Volvo,BMW • </body>
• </html>
Arrays are Objects

• <!DOCTYPE html>
• <html>
• <body>
• Output:
• <h2>JavaScript Arrays</h2>

• <p>Arrays use numbers to access its elements.</p>


• JavaScript Arrays
• <p id="demo"></p>
• Arrays use numbers to
• <script>
• var person = ["John", "Doe", 46]; access its elements.
• document.getElementById("demo").innerHTML =
person[0]; • John
• </script>

• </body>
• </html>
• <!DOCTYPE html>
• <html> • JavaScript Objects
• <body>
• JavaScript uses names
• <h2>JavaScript Objects</h2>
• <p>JavaScript uses names to access object
to access object
properties.</p> properties.
• <p id="demo"></p>
• John
• <script>
• var person = {firstName:"John", lastName:"Doe",
age:46};
• document.getElementById("demo").innerHTML =
person["firstName"];
• </script>

• </body>
• </html>
Accessing the First Array Element

• <!DOCTYPE html>
• <html> • JavaScript Arrays
• <body>
• JavaScript array
• <h2>JavaScript Arrays</h2>
elements are accesses
• <p>JavaScript array elements are accesses using
numeric indexes (starting from 0).</p> using numeric indexes
• <p id="demo"></p> (starting from 0).
• <script> • Banana
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
• var first = fruits[0];
• document.getElementById("demo").innerHTML = first;
• </script>

• </body>
• </html>
Accessing the Last Array Element

• <!DOCTYPE html>
• <html> • JavaScript Arrays
• <body>
• JavaScript array
• <h2>JavaScript Arrays</h2>
elements are accesses
• <p>JavaScript array elements are accesses using
numeric indexes (starting from 0).</p> using numeric indexes
• <p id="demo"></p> (starting from 0).
• <script> • Mango
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
• var last = fruits[fruits.length-1];
• document.getElementById("demo").innerHTML = last;
• </script>

• </body>
• </html>
Array properties and methods
• <!DOCTYPE html>
• The length Property • <html>
• The length property of an array • <body>

returns the length of an array • <h2>JavaScript Arrays</h2>


(the number of array • <p>The length property returns the length of an
array.</p>
elements).
• <p id="demo"></p>

• <script>
• Output: • var fruits = ["Banana", "Orange", "Apple", "Mango"];
• document.getElementById("demo").innerHTML =
• JavaScript Arrays fruits.length;
• </script>
• The length property returns
the length of an array. • </body>
• </html>
• 4
Push()
• The easiest way to add a • <!DOCTYPE html>
• <html>
new element to an array is • <body>
<h2>JavaScript Arrays</h2>
using the push() method
• <p>The push method appends a new element to an
array.</p>
<p id="demo"></p>
<script>
• Output: • var fruits = ["Banana", "Orange", "Apple", "Mango"];
• document.getElementById("demo").innerHTML = fruits;
• JavaScript Arrays fruits.push("Lemon");
• document.getElementById("demo").innerHTML =
• The push method appends a fruits;

new element to an array.


• </script>
• Banana,Orange,Apple,Mang
• </body>
o,Lemon • </html>
toString()
• The JavaScript method • <!DOCTYPE html>
• <html>
toString() converts an array to • <body>
a string of (comma separated) <h2>JavaScript Array Methods</h2>
array values. <h2>toString()</h2>
• Output <p>The toString() method returns an array as
a comma separated string:</p>
• JavaScript Array Methods <p id="demo"></p>
<script>
• toString()
• var fruits = ["Banana", "Orange", "Apple",
• The toString() method returns "Mango"];
an array as a comma • document.getElementById("demo").innerH
TML = fruits.toString();
separated string: • </script>
• Banana,Orange,Apple,Mango </body>
• </html>
Join()
• The join() method joins array elements • <!DOCTYPE html>
• <html>
into a string.
• <body>
• It this example we have used " * " as a • <h2>JavaScript Array Methods</h2>
separator between the elements: <h2>join()</h2>
• Banana * Orange * Apple * Mango <p>The join() method joins array elements into a
string.</p>
• 
<p>It this example we have used " * " as a separator
• Output: between the elements:</p>
• JavaScript Array Methods <p id="demo"></p>
<script>
• join() • var fruits = ["Banana", "Orange", "Apple",
• The join() method joins array elements "Mango"];
into a string. • document.getElementById("demo").innerHTML =
fruits.join(" * ");
• It this example we have used " * " as a • </script>
separator between the elements: </body>
• Banana * Orange * Apple * Mango </html>
Popping and Pushing
• <!DOCTYPE html>
• When you work with arrays, it is easy • <html>
to remove elements and add new • <body>
elements. <h2>JavaScript Array Methods</h2>
<h2>pop()</h2>
• This is what popping and pushing is: <p>The pop() method removes the last
• Popping items out of an array, or element from an array.</p>
pushing items into an array. <p id="demo1"></p>
<p id="demo2"></p>
• Popping <script>
• The pop() method removes the last • var fruits = ["Banana", "Orange", "Apple",
element from an array "Mango"];
• Output: • document.getElementById("demo1").inne
• JavaScript Array Methods
rHTML = fruits;
• pop()
• fruits.pop();
• The pop() method removes the last element from an • document.getElementById("demo2").inne
array. rHTML = fruits;
• Banana,Orange,Apple,Mango • </script>
• Banana,Orange,Apple </body>
• </html>
• <!DOCTYPE html>
• The pop() method returns the • <html>
value that was "popped out": • <body>
<h2>JavaScript Array Methods</h2>
• Output: <h2>pop()</h2>
• JavaScript Array Methods <p>The pop() method removes the last element from
an array.</p>
• pop() <p>The return value of the pop() method is the
• The pop() method removes the removed item.</p>
<p id="demo1"></p>
last element from an array. <p id="demo2"></p>
• The return value of the pop() <p id="demo3"></p>
<script>
method is the removed item. • var fruits = ["Banana", "Orange", "Apple",
• Banana,Orange,Apple,Mango "Mango"];
• document.getElementById("demo1").innerHTML =
• Mango fruits;
• document.getElementById("demo2").innerHTML =
• Banana,Orange,Apple fruits.pop();
• document.getElementById("demo3").innerHTML =
fruits;
• </script>
</body>
• </html>
Splicing an Array
The splice() method can be used to add new items to an array:

• <!DOCTYPE html>
• <html> • Output:
• <body>
• JavaScript Array Methods
<h2>JavaScript Array Methods</h2>
<h2>splice()</h2> • splice()
<p>The splice() method adds new elements to
an array.</p>
• The splice() method adds
<p id="demo1"></p> new elements to an array.
<p id="demo2"></p>
<script>
• Original Array:
var fruits = ["Banana", "Orange", "Apple", Banana,Orange,Apple,Mang
"Mango"]; o
document.getElementById("demo1").innerHT
ML = "Original Array:<br>" + fruits; • New Array:
fruits.splice(2, 0, "Lemon", "Kiwi"); Banana,Orange,Lemon,Kiwi,
• document.getElementById("demo2").inne
rHTML = "New Array:<br>" + fruits; Apple,Mango
</script>
</body>
• Using splice() to Remove Elements • <!DOCTYPE html>
• With clever parameter setting, you can use • <html>
splice() to remove elements without leaving • <body>
"holes" in the array: <h2>JavaScript Array Methods</h2>
Output: <h2>splice()</h2>
• JavaScript Array Methods <p>The splice() methods can be used to remove array
elements.</p>
• splice()
<p id="demo"></p>
• The splice() methods can be used to remove array
<script>
elements.
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
• Orange,Apple,Mango
• document.getElementById("demo").innerHTML =
fruits;
• Description: fruits.splice(0, 1);
• The first parameter (0) defines the position where • document.getElementById("demo").innerHTML =
new elements should be added (spliced in). fruits;
• The second parameter (1) defines how </script>
many elements should be removed. </body>
• The rest of the parameters are omitted. No new </html>
elements will be added.
Merging (Concatenating) Arrays
• <!DOCTYPE html>
• <html>
• <body>
• The concat() method creates <h2>JavaScript Array Methods</h2>
a new array by merging <h2>concat()</h2>
<p>The concat() method is used to merge
(concatenating) existing (concatenate) arrays:</p>
arrays: <p id="demo"></p>
• Output: <script>
• var myGirls = ["Cecilie", "Lone"];
• JavaScript Array Methods • var myBoys = ["Emil", "Tobias", "Linus"];
• var myChildren = myGirls.concat(myBoys);
• concat()
document.getElementById("demo").innerHTM
• The concat() method is used L = myChildren;
• </script>
to merge (concatenate)
</body>
arrays: </html>
• Cecilie,Lone,Emil,Tobias,Linus
JavaScript Sorting Arrays
• <!DOCTYPE html>
• <html>
• <body>
• The sort() method sorts • <h2>JavaScript Array Sort</h2>
an array alphabetically: <p>The sort() method sorts an array
alphabetically.</p>
• Output: <button onclick="myFunction()">Try
it</button>
<p id="demo"></p>
<script>
• var fruits = ["Banana", "Orange", "Apple",
"Mango"];
• document.getElementById("demo").inner
HTML = fruits;
function myFunction() {
• fruits.sort();
• document.getElementById("demo").inner
HTML = fruits;
• }
• </script>
</body>
• <!DOCTYPE html>
Reversing an Array • <html>
• <body>
The reverse() method reverses the elements in
• <p>Click the button to reverse the order of the elements in the array.</p>
an array.
• <button onclick="myFunction()">Try it</button>

You can use it to sort an array in descending• <p id="demo"></p>


order:
• <script>
Output: • var fruits = ["Banana", "Orange", "Apple", "Mango"];
• document.getElementById("demo").innerHTML = fruits;

• function myFunction() {
• fruits.reverse();
• document.getElementById("demo").innerHTML = fruits;
• }
• </script>

• </body>
• </html>

• </body>
• </html>
Function
• JavaScript Function Syntax
•  JavaScript function is a • A JavaScript function is defined with the
block of code designed function keyword, followed by a name,
followed by parentheses ().
to perform a particular
task. • Function names can contain letters, digits,
underscores, and dollar signs (same rules
• A JavaScript function is as variables).

executed when • The parentheses may include parameter


"something" invokes it names separated by commas:
• (parameter1, parameter2, ...)
(calls it).
• The code to be executed, by the function,
is placed inside curly brackets: {}
• <!DOCTYPE html>
• <html> • Output:
• <body>
<h2>JavaScript Functions</h2> • JavaScript Functions
<p>This example calls a function which
performs a calculation, and returns the • This example calls a
result:</p>
<p id="demo"></p>
function which
<script> performs a calculation,
• function myFunction(p1, p2) {
• return p1 * p2; and returns the result:
• }
• document.getElementById("demo").inner • 12
HTML = myFunction(4, 3);
• </script>
</body>
• </html>
Property Access operation
• A property access expression evaluates to
the value of an object property or an array
element.
• JavaScript defines two syntaxes for
property access:
• expression . identifier expression
[ expression ]
• The first style of property access is an
expression followed by a period and an
identifier. The expression specifies the
object, and the identifier specifies the
name of the desired property
• The second style of property access
follows the first expression (the object or
array) with another expression in square
brackets. This second expression specifies
the name of the desired property or the
index of the desired array element.
• Example
• var o = {x:1,y:{z:3}}; // An example object
• var a = [o,4,[5,6]]; // An example array that contains the object
• o.x // => 1: property x of expression o
• o.y.z // => 3: property z of expression o.y
• o["x"] // => 1: property x of object o
• a[1] // => 4: element at index 1 of expression a
• a[2]["1"] // => 6: element at index 1 of expression a[2]
• a[0].x // => 1: property x of expression a[0]
JavaScript Accessors (Getters and Setters)
• ECMAScript 5 (2009) introduced Getter and Setters.
• Getters and setters allow you to define Object Accessors (Computed
Properties).

• JavaScript Getter (The get Keyword)


• This example uses a lang property to get the value of
the language property.
Example
• <html>
• <body>
• <h2>JavaScript Getters and Setters</h2> • // Display data from the object using a getter:
• <p>Getters and setters allow you to get • document.getElementById("demo").innerHT
and set properties via methods.</p> ML = person.lang;
• <p>This example uses a lang property to • </script>
get the value of the language • </body>
property.</p> • </html>
• <p id="demo"></p>
• <script>
• // Create an object:
• var person = {
• firstName: "John", • Output:
• lastName : "Doe", • JavaScript Getters and Setters
• language : "en", • Getters and setters allow you to get and set
• get lang() { properties via methods.
• return this.language; • This example uses a lang property to get the
• } value of the language property.
• };
• En
JavaScript Setter (The set Keyword)

• This example uses a lang property • var person = {


to set the value of • firstName: "John",
the language property • lastName : "Doe",
• <!DOCTYPE html> • language : "NO",
• <html> • set lang(value) {
• <body> • this.language = value;
• }
• <h2>JavaScript Getters and Setters</h2>
• };
• <p>Getters and setters allow you to get
• // Set a property using set:
and set properties via methods.</p>
• person.lang = "en";
• <p>This example uses a lang property to
• // Display data from the object:
set the value of the language
• document.getElementById("demo").innerHT
property.</p> ML = person.language;
• <p id="demo"></p> • </script>
• <script> • </body>
• // Create an object: • </html>
• Output
• Output:
• JavaScript Getters and
Setters
• Getters and setters allow
you to get and set
properties via methods.
• This example uses a lang
property to set the value of
the language property.
• en
Example
• var person = {
• firstName: "John",
• Using the lang property, in this example, • lastName : "Doe",
stores an upper case value in • language : "",
the language property • set lang(lang) {
• this.language = lang.toUpperCase();
• <!DOCTYPE html> • }
• <html> • };
• <body> • // Set a property using set:
• <h2>JavaScript Getters and Setters</h2> • person.lang = "en";
• <p>Getters and setters allow you to get • // Display data from the object:
and set properties via methods.</p> • document.getElementById("demo").inner
• <p id="demo"></p> HTML = person.language;
• <script> • </script>
• // Create an object: • </body>
• </html>

• Output:
• JavaScript Getters and Setters
• Getters and setters allow you to get and
set properties via methods.
• EN

You might also like