You are on page 1of 46

JAVASCRIPT

What is JavaScript ?

A programming language may be used to create stand-alone programs. A scripting


language is usually built into a specific application like a database or spreadsheet
or webpage and cannot be used outside of that application.

JavaScript is a scripting language, not a full programming language. It is also not


an outgrowth of the Java programming language.

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 was designed to 'plug a gap' in the techniques available for creating
web-pages.

HTML is relatively easy to learn, but it is static. It allows the use of links to load
new pages, images, sounds, etc., but it provides very little support for any other
type of interactivity.

JavaScript may be added to the head, or to the body, of an HTML source


document, but the effects are different!

Uses of JavaScript

• Use it to add multimedia elements

With JavaScript you can show, hide, change, resize images, and

create image rollovers. You can create scrolling text across the status

bar.

• Create pages dynamically


Based on the user's choices, the date, or other external data, JavaScript

can produce pages that are customized to the user.

• Interact with the user

It can do some processing of forms and can validate user input when

the user submits the form.

Writing JavaScript

JavaScript code is typically embedded in the HTML, to be interpreted and

run by the client's browser. Here are some tips to remember when writing

JavaScript commands.

• JavaScript code is case sensitive

• White space between words and tabs are ignored

• Line breaks are ignored except within a statement

• JavaScript statements end with a semi- colon ;

The SCRIPT Tag

The <SCRIPT> tag alerts a browser that JavaScript code follows. It is

typically embedded in the HTML.

<SCRIPT language = "JavaScript">

statements

</SCRIPT>
Using JavaScript in your HTML

<html>

<head>

<title>Hello World in JavaScript</title>

<script type=

"text/javascript">

