[Go to site: main page, start]

0% found this document useful (0 votes)
11 views38 pages

Java Script

JavaScript is a versatile, lightweight scripting language primarily used for web development, enabling both client-side and server-side applications. It was created in 1995 by Brendan Eich and has evolved to support various functionalities, including DOM manipulation, form validation, and game development. Despite its advantages such as ease of learning and no need for compilation, JavaScript has disadvantages like security vulnerabilities and inconsistent browser interpretations.

Uploaded by

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

Java Script

JavaScript is a versatile, lightweight scripting language primarily used for web development, enabling both client-side and server-side applications. It was created in 1995 by Brendan Eich and has evolved to support various functionalities, including DOM manipulation, form validation, and game development. Despite its advantages such as ease of learning and no need for compilation, JavaScript has disadvantages like security vulnerabilities and inconsistent browser interpretations.

Uploaded by

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

Introduction to JavaScript:

JavaScript is a lightweight, cross-platform and interpreted scripting language. It is well-known for


the development of web pages, many non-browser environments also use it.

JavaScript can be used for Client-side developments as well as Server-side developments.


JavaScript contains a standard library of objects, like Array, Date, and Math, and a core set of
language elements like operators, control structures, and statements.

 Client-side: It supplies objects to control a browser and its Document Object Model (DOM).
Like if client-side extensions allow an application to place elements on an HTML form and
respond to user events such as mouse clicks, form input, and page navigation. Use full
libraries for the client-side are AngularJS, ReactJS, VueJS and so many others.

 Server-side: It supplies objects relevant to running JavaScript on a server. Like if the server-
side extensions allow an application to communicate with a database, and provide continuity
of information from one invocation to another of the application, or perform file
manipulations on a server. The useful framework which is the most famous these days
is [Link].

History of JavaScript:
 It was created in 1995 by Brendan Eich while he was an engineer at Netscape.
 It was originally going to be named LiveScript but was renamed.
 Unlike most programming languages, the JavaScript language has no concept of input or
output.
 It is designed to run as a scripting language in a host environment, and it is up to the host
environment to provide mechanisms for communicating with the outside world.
 The most common host environment is the browser.
JS Structure:
<script type="text/javascript">
// Your javaScript code
</script>

Features of JavaScript: According to a recent survey conducted by Stack Overflow, JavaScript


is the most popular language on earth.
With advances in browser technology and JavaScript having moved into the server with [Link]
and other frameworks, JavaScript is capable of so much more. Here are a few things that we can do
with JavaScript:

 JavaScript was created in the first place for DOM manipulation. Earlier websites were
mostly static, after JS was created dynamic Web sites were made.

 Functions in JS are objects. They may have properties and methods just like another object.
They can be passed as arguments in other functions.

 Can handle date and time.

 Performs Form Validation although the forms are created using HTML.

 No compiler needed.

Platform for JavaScript:


 Web Development: Adding interactivity and behavior to static sites JavaScript was
invented to do this in 1995. By using AngularJS that can be achieved so easily.

 Web Applications: With technology, browsers have improved to the extent that a language
was required to create robust web applications. When we explore a map in Google Maps
then we only need to click and drag the mouse. All detailed view is just a click away, and
this is possible only because of JavaScript. It uses Application Programming
Interfaces(APIs) that provide extra power to the code. The Electron and React is helpful in
this department.

 Server Applications: With the help of [Link], JavaScript made its way from client to
server and [Link] is the most powerful in the server-side.
 Games: Not only in websites, JavaScript also helps in creating games for leisure. The
combination of JavaScript and HTML 5 makes JavaScript popular in game development as
well. It provides the EaseJS library which provides solutions for working with rich graphics.

 Smartwatches: JavaScript is being used in all possible devices and applications. It provides
a library PebbleJS which is used in smartwatch applications. This framework works for
applications that require the internet for its functioning.

 Art: Artists and designers can create whatever they want using JavaScript to draw on HTML
5 canvas, make sound more effective also can be used [Link] library.

 Machine Learning: This JavaScript [Link] library can be used in web development by
using machine learning.

Advantages of JS:

 JavaScript executed on the user’s browsers not on the webserver so it saves bandwidth and
load on the webserver.

 The JavaScript language is easy to learn it offers syntax that is close to English language.

 In JavaScript, if you ever need any certain feature then you can write it by yourself and use
an add-on like Greasemonkey to implement it on the web page.

 It does not require a compilation process so no compiler is needed user’s browsers do the
