Sunteți pe pagina 1din 35

What is a Script?

A script is an executable list of commands like macro or batch file


created by a scripting language. Scripts (like PHP, Perl) which are
executed on a web server are called server-side scripts and scripts
(like JavaScript) which are executed on user's computer, interpreted
by the browser is called client-side scripts.

What is JavaScript?
JavaScript is a cross-platform, object-oriented scripting language
developed by Netscape. JavaScript was created by Netscape
programmer Brendan Eich.
It was first released under the name of LiveScript as part of
Netscape Navigator 2.0 in September 1995. It was renamed
JavaScript on December 4, 1995. As JavaScript works on the client
side, It is mostly used for client-side web development.
JavaScript is designed for use on web pages and closely integrated
with HTML. JavaScript can create applications which run in the
browsers such as IE, Opera, FireFox, Google Chrome and other.
Netscape submitted JavaScript to ECMA International for
standardization resulting in the standardized version named
ECMAScript.

JavaScript and Java


JavaScript and Java are similar in some ways but fundamentally
they are different. Java is a programming language developed by
Sun Microsystems, Inc. and JavaScript is a scripting language
developed by Netscape. Java is a server-side and static type
language. JavaScript is a client-side, dynamically typed language.
Java programs are compiled on the server and run on almost every
platform without distribution of source code whereas scripts
written in JavaScript are placed inside a HTML document and
interpreted by the browser. The syntax, reserved-words of
JavaScript and Java are also different.
JavaScript compares to Java

JavaScript Java

JavaScript is used for front-end web Java is used as a back-end language within a
development (for example field level validation web environment.
in a HTML form).

Interpreted (not compiled) by the client. Compiled byte codes downloaded from the
server, executed on the client.

Object-oriented. No distinction between types Class-based. Objects are divided into classes
of objects. Inheritance is through the prototype and instances with all inheritance through the
mechanism, and properties and methods can be class hierarchy. Classes and instances cannot
added to any object dynamically. have properties or methods added
dynamically.

Variable data types are not declared (loose Variable data types must be declared as Java
typing). maintains strong type checking.

Cannot automatically write to hard disk. Cannot automatically write to hard disk

Control the appearance of elements on our web page

Every web page is a collection of several individual elements which


are called objects like an image, a link etc.
JavaScript is capable of controlling the appearance of many objects.
For example, we can open new pages in customized windows where
we can specify their size, determine whether they have scroll bars
or not etc.

JavaScript responds user actions on our web pages


JavaScript can control objects on web pages in response to various
actions taken by the user which is called event. For example display
a dialog box when a user clicks on a button, opening a new page,
mouse over on a link to change the appearance of the link or control
the background color of your web pages.
Display various date time format
JavaScript has the ability to retrieve the date and time of your
computer's clock and it is enabled to display various formatting of
date-time through its internal date object.
Perform calculations
JavaScript can perform a wide variety of mathematical calculations.
It has a library of all the mathematical constants and functions
needed. These functions can be applied in different ways, for
example, an online financial transaction where JavaScript can be
used to calculate subtotal, total etc, or an online calculator or
creating games and interactive simulations with the advance math
functions such as sine and cosine.
Validate forms data
JavaScript can be used to validate form data including names,
addresses, URL, email addresses, phone numbers, zip codes etc. in
html forms before sending the data to a server. If you want to
validate the said data in server side you have to wait while the
information is sent up to the server for checking, using JavaScript
you can detect the error and prompt the user immediately.
Create Cookies
A cookie is a mechanism in a web browser where a simple text sent
to the visitors' computer. As it is a piece of text, cookies are not
executable. JavaScript can store information from this piece of text
on visitor's computer and reuse it automatically next time the user
visits the same page.
Detect the visitor's browser
Sometimes it is difficult to create pages that are displayed
identically on different browsers or even operating systems.
JavaScript can detect the visitor's browser and load the appropriate
page for that specific browser.
Dynamic HTML
Dynamic HTML, or DHTML, is a collection of technologies used
together to make interactive and animated website by using a
combination of JavaScript, HTML, DOM (Document object module)
and CSS

The HTML Document