function helloWorld() {

document.write("Hello World!");

</script>

</head>

<body>

<script type=

"text/javascript">

helloWorld();

</script>

</body>

</html>
Implementing JavaScript
There are three ways to add JavaScript commands to your Web Pages.
• Embedding code
• Inline code
• External file

Inline Java Script


When java script was written within the html element using attributes related to
events of the element then it is called as inline java script.

Java Script Dialog Boxes


Alert() : Alert function of java script is used to give an alert message to the user.
Prompt() : Prompt function of java script is used to prompt for a value from the
user.
Confirm() : confirm function of java script is used to get confirmation from user
before executing some task.
Example : The following example gives an alert message to the user when user
click on the button using inline java script.
<!doctype html>
<html>
<form>
<input type=”button” value=”Click” onclick=”alert(‘Button Clicked’)”/>
</form>
</html>

Internal Java Script


When java script was written within the <head> section using <script> element
then it is called as internal java script. The <script> element syntax is as follows.
<script type=”text/javascript”>
</script>
Within the <head> section java script will be written in the form of functions. To
create a function in java script use the keyword function and it has the following
syntax.

External File
You can use the SRC attribute of the <SCRIPT> tag to call JavaScript code
from an external text file. This is useful if you have a lot of code or you
want to run it from several pages, because any number of pages can call the
same external JavaScript file. The text file itself contains no HTML tags. It
is call by the following tag:
<SCRIPT SRC="filename.js">
</SCRIPT>

External Example
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>(myFunction is stored in an external file called "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>

JavaScript data types

JavaScript is a loosely typed or a dynamic language. That means you don't have to
declare the type of a variable ahead of time. The type will get determined
automatically while the program is being processed. That also means that you can
have the same variable as different types:

Ex: var foo = 42; // foo is now a Number

var foo = 'bar'; // foo is now a String

var foo = true; // foo is now a Boolean

There are seven data types:

 Six data types that are primitives:


1. Boolean

2. Null

3. Undefined

4. Number

5. String

6. Symbol (new in ECMAScript 6)

 and Object

Primitive values

All types except objects define immutable values (values, which are incapable of
being changed). For example and unlike to C, Strings are immutable. We refer to
values of these types as "primitive values".

Boolean type

Boolean represents a logical entity and can have two values: true, and false.

Null type

The Null type has exactly one value: null. See null and Null for more details.

Undefined type

A variable that has not been assigned a value has the value undefined. See
undefined and Undefined for more details.

Number type

According to the ECMAScript standard, there is only one number type: the
double-precision 64-bit binary format IEEE 754 value (number between -(253
-1) and 253 -1). There is no specific type for integers. In addition to being able
to represent floating-point numbers, the number type has three symbolic
values: +Infinity, -Infinity, and NaN (not-a-number).

To check for the largest available value or smallest available value within +/-
Infinity, you can use the constants Number.MAX_VALUE or
Number.MIN_VALUE and starting with ECMAScript 6, you are also able to check
if a number is in the double-precision floating-point number range using
Number.isSafeInteger() as well as Number.MAX_SAFE_INTEGER and
Number.MIN_SAFE_INTEGER. Beyond this range, integers in JavaScript are not
safe anymore and will be a double-precision floating point approximation of
the value.

The number type has only one integer that has two representations: 0 is
represented as -0 and +0. ("0" is an alias for +0). In the praxis, this has almost
no impact. For example +0 === -0 is true. However, you are able to notice this
when you divide by zero:

> 42 / +0

Output: Infinity

> 42 / -0

Output: -Infinity

Although a number often represents only its value, JavaScript provides some
binary operators. These can be used to represent several Boolean values within
a single number using bit masking. However, this is usually considered a bad
practice, since JavaScript offers other means to represent a set of Booleans
(like an array of Booleans or an object with Boolean values assigned to named
properties). Bit masking also tends to make code more difficult to read,
understand, and maintain. It may be necessary to use such techniques in very
constrained environments, like when trying to cope with the storage limitation
of local storage or in extreme cases when each bit over the network counts.
This technique should only be considered when it is the last measure that can
be taken to optimize size.
String type

JavaScript's String type is used to represent textual data. It is a set of


"elements" of 16-bit unsigned integer values. Each element in the String
occupies a position in the String. The first element is at index 0, the next at
index 1, and so on. The length of a String is the number of elements in it.

Unlike in languages like C, JavaScript strings are immutable. This means that
once a string is created, it is not possible to modify it. However, it is still
possible to create another string based on an operation on the original string.
For example:

A substring of the original by picking individual letters or using String.substr().

A concatenation of two strings using the concatenation operator (+) or


String.concat().

Beware of "stringly-typing" your code!

It can be tempting to use strings to represent complex data. Doing this comes
with short-term benefits:

It is easy to build complex strings with concatenation.

Strings are easy to debug (what you see printed is always what is in the string).

Strings are the common denominator of a lot of APIs (input fields, local storage
values, XMLHttpRequest responses when using responseText, etc.) and it can
be tempting to only work with strings.

With conventions, it is possible to represent any data structure in a string. This


does not make it a good idea. For instance, with a separator, one could
emulate a list (while a JavaScript array would be more suitable). Unfortunately,
when the separator is used in one of the "list" elements, then, the list is
broken. An escape character can be chosen, etc. All of this requires
conventions and creates an unnecessary maintenance burden.

Use strings for textual data. When representing complex data, parse strings
and use the appropriate abstraction.

Symbol type

Symbols are new to JavaScript in ECMAScript Edition 6. A Symbol is a unique


and immutable primitive value and may be used as the key of an Object
property (see below). In some programming languages, Symbols are called
atoms. For more details see Symbol and the Symbol object wrapper in
JavaScript.

Objects

In computer science, an object is a value in memory which is possibly


referenced by an identifier.

Properties

In JavaScript, objects can be seen as a collection of properties. With the object


literal syntax, a limited set of properties are initialized; then properties can be
added and removed. Property values can be values of any type, including other
objects, which enables building complex data structures. Properties are
identified using key values. A key value is either a String or a Symbol value.

There are two types of object properties which have certain attributes: The
data property and the accessor property.
Data property

Associates a key with a value and has the following attributes:

Attributes of a data property

Default
Attribute Type Description
value

Any
The value retrieved by a
[[Value]] JavaScript undefined
get access of the property.
type

If false, the property's


[[Writable]] Boolean [[Value]] can't be false
changed.

Accessor property

Associates a key with one or two accessor functions (get and set) to retrieve or
store a value and has the following attributes:

Attributes of an accessor property

Default
Attribute Type Description
value

[[Get]] Function The function is called with an undefined


object or empty argument list and
undefined retrieves the property value
whenever a get access to the
value is performed. See
also get.

The function is called with an


argument that contains the
Function
assigned value and is executed
[[Set]] object or undefined
whenever a specified property
undefined
is attempted to be changed.
See also set.

Variables
Programmers use variables to store values. A variable can hold several types
of data. In JavaScript you don't have to declare a variable's data type before
using it. Any variable can hold any JavaScript data type, including:
• String data
• Numbers
• Boolean values (T/F)

Variable Names
There are rules and conventions in naming variables in any programming
language. It is good practice to use descriptive names for variables. The
following are the JavaScript rules:
• The variable name must start with a letter or an underscore.
firstName or _myName
• You can use numbers in a variable name, but not as the first
character.
name01 or tuition$
• You can't use space to separate characters.
userName not user Name
• Capitalize the first letter of every word except the first
salesTax or userFirstName

• To declare variables, use the keyword var and the variable name:
var userName
• To assign values to variables, add an equal sign and the value:
var userName = "Smith"
var price = 100

Array

It stores a fixed-size sequential collection of elements of the same type.

Syntax

Use the following syntax to create an Array object −

var fruits = new Array( "apple", "orange", "mango" );

You can create array by simply assigning values as follows −

var fruits = [ "apple", "orange", "mango" ];

You will use ordinal numbers to access and to set values inside an array as follows.

fruits[0] is the first element

fruits[1] is the second element

fruits[2] is the third element

Array Properties
Here is a list of the properties of the Array object along with their description.

Property Description

constructo Returns a reference to the array function that


r created the object.

index The property represents the zero-based index of


the match in the string
input This property is only present in arrays created by
regular expression matches.

length Reflects the number of elements in an array.

prototype The prototype property allows you to add


properties and methods to an object.

In the following sections, we will have a few examples to illustrate the usage of
Array properties.

Array Methods
Here is a list of the methods of the Array object along with their description.

Method Description

concat() Returns a new array comprised of this array


joined with other array(s) and/or value(s).

every() Returns true if every element in this array


satisfies the provided testing function.

filter() Creates a new array with all of the elements of


this array for which the provided filtering
function returns true.

forEach() Calls a function for each element in the array.

indexOf() Returns the first (least) index of an element


within the array equal to the specified value, or
-1 if none is found.
join() Joins all elements of an array into a string.

lastIndexOf( Returns the last (greatest) index of an element


) within the array equal to the specified value, or
-1 if none is found.

Operators
JavaScript supports the following types of operators.

 Arithmetic Operators

 Comparision Operators

 Logical (or Relational) Operators

 Assignment Operators

 Conditional (or ternary) Operators

Arithmetic Operators
JavaScript supports the following arithmetic operators −

Assume variable A holds 10 and variable B holds 20, then −

Sr.No Operator and Description

1 + (Addition)

Adds two operands

Ex: A + B will give 30

2 - (Subtraction)
Subtracts the second operand from the first

Ex: A - B will give -10

3 * (Multiplication)

Multiply both operands

Ex: A * B will give 200

4 / (Division)

Divide the numerator by the denominator

Ex: B / A will give 2

5 % (Modulus)

Outputs the remainder of an integer division

Ex: B % A will give 0

6 ++ (Increment)

Increases an integer value by one

Ex: A++ will give 11

7 -- (Decrement)

Decreases an integer value by one

Ex: A-- will give 9

Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10
will give "a10".
Comparison Operators
JavaScript supports the following comparison operators −

Assume variable A holds 10 and variable B holds 20, then −

Sr.No Operator and Description

1 = = (Equal)

Checks if the value of two operands are equal or not, if


yes, then the condition becomes true.

Ex: (A == B) is not true.

2 != (Not Equal)

Checks if the value of two operands are equal or not, if


the values are not equal, then the condition becomes
true.

Ex: (A != B) is true.

3 > (Greater than)

Checks if the value of the left operand is greater than


the value of the right operand, if yes, then the condition
becomes true.

Ex: (A > B) is not true.

4 < (Less than)

Checks if the value of the left operand is less than the


value of the right operand, if yes, then the condition
becomes true.
Ex: (A < B) is true.

5 >= (Greater than or Equal to)

Checks if the value of the left operand is greater than or


equal to the value of the right operand, if yes, then the
condition becomes true.

Ex: (A >= B) is not true.

6 <= (Less than or Equal to)

Checks if the value of the left operand is less than or


equal to the value of the right operand, if yes, then the
condition becomes true.

Ex: (A <= B) is true.

Logical Operators
JavaScript supports the following logical operators −

Assume variable A holds 10 and variable B holds 20, then −

Sr.No Operator and Description

1 && (Logical AND)

If both the operands are non-zero, then the condition


becomes true.

Ex: (A && B) is true.

2 || (Logical OR)
If any of the two operands are non-zero, then the
condition becomes true.

Ex: (A || B) is true.

3 ! (Logical NOT)

Reverses the logical state of its operand. If a condition


is true, then the Logical NOT operator will make it
false.

Ex: ! (A && B) is false.

Bitwise Operators
JavaScript supports the following bitwise operators −

Assume variable A holds 2 and variable B holds 3, then −

Sr.No Operator and Description

1 & (Bitwise AND)

It performs a Boolean AND operation on each bit of its


integer arguments.

Ex: (A & B) is 2.

2 | (BitWise OR)

It performs a Boolean OR operation on each bit of its


integer arguments.

Ex: (A | B) is 3.

3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each
bit of its integer arguments. Exclusive OR means that
either operand one is true or operand two is true, but
not both.

Ex: (A ^ B) is 1.

4 ~ (Bitwise Not)

It is a unary operator and operates by reversing all the


bits in the operand.

Ex: (~B) is -4.

5 << (Left Shift)

It moves all the bits in its first operand to the left by the
number of places specified in the second operand. New
bits are filled with zeros. Shifting a value left by one
position is equivalent to multiplying it by 2, shifting
two positions is equivalent to multiplying by 4, and so
on.

Ex: (A << 1) is 4.

6 >> (Right Shift)

Binary Right Shift Operator. The left operand’s value is


moved right by the number of bits specified by the right
operand.

Ex: (A >> 1) is 1.

7 >>> (Right shift with Zero)

This operator is just like the >> operator, except that the
bits shifted in on the left are always zero.

Ex: (A >>> 1) is 1.

Assignment Operators
JavaScript supports the following assignment operators −

Sr.No Operator and Description

1 = (Simple Assignment )

Assigns values from the right side operand to the left


side operand

Ex: C = A + B will assign the value of A + B into C

2 += (Add and Assignment)

It adds the right operand to the left operand and assigns


the result to the left operand.

Ex: C += A is equivalent to C = C + A

3 −= (Subtract and Assignment)

It subtracts the right operand from the left operand and


assigns the result to the left operand.

Ex: C -= A is equivalent to C = C - A

4 *= (Multiply and Assignment)

It multiplies the right operand with the left operand and


assigns the result to the left operand.
Ex: C *= A is equivalent to C = C * A

5 /= (Divide and Assignment)

It divides the left operand with the right operand and


assigns the result to the left operand.

Ex: C /= A is equivalent to C = C / A

6 %= (Modules and Assignment)

It takes modulus using two operands and assigns the


result to the left operand.

Ex: C %= A is equivalent to C = C % A

Note − Same logic applies to Bitwise operators so they will become like <<=, >>=,
>>=, &=, |= and ^=.

Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript:
the conditional operator (? :) and the typeof operator.

Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value
and then executes one of the two given statements depending upon the result of
the evaluation.

Sr.No Operator and Description

1 ? : (Conditional )

If Condition is true? Then value X : Otherwise value Y


typeof Operator
The typeof operator is a unary operator that is placed before its single operand,
which can be of any type. Its value is a string indicating the data type of the
operand.

The typeof operator evaluates to "number", "string", or "boolean" if its operand


is a number, string, or boolean value and returns true or false based on the
evaluation.

Here is a list of the return values for the typeof Operator.

Type String Returned by typeof

Number "number"

String "string"

Boolean "boolean"

Object "object"

Function "function"

Undefined "undefined"

Null "object"

Expressions

An expression is any valid unit of code that resolves to a value.


Every syntactically valid expression resolves to some value but conceptually, there are two
types of expressions: with side effects (for example: those that assign value to a variable) and
those that in some sense evaluates and therefore resolves to value.

The expression x = 7 is an example of the first type

The code 3 + 4 is an example of the second expression type

JavaScript has the following expression categories:

 Arithmetic: evaluates to a number, for example 3.14159. (Generally


uses arithmetic operators.)

 String: evaluates to a character string, for example, "Fred" or "234".


(Generally uses string operators.)

 Logical: evaluates to true or false. (Often involves logical operators.)

 Primary expressions: Basic keywords and general expressions in


JavaScript.

 Left-hand-side expressions: Left values are the destination of an


assignment.

Primary expressions

Basic keywords and general expressions in JavaScript.

this

Use the this keyword to refer to the current object. In general, this refers to the
calling object in a method. Use this either with the dot or the bracket notation:

this['propertyName']

this.propertyName

Grouping operator
The grouping operator ( ) controls the precedence of evaluation in expressions.
For example, you can override multiplication and division first, then addition and
subtraction to evaluate addition first.

Comprehensions

Comprehensions are an experimental JavaScript feature, targeted to be included


in a future ECMAScript version. There are two versions of comprehensions:

[for (x of y) x]

Array comprehensions.

(for (x of y) y)

Generator comprehensions.

Comprehensions exist in many programming languages and allow you to quickly


assemble a new array based on an existing one.

Left-hand-side expressions

Left values are the destination of an assignment.

new

You can use the new operator to create an instance of a user-defined object type
or of one of the built-in object types. Use new as follows:

var objectName = new objectType([param1, param2, ..., paramN]);

super

The super keyword is used to call functions on an object's parent. It is useful


with classes to call the parent constructor, for example.

super([arguments]); // calls the parent constructor.


super.functionOnParent([arguments]);

Spread operator

The spread operator allows an expression to be expanded in places where


multiple arguments (for function calls) or multiple elements (for array literals) are
expected.

Example: Today if you have an array and want to create a new array with the
existing one being part of it, the array literal syntax is no longer sufficient and you
have to fall back to imperative code, using a combination of push, splice, concat,
etc. With spread syntax this becomes much more succinct:

var parts = ['shoulder', 'knees'];

var lyrics = ['head', ...parts, 'and', 'toes'];

Looping

Very often when you write code, you want the same block of code to run a
number of times. You can use looping statements in your code to do this.

JavaScript supports different kinds of loops:

 for - loops through a block of code a number of times

 for/in - loops through the properties of an object

 while - loops through a block of code while a specified condition is


true

 do/while - also loops through a block of code while a specified


condition is true

The For Loop

The for loop has the following syntax:


for (statement 1; statement 2; statement 3) {
code block to be executed
}

Statement 1 is executed before the loop (the code block) starts.

Statement 2 defines the condition for running the loop (the code block).

Statement 3 is executed each time after the loop (the code block) has been
executed.

Example:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Loops</h2>

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

<script>

var text = "";

var i;

for (i = 0; i < 5; i++) {

text += "The number is " + i + "<br>";

document.getElementById("demo").innerHTML = text;
</script>

</body>

</html>

The For/In Loop

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

Example:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Loops</h2>

<p>The for/in statement loops through the properties of an object.</p>

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

<script>

var txt = "";

var person = {fname:"John", lname:"Doe", age:25};

var x;

for (x in person) {

txt += person[x] + " ";

document.getElementById("demo").innerHTML = txt;

</script>
</body>

</html>

The While Loop

The while loop loops through a block of code as long as a specified condition is
true.

Syntax
while (condition) {
code block to be executed
}

Example
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript while</h2>

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

<script>

var text = "";

var i = 0;

while (i < 10) {

text += "<br>The number is " + i;

i++;

document.getElementById("demo").innerHTML = text;
</script>

</body>

</html>

If you forget to increase the variable used in the condition, the loop will never
end. This will crash your browser.

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop as
long as the condition is true.

Syntax
do {
code block to be executed
}
while (condition);

Example
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript do ... while</h2>

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

<script>

var text = ""


var i = 0;

do {

text += "<br>The number is " + i;

i++;

while (i < 10);

document.getElementById("demo").innerHTML = text;

</script>

</body>

</html>

JavaScript Break and Continue

he break statement "jumps out" of a loop.

The continue statement "jumps over" one iteration in the loop.

The Break Statement

The break statement can also be used to jump out of a loop.

The break statement breaks the loop and continues executing the code after the
loop (if any):

Example:

<!DOCTYPE html>

<html>
<body>

<p>A loop with a break.</p>

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

<script>

var text = "";

var i;

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

if (i === 3) { break; }

text += "The number is " + i + "<br>";

document.getElementById("demo").innerHTML = text;

</script>

</body>

</html>

The 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.

Example
<!DOCTYPE html>

<html>

<body>

<p>A loop which will skip the step where i = 3.</p>


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

<script>

var text = "";

var i;

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

if (i === 3) { continue; }

text += "The number is " + i + "<br>";

document.getElementById("demo").innerHTML = text;

</script>

</body>

</html>

Functions
With functions, you can give a name to a whole block of code, allowing you
to reference it from anywhere in your program. JavaScript has built-in
functions for several predefined operations. Here are three functions.
• alert("message")
• confirm("message")
• prompt("message")
JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name,


followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


code to be executed
}

A function can have up to 255 arguments.

Function parameters are the names listed in the function definition.

Function arguments are the real values received by the function when it is
invoked.

Inside the function, the arguments (the parameters) behave as local variables.

A Function is much the same as a Procedure or a Subroutine, in other


programming languages.

Function Invocation

The code inside the function will execute when "something" invokes (calls) the
function:

 When an event occurs (when a user clicks a button)

 When it is invoked (called) from JavaScript code

 Automatically (self invoked)

Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to
the "caller":

Example

Calculate the product of two numbers, and return the result:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation and returns the
result:</p>

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

<script>

function myFunction(a, b) {

return a * b;

document.getElementById("demo").innerHTML = myFunction(4, 3);

</script>

</body>

</html>

The () Operator Invokes the Function


Accessing a function without () will return the function definition instead of the
function result
Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations

JavaScript Objects
objects are variables too. But objects can contain many values.

Example:

<!DOCTYPE html>

<html>

<body>

<p>Creating a JavaScript Object.</p>

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

<script>

var car = {type:"Fiat", model:"500", color:"white"};

document.getElementById("demo").innerHTML = car.type;

</script>

</body>

</html>

The values are written as name:value pairs (name and value separated by a
colon).

JavaScript objects are containers for named values.


Object Properties

The name:values pairs (in JavaScript objects) are called properties.

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Object Methods

Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions.

JavaScript objects are containers for named values called properties or methods.

Object Definition

You define (and create) a JavaScript object with an object literal:

Spaces and line breaks are not important. An object definition can span multiple
lines:

Example:

<!DOCTYPE html>

<html>

<body>

<p>Creating a JavaScript Object.</p>

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

<script>

var person = {

firstName : "John",
lastName : "Doe",

age : 50,

eyeColor : "blue"

};

document.getElementById("demo").innerHTML =

person.firstName + " is " + person.age + " years old.";

</script>

</body>

</html>

Accessing Object Properties

You can access object properties in two ways:

objectName.propertyName

or

objectName["propertyName"]

Accessing Object Methods

You access an object method with the following syntax:

objectName.methodName()

Dialog Boxes
javaScript supports three important types of dialog boxes. These dialog boxes can
be used to raise and alert, or to get confirmation on any input or to have a kind of
input from the users.
Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For
example, if one input field requires to enter some text but the user does not
provide any input, then as a part of validation, you can use an alert box to give a
warning message.

Nonetheless, an alert box can still be used for friendlier messages. Alert box gives
only one button "OK" to select and proceed.

Example

<html>

<head>

<script type="text/javascript">

<!--

function Warn() {

alert ("This is a warning message!");

document.write ("This is a warning message!"); }

//-->

</script>

</head>

<body>

<p>Click the following button to see the result: </p>

<form>

<input type="button" value="Click Me" onclick="Warn();" />

</form>

</body>
</html>

Confirmation Dialog Box

A confirmation dialog box is mostly used to take user's consent on any option. It
displays a dialog box with two buttons: Cancel.

If the user clicks on the OK button, the window method confirm() will return true.
If the user clicks on the Cancel button, then confirm() returns false. You can use a
confirmation dialog box as follows.

Example

<html>

<head>

<script type="text/javascript">

<!--

function getConfirmation(){

var retVal = confirm("Do you want to continue ?");

if( retVal == true ){

document.write ("User wants to continue!");

return true;

else{

document.write ("User does not want to continue!");

return false;
}

//-->

</script>

</head>

<body>

<p>Click the following button to see the result: </p>

<form>

<input type="button" value="Click Me" onclick="getConfirmation();" />

</form>

</body>

</html>

Prompt Dialog Box

The prompt dialog box is very useful when you want to pop-up a text box to get
user input. Thus, it enables you to interact with the user. The user needs to fill in
the field and then click OK.

This dialog box is displayed using a method called prompt() which takes two
parameters: (i) a label which you want to display in the text box and (ii) a default
string to display in the text box.

This dialog box has two buttons: OK and Cancel. If the user clicks the OK button,
the window method prompt() will return the entered value from the text box. If
the user clicks the Cancel button, the window method prompt() returns null.
Example

The following example shows how to use a prompt dialog box −

<html>

<head>

<script type="text/javascript">

<!--

function getValue(){

var retVal = prompt("Enter your name : ", "your name here");

document.write("You have entered : " + retVal);

//-->

</script>

</head>

<body>

<p>Click the following button to see the result: </p>

<form>

<input type="button" value="Click Me" onclick="getValue();" />

</form>

</body>

</html>

Events and events handling:


JavaScript's interaction with HTML is handled through events that occur when
the user or the browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button, that
click too is an event. Other examples include events like pressing any key, closing
a window, resizing a window, etc.

Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable.

onclick Event Type

This is the most frequently used event type which occurs when a user clicks the left button of
his mouse. You can put your validation, warning etc., against this event type.

Example

Try the following example.

<html>

<head>

<script type="text/javascript">

<!--

function sayHello() {
alert("Hello World")

//-->

</script>

</head>

<body>

<p>Click the following button and see result</p>

<form>

<input type="button" onclick="sayHello()" value="Say Hello" />

</form>

</body>

</html>
onsubmit Event type
onsubmit is an event that occurs when you try to submit a form. You can put
your form validation against this event type.

Example
The following example shows how to use onsubmit. Here we are calling
a validate() function before submitting a form data to the webserver.
If validate() function returns true, the form will be submitted, otherwise it will
not submit the data.

Try the following example.


<html>

<head>

<script type="text/javascript">

<!--

function validation() {

all validation goes here

.........

return either true or false

//-->

</script>

</head>

<body>

<form method="POST" action="t.cgi" onsubmit="return validate()">

.......

<input type="submit" value="Submit" />

</form>

</body>
</html>

onmouseover and onmouseout

These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and the
onmouseout triggers when you move your mouse out from that element. Try the following
example.

<html>

<head>

<script type="text/javascript">

<!--

function over() {

document.write ("Mouse Over");

function out() {

document.write ("Mouse Out");

//-->

</script>
</head>

<body>

<p>Bring your mouse inside the division to see the result:</p>

<div onmouseover="over()" onmouseout="out()">

<h2> This is inside the division </h2>

</div>

</body>

</html>

You might also like