task.

 JavaScript is easy to debug, and there are lots of frameworks available that you can use and
become master on that.

Disadvantages of JS:

 JavaScript codes are visible to the user so user can place some code into the site that
compromises the security of data over the website. That will be security issue.

 All browsers interpret JavaScript that is correct, but they interpret differently to each other.

 It only supports single inheritance, so in few cases may require the object-oriented
language characteristic.

 A single error in code can totally stop the website’s code rendering on the website.
 JavaScript stores number as a 64-bit floating-point number but operators operate on 32-bit
bitwise operands.

JavaScript Statements:

The programming instructions written in a program in a programming language are known as


statements.

Order of execution of Statements is the same as they are written.

1. Semicolons:

 Semicolons separate JavaScript statements.

 Semicolon marks the end of a statement in javascript.

Example:

<html>
<body>
<h2>Welcome</h2>
<p id="bit"></p>
<script type=”javascript”>
// Statement 1
var a, b, c;
// Statement 2
a = 2;
// Statement 3
b = 3;
// Statement 4
c = a + b;
[Link](
"bit").innerHTML =
"The value of c is " + c + ".";
</script>
</body>
</html>

2. Code Blocks:
JavaScript statements can be grouped together inside curly brackets.
Such groups are known as code blocks.
The purpose of grouping is to define statements to be executed together.

Example:JavaScript function
<html>
<body>
<p>Welcome</p>
<button type="button"
> Click Me!
</button>
<p id="para1"></p>
<p id="para2"></p>
<script>
function myFunction() {

[Link]( "para1").innerHTML = "Hello";


[Link](
"para2").innerHTML =
"How are you?";
}
</script>
</body>
</html>

3. White Space:

 Javascript ignores multiple white spaces.

Javascript would treat following 2 statements as same:


Example:

var a="Hello everyone";

var a = "Hello everyone";

4. Line Length and Line Breaks:


Javascript code preferred line length by most programmers is upto 80 characters.

The best place to break a code line in Javascript, if it doesn’t fits, is after an operator.
Example:

[Link]("para").innerHTML =
"Hello Geek!";

5. Keywords:
Keywords are reserved words and cannot be used as variable name.
A Javascript keyword tells about what kind of operation it will perform.

Some commonly used keywords are:

 break: This is used to terminate a loop or switch.

 continue: This is used to skip a particular iteration in a loop and move to next
iteration.

 do…. while: In this the statements written within do block are executed till the
condition in while is true.

 for: It helps in executing a block of statements till the condition is true.

 function: This keyword is used to declare a function.

 return: This keyword is used to exit a function.

 var: This keyword is used to declare a variable.

 switch: This helps in executing a block of codes depending on different cases.

6. Comments in JavaScript

JavaScript supports both C-style and C++-style comments, Thus −


 Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
 Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
 JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats
this as a single-line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it should
be written as //-->.
Positioning Java Script:
There is a flexibility given to include JavaScript code anywhere in an HTML document.
However the most preferred ways to include JavaScript in an HTML file are as follows −
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in different
ways.

JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For
example:

1. var sum=10+20;

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.

40M

747

Java Try Catch

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 same type) 10==20 = false

!= 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 with Zero (10>>>2) = 2

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 Special Operators


The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-
else.

, Comma Operator allows multiple expressions to be evaluated as single


statement.

delete Delete Operator deletes a property from the object.


in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

Date Get Methods


Get methods are used for getting a part of a date. Here are the most common
(alphabetically):

Method Description

getDate() Get the day as a number (1-31)

getDay() Get the weekday as a number (0-6)

getFullYear() Get the four digit year (yyyy)

getHours() Get the hour (0-23)

getMilliseconds() Get the milliseconds (0-999)


getMinutes() Get the minutes (0-59)

getMonth() Get the month (0-11)

getSeconds() Get the seconds (0-59)

getTime() Get the time (milliseconds since January 1, 1970)

Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Operators</h2>
<p>x = 5, y = 2, calculate z = x + y, and display z:</p>
<p id="demo"></p>
<script>
let x = 5;
let y = 2;
let z = x + y;
[Link]("demo").innerHTML = z;
</script>
</body>
</html>

Example 2:
<!DOCTYPE html>
<html>
<body>
<h2>The += Operator</h2>
<p id="demo"></p>
<script>
var x = 10;
x += 5;
[Link]("demo").innerHTML = x;
</script>
</body>
</html>
Adding to String to number:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Operators</h2>
<p>adding a number and a string, returns a string.</p>
<p id="demo"></p>
<script>
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
[Link]("demo").innerHTML =
x + "<br>" + y + "<br>" + z;
</script>
</body>
</html>