An HTML document is made up of HTML elements, HTML element
attributes, comments, special characters, and doctype. If you like to
add presentational features to an HTML document you can attach
css to an HTML document, to add dynamic user experience (e.g.
popup, alert message, animations etc.) to an HTML document you
can add JavaScipt to your HTML document.
If javascript is disabled in the browser property, even though an
external script is attached or a script is written within
<script>...</script> tags in an HTML document, it becomes inactive.
Certain JavaScripts do not work with all the browsers and
sometimes a script works on and above (or vice a versa) a particular
version of a web browser.
The script Tag
The script is an HTML element. Html script element is used to
enclose client side scripts like JavaScript within an HTML
document.
Syntax
<script>
JavaScript statements.......
</script>

There are four types of attributes in script element:


1. language
The language attribute is used to specify the scripting language and
it's version for the enclosed code. In the following example,
JavaScript version is 1.2. If a specific browser does not support the
said JavaScript version, the code is ignored. If you do not specify a
language attribute, the default behavior depends on the browser
version. The language attribute is deprecated in HTML 4.01.
Example
<script language = "JavaScript1.2">
JavaScript statements.......
</script>
2. src
This attribute specifies the location of an external script. This
attribute is useful for sharing functions among many different
pages. Note that external JavaScript files contain only JavaScript
statements and files must have the extension .js.
Example
<script src = "common.js">
JavaScript statements.......
</script>
3. defer
If you set defer attribute, the browser delays the execution of the
script or it changes the order of the execution of the script. This can
improve the performance by delaying execution of scripts until the
content of body is read and displayed by the browser.
4. type
This attribute specifies the scripting language. The scripting
language is specified as a content type (e.g., "text/javascript" ). The
attribute is supported by all modern browser.
Example
<script type="text/javascript">
JavaScript statements.......
</script>
The noscript tag
If any browser does not support the JavaScript code the alternate
content placed within noscript tag is being executed.
Example
<noscript>
... code ....
</noscript>

JavaScript in HTML document


There are two general areas in HTML
document where JavaScript can be placed. First is
between <head>......</head> section, another is specific location
in <body>......</body> section. If you want to display a message
'Good Morning' (through the JavaScript alert command) at the time
of page loading then you must place the script at the
<head>......</head> section. In the following examples you will see
the different location of <script>.....</script> tags in a HTML
document.

Script in the Head Script in the Body


<!DOCTYPE html> <!DOCTYPE html>
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<title> Script in head section <title> Script in the Body </title>
</title> </head>
<script type = "text/javascript"> <body>
JavaScript statements....... <script type = "text/javascript">
</script> JavaScript statements.......
</head> </script>
<body> </body>
</body> </html>
</html>

Scripts in the Head and Body Two Scripts in the Body

<!DOCTYPE html> <!DOCTYPE html>


<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<title> Script in head and body <title> Two Scripts in the Body
section </title> </title>
<script type = "text/javascript"> </head>
JavaScript statements....... <body>
</script> <script type = "text/javascript"
</head> scr="jsexample.js" >
<body> </script>
<script type = "text/javascript"> <script type = "text/javascript">
JavaScript statements....... JavaScript statements.......
</script> </script>
</body> </body>
</html> </html>

Note: Optionally, if your script is not required to be executed before


the content of the body is displayed, and your script takes longer
time to load objects, you can place your script at the end of the
body element.
Double or Single Quotes in JavaScript
There is no preferred method, you can use either. If you use one
form of the quote (either single or double) in the string, you may use
other as the literal.

JavaScript Syntax
JavaScript syntax refers a set of rules which define how the
language is written and interpreted by the browser. Here are some
basic rules for JavaScript syntax:
JavaScript: Case sensitivity
JavaScript is case sensitive. Therefore when we write any
JavaScript word (for example "else") we must maintain the proper
case. As JavaScript is case sensitive , a variable name "empcode" is
not the same as "Empcode" or a function name "PayCalculation" is
not the same as "paycalculation".
Always remember everything within <script
type="text/javascript">and <script> tags (which are HTML tags) are
case sensitive.
Whitespace
In general, whitespace is not visible on the screen, including
spaces, tabs and newline characters. Whitespace enhances the
readability of the JavaScript code. If used with a string constant,
JavaScript considers it, but if not so, it ignores whitespace.
The following codes are equal.
HTML Code

<script language="JavaScript"> <script language="JavaScript">


empcode="emp123"; empcode = "emp123";
<script> <script>

The following codes are not equal.


HTML Code
<script language="JavaScript"> <script language="JavaScript">
empcode="emp123"; empcode = "emp 123";
<script> <script>

The Semi-Colon
In general, JavaScript does not require a semi-colon at the end of a
statement. If you write two statements in a single line then a semi-
colon is required at the end of the first statement. However,
experienced programmers prefer to use a semi-colon at the end of
each statement to make the code more readable and fix errors
easily.
The following codes are equal.
JS Code

alert("JavaScript Semi-Colon")
alert("JavaScript Semi-Colon")

JS Code

alert("JavaScript Semi-Colon");
alert("JavaScript Semi-Colon")
JavaScript Comments
Code written within comments are not processed by the interpreter.
Comments are good way to write notations to explain what a script
does. JavaScript supports the following two different ways of
commenting, single line comment and multiple line comments.
Single line comment
// This is a single line comment.
Example of single line comments
JS Code
// This is a single line comment

alert("We are learning JavaScript single line comment");

//alert("Good Morning.");

Multiple line comments

In JavaScript multi-line comments start with /* and end with */.

Example of multiple line comments


JS Code

/* Multiple line comments start here

alert("Good Morning");

Multiple line comments end here*/