JavaScript in <head>...</head> section

When the script needs to run on some event, such as when a user clicks somewhere, then that
script in the head as follows −
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert(“My World")
}
//-->
</script>
</head>

<body>
<input type = "button" value = "Click" />
</body>
</html>

JavaScript in <body>...</body> section

When a script needs to run as the page loads so that the script generates content in the page,
then the script goes in the <body> portion of the document. In this case, it would not have any
function defined using JavaScript.
<html>
<head>
</head>

<body>
<script type = "text/javascript">
<!--
[Link]("Hello World")
//-->
</script>

<p>This is web page body </p>


</body>
</html>

JavaScript in <body> and <head> Sections

We can include the JavaScript code in <head> and <body> section altogether as follows −
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<script type = "text/javascript">
<!--
[Link]("Hello World")
//-->
</script>

<input type = "button" value = "Say Hello" />


</body>
</html>

JavaScript in External File

There exist some situation where we are reusing identical JavaScript code on multiple pages of
a site.
The script tag provides a mechanism to allow to store JavaScript in an external file and then
include it into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML
code using script tag and its src attribute.
<html>
<head>
<script type = "text/javascript" src = "[Link]" ></script>
</head>

<body>
.......
</body>
</html>

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>
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money, name;
//-->
</script>
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.
For instance, you might create a variable named money and assign the value 2000.50 to it later.
For another variable, you can assign a value at the time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>

JavaScript Variable Scope

The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.
 Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
 Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the
same name. If you declare a local variable or function parameter with the same name as a global
variable, you effectively hide the global variable.
<html>
<body > <script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
[Link](myVar);
}
//-->
</script>
</body>
</html>

JavaScript Variable Names

While naming your variables in JavaScript, keep the following rules in mind.
 You should not use any of the JavaScript reserved keywords as a variable name. These
keywords are mentioned in the next section. For example, break or boolean variable
names are not valid.
 JavaScript variable names should not start with a numeral (0-9). They must begin with a
letter or an underscore character. For example, 123test is an invalid variable name
but _123test is a valid one.
 JavaScript variable names are case-sensitive. For example, Name and name are two
different variables.

JavaScript Reserved Words

A list of all the reserved words in JavaScript are given in the following table. They cannot be
used as JavaScript variables, functions, methods, loop labels, or any object names.

abstract else instanceof switch

boolean enum int synchronized

break export interface this

byte extends long throw

case false native throws

catch final new transient

char finally null true

class float package try


const for private typeof

continue function protected var

debugger goto public void

default if return volatile

delete implements short while

do import static with

double in super

Javascript Conditions:

JavaScript supports conditional statements which are used to perform different actions based on
different conditions. Here we will explain the if..else statement.

Flow Chart of if-else

The following flow chart shows how the if-else statement works.
JavaScript supports the following forms of if..else statement −
 if statement
 if...else statement
 if...else if... statement.

if statement

The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}

Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
are executed. If the expression is false, then no statement would be not executed. Most of the
times, you will use comparison operators while making decisions.
Example
<html>
<body>
<script type = "text/javascript">
var age = 20;

if( age > 18 ) {


// [Link]("<b>Qualifies for driving</b>");
[Link](“para1”).innerHTML=("<b>Qualifies for driving</b>");

}
</script>
<p id=”para1”>Set the variable to different value and then try...</p>
</body>
</html>

Output
Qualifies for driving
Set the variable to different value and then try...

if...else statement

The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in
the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
block are executed.
Example
<html>
<body>
<script type = "text/javascript">
var age = 15;

if( age > 18 ) {


[Link]("<b>Qualifies for driving</b>");
} else {
[Link]("<b>Does not qualify for driving</b>");
}
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Does not qualify for driving
Set the variable to different value and then try...

if...else if... statement

The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a part
of the else clause of the previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is executed.
Example
<html>
<body>
<script type = "text/javascript">
var book = "maths";
if( book == "history" ) {
[Link]("<b>History Book</b>");
} else if( book == "maths" ) {
[Link]("<b>Maths Book</b>");
} else if( book == "economics" ) {
[Link]("<b>Economics Book</b>");
} else {
[Link]("<b>Unknown Book</b>");
}
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>