alert("We are learning JavaScript multiple

line comments.");

Example of comments at the end of a line


JS Code

var empcode // declaring employee code

var empname // declaring employee name

alert("We are learning how to put

comments at the end of a line");

The Software tools

To create a JavaScript code for web applications you need a simple text editor.
For windows environment, you can use Windows NotePad and for Mac OS X, the
TextEdit application is usable. There are lots of good tools in the market for
developing a web-based application like Macromedia's Dreamweaver.

Initially, it will be best to write the code by hand in a simple text editor rather
than use advanced tools. An important factor to remember that Windows Notepad
saves files with an extension of .txt, if you do not mention another extension.
Therefore at the time of saving the HTML document files, we must mention .html
extension.

JavaScript Variables

In our school life, we learned about variables and equations in algebra. Let
assume a=30, b=12 and c= a-b, then c=18, i.e. variables like a, b, c store numbers.
In JavaScript and other programming language, a variable contain values (piece of
information) and stores in computer's memory which is changeable.

Valid identifier names

 The first character must be a UnicodeLetter, an underscore (_), dollar sign ($), or \

UnicodeEscapeSequence

 The rest of the name can be made up of starting character, UnicodeCombiningMark,

UnicodeDigit, UnicodeConnectorPunctuation, <ZWNJ>, <ZWJ>

 A variable name cannot contain space character.

 In JavaScript, variables are case sensitive, so emp_code is different from Emp_Code.

 We should not use the "reserve words" like alert, var as a variable name. See the list

ofReserve Words.

 JavaScript: Constants

 In JavaScript, constants are declared with const keyword and assigned at


the time of the declaration. A constant can be global or local to a function
where it is declared

 Constants are read-only, therefore you can not modify them later on.

 Naming a constant in JavaScript follow the same rule of naming a variable


except that the const keyword is always required, even for global
constants.

 If the keyword is omitted, the identifier is assumed to represent a variable.

JavaScript: Data Type

A value is a piece of information that can be a Number, String, Boolean, Null etc. JavaScript
recognizes the following types of values.

Types Description Example

String A series of characters enclosed in "google.com",


quotation marks. A string must be 'yahoo.com'
delimited by quotation marks of the
same type, either single quotation
marks ( ') or double quotation marks
(").

Numbers Any numeric value. The numbers can 45, 45887, -45,
be either positive or negative. 12.23, -145.55

Logical A logical true or false. Use to evaluate true, false


(Boolean) whether a condition is true or false.

null A special keyword denoting a null


value (i.e. empty value or nothing).
Since JavaScript is case-sensitive, null
is not the same as Null, NULL, or any
other variant.

undefined A top-level property whose value is


undefined, undefined is also a
primitive value.

JavaScript: Data Type Conversion

JavaScript is a dynamically typed language. Therefore there is no need to specify


the data type of a variable at the time of declaring it. Data types are converted
automatically as needed during script execution.

For example, we define the age of a person in the 'age' variable as follows :

var age = 21

Let store a string value to the said variable.

age = "What is your age?"

As JavaScript is dynamically typed, the said assignment does not create any
error.

JavaScript: Expressions

The following expressions contain string values, numeric values, and + operator.
JavaScript converts numeric values to strings.

x = "What is your age ?" + 21 // returns "What is your age ?21 "

y = 21 + " is my age. " // returns "21 is my age."

JavaScript alert - Dialog box

Description

alert() is a simple function to display a message to a dialog box (also called alert
box). Here is a simple example to display a text in the alert box.

HTML Code

JavaScript prompt - Dialog box

Description
The alert() method can not interact with the visitor. To interact with the user we
use prompt(), which asks the visitor to input some information and stores the
information in a variable.

JavaScript confirm - Dialog box

Description

Confirm() displays a dialog box with two buttons, OK and Cancel and a text as a
parameter. If the user clicks on OK button, confirm () returns true and on clicking
Cancel button, confirm() returns false.

Code:-

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>JavaScript confirm box example </title>
</head>
<body>
<h1 style="color: red">JavaScript confirm() box example</h1>
<hr />
<script type="text/javascript">
mess1='Press Ok to Continue.';
math=99;
x = confirm(mess1);
if (x == true)
{
alert("You have clicked on Ok Button.");
}
else
{
alert("You have clicked on Cancel Button."); }
</script>
</body>
</html>

JavaScript Operators

Arithmetic Operators : +, -, *, /

In JavaScript, arithmetic operators take numerical values (either literals or


variables) as their operands and return a single numerical value. There are four
standard arithmetic operators, addition (+), subtraction (-), multiplication (*), and
division (/).

These operators work as they do in other programming languages except the


division (/) operator which returns a floating-point division in JavaScript, not a
truncated division as it does in languages such as C or Java.
For example:
1/2 returns 0.5 in JavaScript.
1/2 returns 0 in Java.

In addition, JavaScript provides modules(%), increment(++), decrement(--) and


unary negation(-) operators.

Assignment Operators

An assignment operator assigns a value to its left operand based on the value of its right operand.
The first operand must be a variable and basic assignment operator is equal (=), which assigns the
value of its right operand to its left operand. That is, a = b assigns the value of b to a.

In addition to the regular assignment operator "=" the other assignment operators are shorthand for
standard operations, as shown in the following table.

Shorthand Expression Description

a +=b a=a+b Adds 2 numbers and assigns the result to the first.

a -= b a=a-b Subtracts 2 numbers and assigns the result to the first.

a *= b a = a*b Multiplies 2 numbers and assigns the result to the first.

a /=b a = a/b Divides 2 numbers and assigns the result to the first.

a %= b a = a%b Computes the modulus of 2 numbers and assigns the result to


the first.

a<<=b a = a<<b Performs a left shift and assigns the result to the first operand.

a>>=b a = a>>b Performs a sign-propagating right shift and assigns the result
to the first operand.

a>>>=b a = a>>>b Performs a zero-fill right shift and assigns the result to the first
operand.

a&= b a = a&b Performs a bitwise AND and assigns the result to the first
operand.

a^= b a = a^b Performs a bitwise XOR and assigns the result to the first
operand.

a |=b a = a|b Performs a bitwise OR and assigns the result to the first
operand.

Bitwise Operators

Bitwise operators perform an operation on the bitwise (0,1) representation of


their arguments, rather than as decimal, hexadecimal, or octal numbers. For
example, the decimal number eight has a binary representation of 1000. Bitwise
operators do their operations on such binary representation (for example 1000)
but they return standard JavaScript numerical values.

Here is a list of JavaScript's bitwise operators.

Operator Usage Description

Bitwise AND a&b Returns a one in each bit position if bits of both left and right
operands are ones.

Bitwise OR a|b Returns a one in each bit if bits of either left or right operand is
one.

Bitwise XOR a^b Returns a one in a bit position if bits of one but not both left and
right operand are one.

Bitwise NOT ~a Flips the bits of its operand.

Left shift a << b Shifts a in binary representation b bits to the left, shifting in zeros
from the right.

Sign- a >> b Shifts a in binary representation b bits to the right, discarding bits
propagating shifted off.
right shift

Zero-fill right a >>> b Shifts a in binary representation b bits to the right, discarding bits
shift shifted off, and shifting in zeros from the left.

Comparison Operators

Sometimes it is required to compare the value of one variable with other. The comparison operators
take simple values (numbers or string) as arguments and evaluate either true or false. Here is a list of
comparison operators.

Operator Comparisons Description

Equal (==) x == y Returns true if the operands are equal.

Strict equal x === y Returns true if the operands are equal and of the same
(===) type.

Not equal (!=) x != y Returns true if the operands are not equal.

Strict not equal x !== y Returns true if the operands are not equal and/or not of the
(!==) same type.

Greater than (>) x>y Returns true if the left operand is greater than the right
operand.

Greater than or x>=y Returns true if the left operand is greater than or equal to
equal (>=) the right operand.

Less than (<) x<y Returns true if the left operand is less than the right
operand.

Less than or x<=y Returns true if the left operand is less than or equal to the
equal (<=) right operand.

Pictorial presentation of Equal (==) operator

Pictorial presentation of Strict equal (===) operator


Test Strict equal (===) operator

The following web document returns false as the strict equal operator will
compare both value and type of x and y.

Pictorial presentation of Not equal(!=) operator

Test Not equal (!=) operator

The following web document returns false though the type of x and y are not equal
(the first one is integer type and the second one is character type) but their
values are equal.

Pictorial presentation of Strict not equal(!==) operator

Test Strict not equal (!==) operator

The following web document returns true though their values are equal but the
type of x and y are not equal (the first one is integer type and the second one is
character type).

Pictorial presentation of Greater than(>) operator


Test Greater than(>) operator

The following web document returns true as the value of x is greater than y.

Pictorial presentation of Greater than or equal (>=)

Test Greater than or equal (>=) operator

The following web document returns true as the value of x is equal to y.

Pictorial presentation of Less than (<) operator

Test Less than (<) operator

The following web document returns true as the value of x is less than y.
Pictorial presentation of Greater than or equal (>=)

Test Greater than or equal (>=) operator

The following web document returns true as the value of x is equal to y.


Logical Operators
The logical operators used in Javascript are listed below:

Operator Usage Description

Logical AND ( && ) a && b is true if both a and b are true.

Logical OR ( || ) a || b is true if either a or b is true.

Logical NOT ( ! ) !a is true if a is not true.

JavaScript Logical AND operator (&&)

The following conditions are true :


 true && true
 (20 > 5) && (5 < 20)
The following conditions are false :
 true && false
 (20 > 5) && (20 < 5)
 false && true
 (20 < 5) && (20 > 5)
 false && false
 (20 < 5) && (5 > 20)
JavaScript Logical OR operator (||)

The following conditions are true :


 true || true
 (20 > 5) || (5 < 20)
 true || false
 (20 > 5) || (20 < 5)
 false || true
 (20 < 5) || (20 > 5)
The following conditions are false :
 false || false
 (20 < 5) || (5 > 20)
String Concatenation

When working with JavaScript strings sometimes you need to join two or more
strings together into a single string. Joining multiple strings together is known as
concatenation.

The concatenation operator

The concatenation operator (+) concatenates two or more string values together
and return another string which is the union of the two operand strings.

The shorthand assignment operator += can also be used to concatenate strings.

?: (Conditional operator)

The conditional operator is used as a shortcut for standard if statement. It takes


three operands.

Syntax

Condition ? expr1: expr2

Parameters

condition : An expression that evaluates to true or false.

expr1, expr2 : Expressions with values of any types.

If the condition is true, the operator returns the value of expr1; otherwise, it
returns the value of expr2.

For example

status = (marks >= 30) ? "Pass" : "Fail"

The statement assigns value "Pass" to the variable status if marks are 30 or more.
Otherwise, it assigns the value of "Fail" to status.

JavaScript: Conditional Operator and If else statement

The conditional operator statement of the above example


status = (marks >= 30) ? "Pass" : "Fail" is equivalent to the following statement.

if marks>=30

document.write("Pass");

else

document.write("Fail");
The comma operator (,) is used to execute two expressions
sequentially.

Syntax

expr1, expr2
Parameters

expr1: Any expressions.

expr2: Any expressions.

We use the comma operator when we want to include multiple expressions in a


location that requires a single expression. This operator is generally used inside a
for loop, to allow multiple variables to be updated (increase/decrease) each time
through the loop.

For example, we want to display a serial No. (starting from 1) and an employee
code ( starting from 10 ), the following code uses the comma operator to
increment two variables at once.

for (var i=1, j=10; i <=10; i++, j++)

alert('Sl. No. : '+i+' Employee Code : '+j)

Delete Operator

The delete operator deletes an object, an object's property, or an element from an


array. The operator can also delete variables which are not declared with the var
statement

The function operator defines a function inside an expression.

Version

Implemented in JavaScript 1.5

Syntax

var1 = function( parameter1, parameter2,......parametern)


{
statement(s)
}
Parameters

parameters: A list of arguments to the function.

statement(s): JavaScript statements.

var a = 12;
var b = 14;
var x = function(a,b)
{
return a*a+2*a*b+b*b;
};
console.log("The square of "+a+ " and "+b +" is " +x(a,b));

The in operator is used to check whether a given property is available on an


object.
Syntax

property in object
Parameters

property: Name of the property.

object: Name of the object.

The instanceof operator is used to check the type of an object at run time. The
instanceof operator returns a boolean value that indicates if an object is an instance
of a particular class.
Syntax

var result = objectName instanceof objectType


Parameters

objectName: Name of the Object.

objectType: The type of the object.

The newoperator is used to create an instance of a user-defined


object type or one of builtin object types which have a constructor
function.

Syntax

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


Parameters

objectName: Name of the new object.

objectType: The type of the object.

param1, param2, ....paramN : Property values for the object.

To create a user-defined object type following steps are required.

 Write a function to define the object type

 Use new operator to create an instance of the object.

Example: Object type and object instance.


Suppose we want to create an object type for students with three properties
name, class, and rollno. To do this first declare the following function.

function student(name, class, rollno)

this.name = name;

this.class = class

this.rollno = rollno;

To create an object called studentvi declare the following statement.


studentvi = new student("David Rayy", "VI", 12)

The above statement creates an object called studentv and assigns it the
specified values for its properties. Therefore the value of studentv.name is the
string "David Rayy", studentv.class is the string "VI" and student.rollno is the
integer 12. You can create any number of student objects by calls to new.

Example: Object property that is itself another object.

To create the student object once again declare the said function once again

function student(name, class, rollno)

this.name = name;

this.class = class

this.rollno = rollno;

And then instantiate two new student objects as follows:

studentv = new student("John", "V", 10)

studentvi = new student("David Rayy", "VI", 12)

Now create an another object called school with school name, address, city,
sdetails where sdetails prperty takes a student object as follows.

function school(sname, city, sdetails )

this.sname = sname;

this.city = city;

this.sdetails = sdetails;

}
To instantiate the new objects, use the following statements :

school1 = new school("Dubai International School", "Dubai", studentv)

school2 = new school("New Delhi International School", "New Delhi", studentvi)

The above statement pass the objects studentv and studentvi as the parameters
for the school. To get the name of the student belongs to school2 youn access the
following property:

school2.sdetails.name

The this operator is used to refer the current object. In general, this
refers to the calling object in a method.

Syntax

this.propertyName
Parameter

propertyName: The name of the property.

The typeof operator is used to get the data type (returns a string)
of its operand. The operand can be either a literal or a data
structure such as a variable, a function, or an object. The operator
returns the data type.

Syntax

typeof operand
or
typeof (operand)
There are six possible values that typeof returns: object, boolean, function, number, string, and
undefined. The following table summarizes possible values returned by the typeof operator.

Type of the operand Result

Object "object"

boolean "boolean"

function "function"

number "number"

string "string"

undefined "undefined"
var index = 8;
var result = (typeof index === 'number');
alert(result);
// Output: true
var description = "w3resource";
var result = (typeof description === 'string');
alert(result);
// Output: true

The void
operator is used to evaluate a JavaScript expression
without returning a value.

Syntax

void (expression)
void expression

JavaScript Primitives
A primitive value is a value that has no properties or methods.

A primitive data type is data that has a primitive value.

JavaScript defines 5 types of primitive data types:

 string
 number

 boolean

 null

 undefined

Primitive values are immutable (they are hardcoded and therefore cannot be changed).

if x = 3.14, you can change the value of x. But you cannot change the value of 3.14.

Value Type Comment

"Hello" string "Hello" is always "Hello"

3.14 number 3.14 is always 3.14

true boolean true is always true


false boolean false is always false

null null (object) null is always null

undefined undefined undefined is always undefined

Objects are Variables Containing Variables


JavaScript variables can contain single values:

Example
var person = "John Doe";

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

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

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

A JavaScript object is a collection of named values

Object Properties
The named values, in JavaScript objects, are called properties.

Property Value

firstName John

lastName Doe

age 50

eyeColor blue
What are the conditional statements in Javascript?

In such cases, we need to use conditional statements that allow our program to
make correct decisions and perform right actions. JavaScript supports conditional
statements which are used to perform different actions based on different conditions.

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
Try the following example to understand how the if statement works.

<html>

<body>

<script type = "text/javascript">

<!--

var age = 20;

if( age > 18 ) {

document.write("<b>Qualifies for driving</b>");

//-->

</script>

<p>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
Try the following code to learn how to implement an if-else statement in
JavaScript.
<html>

<body>

<script type = "text/javascript">

<!--

var age = 15;

if( age > 18 ) {

document.write("<b>Qualifies for driving</b>");

} else {

document.write("<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 ifstatements, 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 elseblock is executed.

Example
Try the following code to learn how to implement an if-else-if statement
in JavaScript.
<html>

<body>

<script type = "text/javascript">

var book = "maths";

if( book == "history" ) {

document.write("<b>History Book</b>");

} else if( book == "maths" ) {


document.write("<b>Maths Book</b>");

} else if( book == "economics" ) {

document.write("<b>Economics Book</b>");

} else {

document.write("<b>Unknown Book</b>");

</script>

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

</body>

<html>

Switch Case
You can use multiple if...else…if statements, as in the previous chapter,
to perform a multiway branch. However, this is not always the best
solution, especially when all of the branches depend on the value of a
single variable.
Starting with JavaScript 1.2, you can use a switch statement which
handles exactly this situation, and it does so more efficiently than
repeated if...else if statements.

Flow Chart
The following flow chart explains a switch-case statement works.

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 caseagainst the value of the
expression until a match is found. If nothing matches,
a default condition will be used.

JavaScript Loops
Loops in JavaScript are used to execute the same block of code a
specified number of times or while a specified condition is true.
Very often when you write code, you want the same block of code to run
over and over again in a row. Instead of adding several almost equal lines in
a script we can use loops to perform a task like this.
In JavaScript there are two different kind of loops:
 for - loops through a block of code a specified number of times
 while - loops through a block of code while a specified condition is
true
The For Loop
The for loop is used when you know in advance how many times the
script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)

code to be executed
}
Example
Explanation: The example below defines a loop that starts with i=0.
The loop will continue to run as long as i is less than, or equal to 10. i will
increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <=
could be any comparing statement.
<html>

<body>

<script type="text/javascript">

var i=0

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

document.write("The number is " + i)


document.write("<br />")

</script>

</body>

</html>

Example 2
How to use the for loop to loop through the different HTML headers.
<html>

<body>

<script type="text/javascript">

for (i = 1; i <= 6; i++)

document.write("<h" + i + ">This is header " + i)

document.write("</h" + i + ">")

</script>

</body>

</html>

The While Loop


The while loop is used when you want the loop to execute and continue
executing while the specified condition is true.
while (var<=endvalue)

code to be executed

}
Note: The <= could be any comparing statement.
Example
Explanation: The example below defines a loop that starts with i=0.
The loop will continue to run as long as i is less than, or equal to 10. i will
increase by 1 each time the loop runs.
<html>

<body>

<script type="text/javascript">

var i=0

while (i<=10)

document.write("The number is " + i)


document.write("<br />")

i=i+1

</script>

</body>

</html>

Result
The number is 0

The number is 1

The number is 2 to The number is 10

The do...while Loop


The do...while loop is a variant of the while loop. This loop will always
execute a block of code ONCE, and then it will repeat the loop as long as the
specified condition is true. This loop will always be executed at least once,
even if the condition is false, because the code is executed before the
condition is tested.
do

code to be executed
}
while (var<=endvalue)
Example
<html>

<body>

<script type="text/javascript">

var i=0

do

document.write("The number is " + i)

document.write("<br />")

i=i+1

while (i<0)

</script>

</body>

</html>

Result
The number is 0

Break and Continue


There are two special statements that can be used inside loops: break
and continue.
Break
The break command will break the loop and continue executing the
code that follows after the loop (if any).

Example
<html>

<body>

<script type="text/javascript">

var i=0

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

if (i==3){break}

document.write("The number is " + i)

document.write("<br />")

</script>

</body>

</html>

Result
The number is 0

The number is 1

The number is 2

Continue
The continue command will break the current loop and continue with
the next value.
Example
<html>

<body>

<script type="text/javascript">

var i=0

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

if (i==3){continue}
document.write("The number is " + i)

document.write("<br />")

</script>

</body>

</html>

Result
The number is 0

The number is 1

The number is 2

The number is 4

The number is 5

The number is 6

The number is 7

The number is 8

The number is 9

The number is 10

For ... In
The for...in statement is used to loop (iterate) through the elements of
an array or through the properties of an object.
JavaScript For...In Statement
The for...in statement is used to loop (iterate) through the elements of
an array or through the properties of an object.
The code in the body of the for ... in loop is executed once for each
element/property.
Syntax
for (variable in object)

code to be executed
}
The variable argument can be a named variable, an array element, or a
property of an object.
Example
Using for...in to loop through an array:
<html>

<body>

<script type="text/javascript">

var x

var mycars = new Array()


mycars[0] = "Saab"

mycars[1] = "Volvo"

mycars[2] = "BMW"

for (x in mycars)

document.write(mycars[x] + "<br />")

</script>

</body>

</html>

JavaScript if...else Statement - Tutorialspoint

https://www.w3resource.com/javascript/operators/logical-operator.php

Read from and write to HTML document


https://www.w3resource.com/javascript/HTML-write-read/read-from-and-write-to-
HTML-document.php

Since JavaScript has become an integrated part of the Front End Development,
you must learn how to read from and write to an HTML document.

Before we go the actual coding, let us have a brief discussion on DOM - Document
Object Model, because that will help you to understand the topic better.
A brief note on DOM

Document Object Model is an interface that allows scripts and programs to


dynamically access and update content(e.g. text, image etc.), structure and style
of HTML, XHTML and XML documents. For this discussion, we will focus on HTML
documents only. Document Object model is a W3C recommendation.

Let's take a simple HTML page like following:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>A simple HTML document</title>
</head>
<body>
<h1>This is a simple HTML document</h1>
<p>w3resource web development tutorial</p>
</body>
</html>

Question 11)

Which method is used to convert a string to uppercase letters?


A) ToUpperCase()

B) toUppercase()

C) toUpperCase()

D) touppercase()
Question 12)

var x=’5′, y=10;


alert(+x+y);

What will be the


output?
A) 510

B) 5

C) 15

D) None of the above.

Question 14)
var x = “99”, y=”101″;
alert(x<+y); What will be the output?
A) five

B) four

C) three

D) six

E) true

) false

F) undefined

S-ar putea să vă placă și