Output
Maths Book
Set the variable to different value and then try...
JavaScript supports all the necessary loops to ease down the pressure of programming.

The while Loop

The most basic loop in JavaScript is the while loop which would be discussed in this chapter.
The purpose of a while loop is to execute a statement or code block repeatedly as long as
an expression is true. Once the expression becomes false, the loop terminates.
Flow Chart
The flow chart of while loop looks as follows −

Syntax
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}

Example
<html>
<body>

<script type = "text/javascript">


var count = 0;
[Link]("Starting Loop ");

while (count < 10) {


[Link]("Current Count : " + count + "<br />");
count++;
}

[Link]("Loop stopped!");
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

The do...while Loop

The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Flow Chart
The flow chart of a do-while loop would be as follows −
Syntax
The syntax for do-while loop in JavaScript is as follows −
do {
Statement(s) to be executed;
} while (expression);
Example
<html>
<body>
<script type = "text/javascript">
var count = 0;

[Link]("Starting Loop" + "<br />");


do {
[Link]("Current Count : " + count + "<br />");
count++;
}

while (count < 5);


[Link] ("Loop stopped!");

</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...
The 'for' loop is the most compact form of looping. It includes the following three important
parts −
 The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
 The test statement which will test if a given condition is true or not. If the condition is
true, then the code given inside the loop will be executed, otherwise the control will
come out of the loop.
 The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.

Flow Chart

The flow chart of a for loop in JavaScript would be as follows −

Syntax
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Example
Try the following example to learn how a for loop works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var count;
[Link]("Starting Loop" + "<br />");

for(count = 0; count < 10; count++) {


[Link]("Current Count : " + count );
[Link]("<br />");
}
[Link]("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
JavaScript Popup Boxes

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

Alert Box

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

When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
[Link]("sometext");

The [Link]() method can be written without the window prefix.

<html>

<body>

<h2>JavaScript Alert</h2>

<button it</button>

<script>

function myFunction() {

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

</script>

</body>

</html>

Confirm Box

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

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

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

Syntax
[Link]("sometext");

The [Link]() method can be written without the window prefix.

<html>

<body>

<h2>JavaScript Confirm Box</h2>


<button it</button>

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

<script>

function myFunction() {

var txt;

if (confirm("Press a button!")) {

txt = "You pressed OK!";

} else {

txt = "You pressed Cancel!";

[Link]("demo").innerHTML = txt;

</script>

</body>

</html>

Prompt Box

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

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

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

Syntax
[Link]("sometext","defaultText");

The [Link]() method can be written without the window prefix.

<html>
<body>

<h2>JavaScript Prompt</h2>

<button it</button>

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

<script>

function myFunction() {

let text;

let person = prompt("Please enter your name:", "Harry Potter");

if (person == null || person == "") {

text = "User cancelled the prompt.";

} else {

text = "Hello " + person + "! How are you today?";

[Link]("demo").innerHTML = text;

</script>

</body>

</html>

External JavaScript

Scripts can also be placed in external files:

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

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of
a <script> tag:
You can place an external script reference in <head> or <body> as you like.

The script will behave as if it was located exactly where the <script> tag is located.

External scripts cannot contain <script> tags.

External file: [Link]


function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
}

HTML File:

<html>

<body>

<h2>External JavaScript</h2>

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

<button type="button" it</button>

<p>This example links to "[Link]".</p>

<p>(myFunction is stored in "[Link]")</p>

<script src="[Link]"></script>

</body>

</html>

Advanced JavaScript
 JavaScript is designed on a simple object-based paradigm.
 An object is a collection of properties, and a property is an association between a name
(or key) and a value.
 A property's value can be a function, in which case the property is known as a method.

Objects overview
 Objects in JavaScript, just as in many other programming languages, can be compared to
objects in real life. The concept of objects in JavaScript can be understood with real life,
tangible objects.

 In JavaScript, an object is a standalone entity, with properties and type. Compare it with a
cup, for example. A cup is an object, with properties.

 A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript
objects can have properties, which define their characteristics.

Objects and properties

1. A JavaScript object has properties associated with it.

2. A property of an object can be explained as a variable that is attached to the object.

3. Object properties are basically the same as ordinary JavaScript variables, except for the
attachment to objects. The properties of an object define the characteristics of the object.

4. We can access the properties of an object with a simple dot-notation:

[Link]

 Like all JavaScript variables, both the object name (which could be a normal variable) and
property name are case sensitive. We can define a property by assigning it a value. For
example, let's create an object named myCar and give it properties named make, model,
and year as follows:
 It is written using an object initializer, which is a comma-delimited list of zero or more
pairs of property names and associated values of an object, enclosed in curly braces ({}):
var myCar = {

make: 'Ford',

model: 'Mustang',

year: 1969,

};
Unassigned properties of an object are undefined (and not null).

[Link]; // undefined

Properties of JavaScript objects can also be accessed or set using a bracket notation
Objects are sometimes called associative arrays, since each property is associated with a string
value that can be used to access it.

JavaScript for...in Loop

The JavaScript for...in statement loops through the properties of an object.

Syntax
for (variable in object) {
// code to be executed
}

The block of code inside of the for...in loop will be executed once for each property.

Looping through the properties of an object:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Object Properties</h2>
<p id="demo"></p>
<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt =txt+ person[x] + " ";
}
[Link]("demo").innerHTML = txt;
</script>
</body>
</html>

Adding New Properties

You can add new properties to an existing object by simply giving it a value.

Assume that the person object already exists - you can then give it new properties:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>


<p>You can add new properties to existing objects.</p>
<p id="demo"></p>
<script>
var person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};
[Link] = "India";

[Link]("demo").innerHTML =
[Link] + " is from " + [Link] + ".";
</script>
</body>
</html>

Deleting Properties

The delete keyword deletes a property from an object:

The delete keyword deletes both the value of the property and the property itself.
After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no effect on variables or
functions.

The delete operator should not be used on predefined JavaScript object properties. It can crash
your application.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Object Properties</h2>
<p>You can delete object properties.</p>
<p id="demo"></p>
<script>
var person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};

delete [Link];
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";

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

JavaScript Object Methods

JavaScript methods are actions that can be performed on objects.

A JavaScript method is a property containing a function definition.

Property Value

firstName John
lastName Doe

age 50

eyeColor Blue

fullName function() {return [Link] + " " + [Link];}

Methods are functions stored as object properties.

<!DOCTYPE html>
<html>
<body>
<h2>The JavaScript <i>this</i> Keyword</h2>
<p>In this example, <b>this</b> represents the <b>person</b> object.</p>
<p>Because the person object "owns" the fullName method.</p>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return [Link] + " " + [Link];
}
};

// Display data from the object:


[Link]("demo").innerHTML = [Link]();
</script>
</body>
</html>

Accessing Object Methods

You access an object method with the following syntax:

[Link]()
You will typically describe fullName() as a method of the person object, and fullName as a
property.

The fullName property will execute (as a function) when it is invoked with ().

This example accesses the fullName() method of a person object:

<!DOCTYPE html>
<html>
<body>
<p>Creating and using an object method.</p>
<p>A method is actually a function definition stored as a property value.</p>
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return [Link] + " " + [Link];
}
};
[Link]("demo").innerHTML = [Link]();
</script>
</body>
</html>

Adding a Method to an Object

Adding a new method to an object is easy:

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
};
[Link] = function() {
return [Link] + " " + [Link];
};
[Link]("demo").innerHTML =
"My father is " + [Link]();
</script>
</body>
</html>

Display JavaScript Objects

Some common solutions to display JavaScript objects are:

 Displaying the Object Properties by name


 Displaying the Object Properties in a Loop
 Displaying the Object using [Link]()

Displaying Object Properties by name:

The properties of an object can be displayed as a string:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Display Object Properties</h2>
<p id="demo"></p>
<script>
var person = {name:"John", age:50, city:"New York"};
[Link]("demo").innerHTML = [Link] + " " + [Link] + ","
+ [Link];
</script>
</body>
</html>

Displaying the Object in a Loop

The properties of an object can be collected in a loop:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Display Object Properties</h2>
<p id="demo"></p>
<script>
var x, txt = "";
var person = {name:"John", age:50, city:"New York"};
for (x in person) {
txt += person[x] + " ";
};
[Link]("demo").innerHTML = txt;
</script>
</body>
</html>

Using [Link]()

Any JavaScript object can be converted to an array using [Link]():

Syntax:
var person = {name:"John", age:30, city:"New York"};

var myArray = [Link](person);

Example program:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Display Objects</h2>
<p>[Link]() converts an object to an array.</p>
<p id="demo"></p>
<script>
var person = {name:"John", age:50, city:"New York"};
var myArray = [Link](person);
[Link]("demo").innerHTML = myArray;
</script>
</body>
</html>

You might also like