UI Development -1 ICAT

Download as pdf or txt
Download as pdf or txt
You are on page 1of 179

UI Development - I

UNIT - I

INTRODUCTION TO SCRIPTING
Scripting is the action of writing scripts using a scripting language, distinguishing neatly
between programs, which are written in conventional programming language such as
C,C++,java, and scripts, which are written using a different kind of language.

We could reasonably argue that the use of scripting languages is just another kind of
programming. Scripting languages are used for is qualitatively different from conventional
programming languages like C++ and Ada address the problem of developing large
applications from the ground up, employing a team of professional programmers, starting
from well-defined specifications, and meeting specified performance constraints.

Scripting languages, on other hand, address different problems:


 Building applications from ‘off the shelf’ components
 Controlling applications that have a programmable interface
 Writing programs where speed of development is more important than run-time
efficiency.

The most important difference is that scripting languages incorporate features that enhance
the productivity of the user in one way or another, making them accessible to people who
would not normally describe themselves as programmers, their primary employment being in
some other capacity. Scripting languages make programmers of us all, to some extent.

What do scripting language names mean?


 Perl: Stands for Practical Extraction and Report Language
 Python: Named after the BBC show “Monty Python’s Flying Circus”
 Tcl: Stands for Tool Command Language
Web development is all about communication and data exchange. This communication takes
place via two parties over the HTTP protocol.
These parties are:
Server
The Server is responsible for serving the web pages depending on the client/end user
requirement. It can be either static or dynamic.
Client
A client is a party that requests pages from the server and displays them to the end user. In
general a client program is a web browser.

CLIENT SIDE SCRIPTING


The client is the system on which the Web browser is running. JavaScript is the main
client-side scripting language for the Web. Client-side scripts are interpreted by the browser.

The process with client-side scripting is:


 The user requests a Web page from the server
 The server finds the page and sends it to the user
 The page is displayed on the browser with any scripts running during or after display
So client-side scripting is used to make Web pages change after they arrive at the browser. It
is useful for making pages a bit more interesting and user-friendly. It can also provide useful
gadgets such as calculators, clocks etc. but on the whole is used for appearance and
interaction.
Client-side scripts rely on the user's computer. If that computer is slow they may run slowly.
They may not run at all if the browser does not understand the scripting language. As they
have to run on the user's system the code which makes up the script is there in the HTML for
the user to look at (and copy or change).

There are many client-side scripting languages too.


 JavaScript
 VBScript
 HTML (Structure)
 CSS (Designing)
 AJAX
 jQuery etc.
SERVER SIDE SCRIPTING
Server-side scripting is a method of designing websites so that the process or user request is
run on the originating server. Server-side scripts provide an interface to the user and are used
to limit access to proprietary data and help keep control of the script source code. Below is an
example of client-side scripts vs. server-side scripts.

Server-side scripting examples


Many languages may be used to create these scripts. They include but are not limited to the
examples below.

 ActiveVFP
 ASP
C
 DC
 Java
 JavaScript (using Server-side JavaScript (SSJS) e.g., node.js)
 Perl
 PHP
 Python
R
 Ruby

INTRODUCTION TO SCRIPTING LANGUAGES


Scripting languages are programming languages that are typically written using high-level
programming constructs, which makes them easy to learn. While there is no fixed definition
of what constitutes a scripting language, some of the common distinguishing traits of these
languages include:
 Interpreted: Scripting languages are typically converted into machine level code during
runtime by an interpreter, rather than being compiled into an executable before running.
While this leads to a performance hit as each line has to be interpreted on the fly, it
makes for easier portability between systems.
 Typeless: Variables can be used to hold any type of data without having to explicitly
declare their type. While this can make it easy to run into typecasting errors, it makes the
language easier to learn and can improve readability of the script.
 Native Complex Types: Most scripting languages also natively provide certain complex
data types like strings, arrays, lists and hashes.
 Garbage Collection: Most scripting languages automate garbage collection (freeing of
memory used by data). This can reduce the likelihood of memory leaks occurring.

Characteristics of scripting languages:


These are some properties of scripting languages which differentiate SL from programming
languages.
 Integrated compile and run: SL’s are usually characterized as interpreted languages,
but this is just an oversimplification. They operate on an immediate execution, without
need to issue separate commond to compile the program and then to run the resulting
object file, and without the need to link extensive libraries into he object code. This is
done automatically. A few SL’S are indeed implemented as strict interpreters.

Low overheads and ease of use:


 Variables can be declared by use
 The number of different data types is usually limited
 Everything is string by context it will be converted as number(vice versa)
 Number of data structures is limited(arrays)
 Enhanced functionality: SL’s usually have enhanced functionality in some areas.For
example ,most languages provide string manipulation based on the use of regular
expressions, while other languages provide easy access to low-level operating system
facilities,or to the API,or object exported by an application.
 Efficiency is not an issue: ease of use is achieved at the expense of effeciency, because
efficiency is not an issue in the applications for which SL’S are designed.
 A scripting language is usually interpreted from source code or bytecode. By contrast,
the software environment the scripts are written for is typically written in a compiled
language and distributed in machine code form.
 Scripting languages may be designed for use by end users of a program – end-user
development – or may be only for internal use by developers, so they can write portions
of the program in the scripting language.
 Scripting languages typically use abstraction, a form of information hiding, to spare users
the details of internal variable types, data storage, and memory management.
 Scripts are often created or modified by the person executing them, but they are also
often distributed, such as when large portions of games are written in a scripting
language.
 The characteristics of ease of use, particularly the lack of an explicit compile-link-load
sequence are sometimes taken as the sole definition of a scripting language.

What’s the difference between Scripting and Programming Languages?


Basically, all scripting languages are programming languages. The theoretical difference
between the two is that scripting languages do not require the compilation step and are rather
interpreted. For example, normally, a C program needs to be compiled before running
whereas normally, a scripting language like JavaScript or PHP need not be compiled.

Generally, compiled programs run faster than interpreted programs because they are first
converted native machine code. Also, compilers read and analyze the code only once, and
report the errors collectively that the code might have, but the interpreter will read and
analyze the code statements each time it meets them and halts at that very instance if there is
some error. In practice, the distinction between the two is getting blurred owing to improved
computation capabilities of the modern hardware and advanced coding practices.

Another point to be noted is that while classifying a language as scripting language or


programming language, the environment on which it would execute must be taken into
consideration. The reason why this is important is that we can design an interpreter for C
language and use it as a scripting language, and at the same time, we can design a compiler
for JavaScript and use it as a programming language. A live example of this is V8, the
JavaScript engine of Google Chrome, which compiles the JavaScript code into machine code,
rather than interpreting it.

Some scripting languages traditionally used without an explicit compilation step are
JavaScript, PHP, Python, VBScript.
Some programming languages traditionally used with an explicit compilation step are C,
C++.

Applications of Scripting Languages:


1. To automate certain tasks in a program
2. Extracting information from a data set
3. Less code intensive as compared to traditional programming languages

Applications of Programming Languages:


1. They typically run inside a parent program like scripts
2. More compatible while integrating code with mathematical models
3. Languages like JAVA can be compiled and then used on any platform

BASICS STRUCTURE OF A PROGRAM


 Literals
 Variables
 Camel Case
 Unicode
 Semicolons
 Indentation
 White Space
 Commenting
 Identifiers
 Case Sensitivity
 Reserved Words
 JavaScript Operators
 JavaScript Expressions
Above mentioned list are the basic things of the javascript.
JavaScript code must be inserted between <script> and </script> tags..
<script>
Your code is here
</script>
A JavaScript function is a block of JavaScript code, that can be executed when "called" for.
For example, a function can be called when an event occurs, like when the user clicks a
button.
JavaScript in <head> or <body>
You can place any number of scripts in an HTML document.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
External JavaScript
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:
<script src="myScript.js"></script>

External JavaScript Advantages


Placing scripts in external files has some advantages:
 It separates HTML and code
 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads

External References
External scripts can be referenced with a full URL or with a path relative to the current web
page.
This example uses a full URL to link to a script:
<script src="https://www.w3schools.com/js/myScript1.js"></script>

JAVASCRIPT DATA TYPES


JavaScript includes data types similar to other programming languages like Java or C#. Data
type indicates characteristics of data. It tells the compiler whether the data value is numeric,
alphabetic, date etc., so that it can perform the appropriate operation.
Primitive Data Types
1. String
2. Number
3. Boolean
4. Null
5. Undefined
Non-primitive Data Type
1. Object
2. Date
3. Array

JavaScript is a dynamic or loosely-typed language because a variable can hold value of any
data type at any point of time.

var myVar = 100;


myVar = true;
myVar = null;
myVar = undefined;
myVar = "Steve";
alert(myVar); // Steve

In the above example, myVar will hold last assigned value to it that is string "Steve".

JavaScript - String

String is a primitive data type in JavaScript. A string is textual content. It must be enclosed in
single or double quotation marks.

Example: String literal


"Hello World"
'Hello World'
String value can be assigned to a variable using equal to (=) operator.
Example: String literal assigned to a variable
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript String</h1>
<p id="p1"></p>
<p id="p2"></p>
<script>
var str1 = "Hello World";
var str2 = 'Hello World';
document.getElementById("p1").innerHTML = str1;
document.getElementById("p2").innerHTML = str2;
</script>
</body>
</html>

A string can also be treated like zero index based character array.

<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript String</h1>
<p id="p1"></p> <p id="p2"></p> <p id="p3"></p>
<p id="p4"></p> <p id="p5"></p> <p id="p6"></p>
<script>
var str = 'Hello World';
document.getElementById("p1").innerHTML = str[0];
document.getElementById("p2").innerHTML = str[1];
document.getElementById("p3").innerHTML = str[2];
document.getElementById("p4").innerHTML = str[3];
document.getElementById("p5").innerHTML = str[4];
document.getElementById("p6").innerHTML = str.length
</script>
</body>
</html>

Since, string is character index, it can be accessed using for loop and for-of loop.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript String</h1>
<p id="p1"></p> <p id="p2"></p>
<script>
var str = 'Hello World';
for(var i =0; i< str.length;i++)
document.getElementById("p1").innerHTML =
document.getElementById("p1").innerHTML + str[i];
for(var ch of str)
document.getElementById("p2").innerHTML =
document.getElementById("p2").innerHTML + ch;
</script>
</body>
</html>
Concatenation
A string is immutable in JavaScript, it can be concatenated using plus (+) operator in
JavaScript.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript String Concatenation</h1>
<p id="p1"></p>
<script>
var str = 'Hello ' + "World " + 'from ' + 'TutorialsTeacher';
document.getElementById("p1").innerHTML = str;
</script>
</body>
</html>

Include quotation marks inside string


Use quotation marks inside string value that does not match the quotation marks surrounding
the string value. For example, use single quotation marks if the whole string is enclosed with
double quotation marks and visa-versa.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: Quotes in String</h1>
<p id="p1"></p> <p id="p2"></p>
<script>
var str1 = "This is \"simple\" string";
var str2 = 'This is \'simple\' string';
document.getElementById("p1").innerHTML = str1;
document.getElementById("p2").innerHTML = str2;
</script>
</body>
</html>

JavaScript - Number
The Number is a primitive data type in JavaScript. Number type represents integer, float,
hexadecimal, octal or exponential value. First character in a Number type must be an integer
value and it must not be enclosed in quotation marks.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: Number in JavaScript</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var int = 100;
var float = 100.5;
var hex = 0xfff;
var exponential = 2.56e3;
var octal = 030;
document.getElementById("p1").innerHTML = int;
document.getElementById("p2").innerHTML = float;
document.getElementById("p3").innerHTML = hex;
document.getElementById("p4").innerHTML = exponential;
document.getElementById("p5").innerHTML = octal;
</script>
</body>
</html>
Number object
JavaScript also provides Number object which can be used with new keyword.
var hex = new Number(0xfff);

Caution: Be careful while working with the Number object because comparison of Number
objects using == operator compares Number objects and not the values. Consider the
following example.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: Number object comparison</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var num1 = new Number(100);
var num2 = new Number(100);
var num3 = 100;
document.getElementById("p1").innerHTML = num1 == num2;
document.getElementById("p2").innerHTML = num1 == num3;
document.getElementById("p3").innerHTML = num1 === num3;
document.getElementById("p4").innerHTML = typeof(num1);
document.getElementById("p5").innerHTML = typeof(num3);
</script>
</body>
</html>

Number Properties
The Number type includes some default properties. JavaScript treats primitive values as
object, so all the properties and methods are applicable to both primitive number values and
number objects.

The following table lists all the properties of Number type.

Property Description
MAX_VALUE Returns the maximum number value supported in JavaScript
MIN_VALUE Returns the smallest number value supported in JavaScript
NEGATIVE_INFIN
Returns negative infinity (-Infinity)
ITY
NaN Represents a value that is not a number.
POSITIVE_INFINI
Represents positive infinity (Infinity).
TY

<!DOCTYPE html>
<html>
<body>
<h1>Demo: Number object comparison</h1>

<script>
alert(' Max Value: ' + Number.MAX_VALUE +
'\n Min Value:' + Number.MIN_VALUE +
'\n Negative Infinity:' + Number.NEGATIVE_INFINITY +
'\n Positive Infinity:' + Number.POSITIVE_INFINITY +
'\n NaN:' + Number.NaN
);
</script>
</body>
</html>

Number Methods
The following table lists all the methods of Number type

JavaScript Boolean
Boolean is a primitive data type in JavaScript. Boolean can have only two values, true or
false. It is useful in controlling program flow using conditional statements like if..else, switch,
while, do..while.
<!DOCTYPE html>
<html> <body>
<h1>Demo: JavaScript Boolean</h1>
<script> var YES = true; var NO = false;
alert(YES); alert(NO);
</script>
</body> </html>
The following example demonstrates how a Boolean value controls the program flow using if
condition.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Boolean</h1>
<script>
var YES = true;
var NO = false;
if(YES)
{
alert("This code block will be executed");
}
if(NO)
{
alert("This code block will not be executed");
}
</script>
</body>
</html>

Example: Boolean

alert(1 > 2); // false


alert(10< 9); // false
alert(5 == 5); // true
Boolean object
JavaScript includes Boolean object to represent true or false. It can be initialized using new
keyword.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Boolean Object</h1>
<script>
var bool = new Boolean(true);
alert(bool); // true
</script>
</body>
</html>
Boolean Methods
Primitive or Boolean object includes following methods.
Method Description
Returns string of boolean value in local browser environment.
toLocaleString()
Example: var result = (1 > 2); result.toLocaleString(); // returns "false"
Returns a string of Boolean.
toString()
Example: var result = (1 > 2); result.toString(); // returns "false"
Returns the value of the Boolean object.
valueOf()
Example: var result = (1 > 2); result.valueOf(); // returns false

NULL AND UNDEFINED IN JAVASCRIPT


JavaScript includes two additional primitive type values - null and undefined, that can be
assigned to a variable that has special meaning.
null
You can assign null to a variable to denote that currently that variable does not have any
value but it will have later on. A null means absence of a value.
Eg:
var myVar = null;
alert(myVar); // null

In the above example, null is assigned to a variable myVar. It means we have defined a
variable but have not assigned any value yet, so value is absence.
If you try to find DOM element using document.getElelementByID for example, and if
element is found then it will return null. So it is recommended to check for null before doing
something with that element.

var saveButton = document.getElementById("save");


if (saveButton !== null)
saveButton.submit();

undefined
Undefined is also a primitive value in JavaScript. A variable or an object has an undefined
value when no value is assigned before using it. So you can say that undefined means lack of
value or unknown value.
var myVar;
alert(myVar); // undefined
In the above example, we have not assigned any value to a variable named 'myVar'. A
variable 'myVar' lacks a value. So it is undefined.

JavaScript Object
Object is a non-primitive data type in JavaScript. It is like any other variable, the only
difference is that an object holds multiple values in terms of properties and methods.
Properties can hold values of primitive data types and methods are functions.
In other programming languages like Java or C#, you need a class to create an object of it. In
JavaScript, an object is a standalone entity because there is no class in JavaScript.
However, you can achieve class like functionality using functions. We will learn how to treat
a function as a class in the advance JavaScript section.
Let's learn how to create an object in JavaScript.
In JavaScript, an object can be created in two ways:
Object literal
Object constructor

Object Literal
The object literal is a simple way of creating an object using { } brackets. You can include
key-value pair in { }, where key would be property or method name and value will be value
of property of any data type or a function. Use comma (,) to separate multiple key-value
pairs.
Syntax:
var <object-name> = { key1: value1, key2: value2,... keyN: valueN};

The following example creates an object using object literal syntax.


var emptyObject = {}; // object with no properties or methods
var person = { firstName: "John" }; // object with single property
// object with single methodvar message = {
showMessage: function (val) {
alert(val);
}
};
// object with properties & methodvar person = {
firstName: "James",
lastName: "Bond",
age: 15,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};
Only property or method name without value is not valid. The following syntax is invalid.

Access JavaScript Object Properties & Methods


<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Object</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var person = {
firstName: "James",
lastName: "Bond",
age: 25,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};
document.getElementById("p1").innerHTML = person.firstName;
document.getElementById("p2").innerHTML = person.lastName;
document.getElementById("p3").innerHTML = person["firstName"];
document.getElementById("p4").innerHTML = person["lastName"];
document.getElementById("p5").innerHTML = person.getFullName();
</script>
</body>
</html>

Object Constructor
The second way to create an object is with Object Constructor using new keyword. You can
attach properties and methods using dot notation. Optionally, you can also create properties
using [ ] brackets and specifying property name as string.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Object</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var person = new Object();
// Attach properties and methods to person object
person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};
// access properties & methods
document.getElementById("p1").innerHTML = person.firstName;
document.getElementById("p2").innerHTML = person.lastName;
document.getElementById("p3").innerHTML = person["firstName"];
document.getElementById("p4").innerHTML = person["lastName"];
document.getElementById("p5").innerHTML = person.getFullName();
</script>
</body>
</html>

Undefined Property or Method


JavaScript will return 'undefined' if you try to access properties or call methods that do not
exist.
If you are not sure whether an object has a particular property or not, then use
hasOwnProperty() method before accessing properties.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Object</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var person = new Object();
document.getElementById("p1").innerHTML = person.firstName;
if(person.hasOwnProperty("firstName")){
document.getElementById("p2").innerHTML=
person.firstName;
}
</script>
</body></html>

Access Object Keys.


Use for..in loop to get the list of all properties and methods of an object.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Object</h1>
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<script>
var person = new Object();
person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};
var i = 0;
for(var key in person){
document.getElementById("p" + i++).innerHTML = key;
};
</script>
</body>
</html>

JavaScript - Date

The Date object is a datatype built into the JavaScript language. Date objects are created with
the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods
simply allow you to get and set the year, month, day, hour, minute, second, and millisecond
fields of the object, using either local time or UTC (universal, or GMT) time.
The ECMAScript standard requires the Date object to be able to represent any date and time,
to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of
plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755.

Syntax
You can use any of the following syntaxes to create a Date object using Date() constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

Here is a description of the parameters −


 No Argument − With no arguments, the Date() constructor creates a Date object set
to the current date and time.
 milliseconds − When one numeric argument is passed, it is taken as the internal
numeric representation of the date in milliseconds, as returned by the getTime()
method. For example, passing the argument 5000 creates a date that represents five
seconds past midnight on 1/1/70.
 datestring − When one string argument is passed, it is a string representation of a
date, in the format accepted by the Date.parse() method.
 7 agruments − To use the last form of the constructor shown above. Here is a
description of each argument −
year − Integer value representing the year. For compatibility (in order to avoid
the Y2K problem), you should always specify the year in full; use 1998, rather
than 98.
month − Integer value representing the month, beginning with 0 for January to
11 for December.
date − Integer value representing the day of the month.
hour − Integer value representing the hour of the day (24-hour scale).
minute − Integer value representing the minute segment of a time reading.
second − Integer value representing the second segment of a time reading.
millisecond − Integer value representing the millisecond segment of a time
reading.

JavaScript Array
Objects allow you to store keyed collections of values. That’s fine.
But quite often we find that we need an ordered collection, where we have a 1st, a 2nd, a 3rd
element and so on.
For example, we need that to store a list of something: users, goods, HTML elements etc.
It is not convenient to use an object here, because it provides no methods to manage the order
of elements. We can’t insert a new property “between” the existing ones.
Objects are just not meant for such use.
There exists a special data structure named Array, to store ordered collections.

There are two syntaxes for creating an empty array:


let arr = new Array();let arr = [];

Almost all the time, the second syntax is used. We can supply initial elements in the brackets:
let fruits = ["Apple", "Orange", "Plum"];

Array elements are numbered, starting with zero.


We can get an element by its number in square brackets:
let fruits = ["Apple", "Orange", "Plum"];
alert( fruits[0] ); // Apple
alert( fruits[1] ); // Orange
alert( fruits[2] ); // Plum

We can replace an element:


fruits[2] = 'Pear'; // now ["Apple", "Orange", "Pear"]

…Or add a new one to the array:


fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"]

The total count of the elements in the array is its length:


let fruits = ["Apple", "Orange", "Plum"];
alert( fruits.length ); // 3

We can also use alert to show the whole array.


let fruits = ["Apple", "Orange", "Plum"];
alert( fruits ); // Apple,Orange,Plum
An array can store elements of any type.

For instance:
// mix of values
let arr = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ];
// get the object at index 1 and then show its name
alert( arr[1].name ); // John
// get the function at index 3 and run it
arr[3](); // hello

Methods pop/push, shift/unshift


A queue is one of the most common uses of an array. In computer science, this means an
ordered collection of elements which supports two operations:
 push appends an element to the end.
 shift get an element from the beginning, advancing the queue, so that the 2nd element
becomes the 1st.

Arrays support both operations.


In practice we need it very often. For example, a queue of messages that need to be shown
on-screen.
There’s another use case for arrays – the data structure named stack.
It supports two operations:
 push adds an element to the end.
 pop takes an element from the end.
So new elements are added or taken always from the “end”.
A stack is usually illustrated as a pack of cards: new cards are added to the top or taken from
the top:
For stacks, the latest pushed item is received first, that’s also called LIFO (Last-In-First-Out)
principle. For queues, we have FIFO (First-In-First-Out).
Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove
elements both to/from the beginning or the end.
In computer science the data structure that allows it is called deque.

Performance

Methods push/pop run fast, while shift/unshift are slow.

Why is it faster to work with the end of an array than with its beginning? Let’s see what
happens during the execution:

fruits.shift(); // take 1 element from the start

It’s not enough to take and remove the element with the number 0. Other elements need to be
renumbered as well.

The shift operation must do 3 things:

1. Remove the element with the index 0.


2. Move all elements to the left, renumber them from the index 1 to 0, from 2 to 1 and so
on.
3. Update the length property.
The more elements in the array, the more time to move them, more in-memory
operations.
The similar thing happens with unshift: to add an element to the beginning of the array, we
need first to move existing elements to the right, increasing their indexes.
And what’s with push/pop? They do not need to move anything. To extract an element from
the end, the pop method cleans the index and shortens length.

The actions for the pop operation:


fruits.pop(); // take 1 element from the end

JavaScript Array Methods

The Array object has many properties and methods which help developers to handle arrays
easily and efficiently. You can get the value of a property by specifying arrayname.property
and the output of a method by specifying arrayname.method().

1. length property --> If you want to know the number of elements in an array, you can
use the length property.
2. prototype property --> If you want to add new properties and methods, you can use
the prototype property.
3. reverse method --> You can reverse the order of items in an array using a reverse
method.
4. sort method --> You can sort the items in an array using sort method.
5. pop method --> You can remove the last item of an array using a pop method.
6. shift method --> You can remove the first item of an array using shift method.
7. push method --> You can add a value as the last item of the array.
JAVASCRIPT VARIABLE
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>
Note − Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of
any data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.

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. Take a look into the following
example.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script> </body></html>
Result:
Local
There are some rules while declaring a JavaScript variable
 Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
 After first letter we can use digits (0 to 9), for example value1.
 JavaScript variables are case sensitive, for example x and X are different variables.

JAVASCRIPT CONSTANT
Constants are block-scoped, much like variables defined using the let statement. The value of
a constant can't be changed through reassignment, and it can't be re-declared.
Global constants do not become properties of the window object, unlike var variables.
The const declaration creates a read-only reference to a value. It does not mean the value it
holds is immutable, just that the variable identifier cannot be reassigned.
For instance, in the case where the content is an object, this means the object's contents (e.g.,
its properties) can be altered.
A constant cannot share its name with a function or a variable in the same scope.

Syntax
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
nameN
The constant's name, which can be any legal identifier.
valueN
The constant's value; this can be any legal expression, including a
function expression.
Example
const number = 42;
try {
number = 99;
}
catch(err) {
console.log(err);
// expected output: TypeError: invalid assignment to const `number'
// Note - error messages will vary depending on browser
}
console.log(number);
// expected output: 42

POINTERS
No, JS doesn't have pointers.
Objects are passed around by passing a copy of a reference. The programmer cannot access
any C-like "value" representing the address of an object.
Within a function, one may change the contents of a passed object via that reference, but you
cannot modify the reference that the caller had because your reference is only a copy:
var foo = {'bar': 1};
function tryToMungeReference(obj) {
obj = {'bar': 2}; // won't change caller's object}
function mungeContents(obj) {
obj.bar = 2; // changes _contents_ of caller's object}

tryToMungeReference(foo);
foo.bar === 1; // true - foo still references original object

mungeContents(foo);
foo.bar === 2; // true - object referenced by foo has been modified

OPERATORS
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’
is called the operator. JavaScript supports the following types of operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators
JavaScript supports the following arithmetic operators
Assume variable A holds 10 and variable B holds 20, then

Sr.No. Operator & Description


+ (Addition)
1 Adds two operands
Ex: A + B will give 30
- (Subtraction)
2 Subtracts the second operand from the first
Ex: A - B will give -10
* (Multiplication)
3 Multiply both operands
Ex: A * B will give 200
/ (Division)
4 Divide the numerator by the denominator
Ex: B / A will give 2
% (Modulus)
5 Outputs the remainder of an integer division
Ex: B % A will give 0
++ (Increment)
6 Increases an integer value by one
Ex: A++ will give 11
-- (Decrement)
7 Decreases an integer value by one
Ex: A-- will give 9

Example
The following code shows how to use arithmetic operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";

document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);

b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and then try...
</body>
</html>
output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try…

Comparison Operators
JavaScript supports the following comparison operators

Sr.No. Operator & Description


= = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
1
becomes true.
Ex: (A == B) is not true.
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then
2
the condition becomes true.
Ex: (A != B) is true.
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if
3
yes, then the condition becomes true.
Ex: (A > B) is not true.
< (Less than)
Checks if the value of the left operand is less than the value of the right operand, if
4
yes, then the condition becomes true.
Ex: (A < B) is true.
>= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the right
5
operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
<= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right
6
operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

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


result = (a == b);
document.write(result);
document.write(linebreak);

document.write("(a < b) => ");


result = (a < b);
document.write(result);
document.write(linebreak);

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


result = (a > b);
document.write(result);
document.write(linebreak);

document.write("(a != b) => ");


result = (a != b);
document.write(result);
document.write(linebreak);

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


result = (a >= b);
document.write(result);
document.write(linebreak);

document.write("(a <= b) => ");


result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and different operators and then try...
</body></html>
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...

Logical Operators
JavaScript supports the following logical operators
Sr.No. Operator & Description
&& (Logical AND)
1 If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
|| (Logical OR)
2 If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
3
operator will make it false.
Ex: ! (A && B) is false.

Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";

document.write("(a && b) => ");


result = (a && b);
document.write(result);
document.write(linebreak);
document.write("(a || b) => ");
result = (a || b);
document.write(result);
document.write(linebreak);

document.write("!(a && b) => ");


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

Bitwise Operators
JavaScript supports the following bitwise operators
Sr.No. Operator & Description
& (Bitwise AND)
1 It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
| (BitWise OR)
2 It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer arguments.
3 Exclusive OR means that either operand one is true or operand two is true, but not
both.
Ex: (A ^ B) is 1.
~ (Bitwise Not)
4 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.
>> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the number of
6
bits specified by the right operand.
Ex: (A >> 1) is 1.
>>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left are
7
always zero.
Ex: (A >>> 1) is 1.

Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";

document.write("(a & b) => ");


result = (a & b);
document.write(result);
document.write(linebreak);

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


result = (a | b);
document.write(result);
document.write(linebreak);

document.write("(a ^ b) => ");


result = (a ^ b);
document.write(result);
document.write(linebreak);

document.write("(~b) => ");


result = (~b);
document.write(result);
document.write(linebreak);

document.write("(a << b) => ");


result = (a << b);
document.write(result);
document.write(linebreak);

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


result = (a >> b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body></html>
Output
a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...

Assignment Operators
JavaScript supports the following assignment operators
Sr.No. Operator & Description
= (Simple Assignment )
1 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
+= (Add and Assignment)
2 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
−= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left
3
operand.
Ex: C -= A is equivalent to C = C - A
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left
4
operand.
Ex: C *= A is equivalent to C = C * A
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left
5
operand.
Ex: C /= A is equivalent to C = C / A
%= (Modules and Assignment)
6 It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A

Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";

document.write("Value of a => (a = b) => ");


result = (a = b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a += b) => ");


result = (a += b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a -= b) => ");


result = (a -= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a *= b) => ");


result = (a *= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a /= b) => ");


result = (a /= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a %= b) => ");


result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body></html>
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...

Miscellaneous Operator
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
? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y

Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body></html>
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...

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"
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";

result = (typeof b == "string" ? "B is String" : "B is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);

result = (typeof a == "string" ? "A is String" : "A is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body></html>
Output
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...
Unary operators:
The unary operators require only one operand; they perform various operations such as
incrementing/decrementing a value by one, negating an expression, or inverting the value of a
boolean.
Operator Description
Unary plus operator; indicates positive value (numbers are positive without this,
+
however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean
Binary Opearators:
A binary operator is an operator that operates on two operands and manipulates them to
return a result. Operators are represented by special characters or by keywords and provide an
easy way to compare numerical values or character strings.
Binary operators are presented in the form:
Operand1 Operator Operand2
Some common binary operators in computing include:
 Equal (==)
 Not equal (!=)
 Less than (<)
 Greater than (>)
 Greater than or equal to (>=)
 Less than or equal to (<=)
 Logical AND (&&)
 Logical OR (||)
 Plus (+)
 Minus (-)
 Multiplication (*)
 Divide (/)

Tertiary Operators:
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a
condition followed by a question mark (?), then an expression to execute if the condition is
truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
This operator is frequently used as a shortcut for the if statement.
condition ? exprIfTrue : exprIfFalse

STATEMENTS
JavaScript supports a compact set of statements that you can use to incorporate a great deal of
interactivity in Web pages. This chapter provides an overview of these statements.
Use the semicolon (;) character to separate statements in JavaScript code.
Block Statement
A block statement is used to group statements. The block is delimited by a pair of curly
brackets:
{
statement_1;
statement_2;
.
.
.
statement_n;
}
Example
Block statements are commonly used with control flow statements (e.g. if, for, while).
while (x < 10){
x++;
}

Conditional Statements
A conditional statement is a set of commands that executes if a specified condition is true.
JavaScript supports two conditional statements: if...else and switch.

if…else Statement
Use the if statement to execute a statement if a logical condition is true. Use the optional else
clause to execute a statement if the condition is false. An if statement looks as follows:
if (condition)
statement_1
[else
statement_2]
condition can be any expression that evaluates to true or false. If condition evaluates to true,
statement_1 is executed; otherwise, statement_2 is executed. statement_1 and statement_2
can be any statement, including further nested if statements.
You may also compound the statements using else if to have multiple conditions tested in
sequence, as follows:
if (condition)
statement_1
[else if (condition_2)
statement_2]
...
[else if (condition_n_1)
statement_n_1]
[else
statement_n]

switch Statement
A switch statement allows a program to evaluate an expression and attempt to match the
expression’s value to a case label. If a match is found, the program executes the associated
statement. A switch statement looks as follows:
switch (expression) {
case label_1:
statements_1
[break;]
case label_2:
statements_2
[break;]
...
default:
statements_def
[break;]
}

The program first looks for a case clause with a label matching the value of expression and
then transfers control to that clause, executing the associated statements.
If no matching label is found, the program looks for the optional default clause, and if found,
transfers control to that clause, executing the associated statements.
If no default clause is found, the program continues execution at the statement following the
end of switch. By convention, the default clause is the last clause, but it does not need to be
so.
The optional break statement associated with each case clause ensures that the program
breaks out of switch once the matched statement is executed and continues execution at the
statement following switch.
If break is omitted, the program continues execution at the next statement in the switch
statement.

Example
In the following example, if fruittype evaluates to "Bananas", the program matches the value
with case “Bananas” and executes the associated statement.
When break is encountered, the program terminates switch and executes the statement
following switch.
If break were omitted, the statement for case “Cherries” would also be executed.
switch (fruittype) {
case "Oranges":
document.write("Oranges are $0.59 a pound.<br>");
break;
case "Apples":
document.write("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
document.write("Bananas are $0.48 a pound.<br>");
break;
case "Cherries":
document.write("Cherries are $3.00 a pound.<br>");
break;
case "Mangoes":
case "Papayas":
document.write("Mangoes and papayas are $2.79 a pound.<br>");
break;
default:
document.write("Sorry, we are out of " + fruittype + ".<br>");
}
document.write("Is there anything else you'd like?<br>");
Control Statements

Loop Statements
A loop is a set of commands that executes repeatedly until a specified condition is met.
JavaScript supports the for, do while, and while loop statements, as well as label (label is not
itself a looping statement, but is frequently used with these statements).
In addition, you can use the break and continue statements within loop statements.
Another statement, for...in, executes statements repeatedly but is used for object
manipulation.
The loop statements are:
 for Statement
 do…while Statement
 while Statement
 label Statement
 break Statement
 continue Statement

for Statement
A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is
similar to the Java and C for loop. A for statement looks as follows:
for ([initialExpression]; [condition]; [incrementExpression])
statement
When a for loop executes, the following occurs:
1. The initializing expression initialExpression, if any, is executed. This expression
usually initializes one or more loop counters, but the syntax allows an expression of
any degree of complexity. This expression can also declare variables.
2. The condition expression is evaluated. If the value of condition is true, the loop
statements execute. If the value of condition is false, the for loop terminates. If the
condition expression is omitted entirely, the condition is assumed to be true.
3. The statement executes. To execute multiple statements, use a block statement ({ ... })
to group those statements.
4. The update expression incrementExpression, if there is one, executes, and control
returns to step 2.

do…while Statement
The do...while statement repeats until a specified condition evaluates to false. A do...while
statement looks as follows:
do
statement
while (condition);
statement executes once before the condition is checked. To execute multiple statements, use
a block statement ({ ... }) to group those statements. If condition is true, the statement
executes again. At the end of every execution, the condition is checked. When the condition
is false, execution stops and control passes to the statement following do...while.
while Statement
A while statement executes its statements as long as a specified condition evaluates to true. A
while statement looks as follows:
while (condition)
statement
If the condition becomes false, statement within the loop stops executing and control passes
to the statement following the loop.
The condition test occurs before statement in the loop are executed. If the condition returns
true, statement is executed and the condition is tested again.
If the condition returns false, execution stops and control is passed to the statement following
while.
To execute multiple statements, use a block statement ({ … }) to group those statements.

label Statement
A label provides a statement with an identifier that lets you refer to it elsewhere in your
program. For example, you can use a label to identify a loop, and then use the break or
continue statements to indicate whether a program should interrupt the loop or continue its
execution.
The syntax of the label statement looks like the following:
label :
statement

break Statement
Use the break statement to terminate a loop, switch, or in conjunction with a label statement.
 When you use break without a label, it terminates the innermost enclosing while,
do-while, for, or switch immediately and transfers control to the following statement.
 When you use break with a label, it terminates the specified labeled statement.

The syntax of the break statement looks like this:


1. break;
2. break label;
The first form of the syntax terminates the innermost enclosing loop or switch; the second
form of the syntax terminates the specified enclosing label statement.

continue Statement
The continue statement can be used to restart a while, do-while, for, or label statement.
 When you use continue without a label, it terminates the current iteration of the
innermost enclosing while, do-while or for statement and continues execution of the
loop with the next iteration. In contrast to the break statement, continue does not
terminate the execution of the loop entirely. In a while loop, it jumps back to the
condition. In a for loop, it jumps to the increment-expression.
 When you use continue with a label, it applies to the looping statement identified with
that label.
The syntax of the continue statement looks like the following:
1. continue
2. continue label
ARRAYS & STRINGS
The Array object lets you store multiple values in a single variable. It stores a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables of the same
type.
Syntax
Use the following syntax to create an Array object
var fruits = new Array( "apple", "orange", "mango" );

The Array parameter is a list of strings or integers. When you specify a single numeric
parameter with the Array constructor, you specify the initial length of the array. The
maximum length allowed for an array is 4,294,967,295.
You can create array by simply assigning values as follows
var fruits = [ "apple", "orange", "mango" ];

Array Properties
Sr.No. Property & Description
constructor
1
Returns a reference to the array function that created the object.
index
2
The property represents the zero-based index of the match in the string
input
3
This property is only present in arrays created by regular expression matches.
length
4
Reflects the number of elements in an array.
prototype
5
The prototype property allows you to add properties and methods to an object.

Array Methods
Sr.No. Method & Description
concat()
1
Returns a new array comprised of this array joined with other array(s) and/or value(s).
every()
2
Returns true if every element in this array satisfies the provided testing function.
filter()
3 Creates a new array with all of the elements of this array for which the provided
filtering function returns true.
forEach()
4
Calls a function for each element in the array.
indexOf()
5 Returns the first (least) index of an element within the array equal to the specified
value, or -1 if none is found.
join()
6
Joins all elements of an array into a string.
lastIndexOf()
7 Returns the last (greatest) index of an element within the array equal to the specified
value, or -1 if none is found.
map()
8 Creates a new array with the results of calling a provided function on every element in
this array.
pop()
9
Removes the last element from an array and returns that element.
push()
10 Adds one or more elements to the end of an array and returns the new length of the
array.
reduce()
11 Apply a function simultaneously against two values of the array (from left-to-right) as
to reduce it to a single value.
reduceRight()
12 Apply a function simultaneously against two values of the array (from right-to-left) as
to reduce it to a single value.
reverse()
13 Reverses the order of the elements of an array -- the first becomes the last, and the last
becomes the first.
shift()
14
Removes the first element from an array and returns that element.
slice()
15
Extracts a section of an array and returns a new array.
some()
16
Returns true if at least one element in this array satisfies the provided testing function.
toSource()
17
Represents the source code of an object
sort()
18
Sorts the elements of an array
splice()
19
Adds and/or removes elements from an array.
toString()
20
Returns a string representing the array and its elements.
unshift()
21 Adds one or more elements to the front of an array and returns the new length of the
array.
String

The String object lets you work with a series of characters; it wraps Javascript's string
primitive data type with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects, you can
call any of the helper methods of the String object on a string primitive.

Syntax
Use the following syntax to create a String object
var val = new String(string);
The String parameter is a series of characters that has been properly encoded.

String Properties
Sr.No. Property & Description
constructor
1
Returns a reference to the String function that created the object.
length
2
Returns the length of the string.
prototype
3
The prototype property allows you to add properties and methods to an object.

String Methods
r.No. Method & Description
charAt()
1
Returns the character at the specified index.
charCodeAt()
2
Returns a number indicating the Unicode value of the character at the given index.
concat()
3
Combines the text of two strings and returns a new string.
indexOf()
4 Returns the index within the calling String object of the first occurrence of the specified
value, or -1 if not found.
lastIndexOf()
5 Returns the index within the calling String object of the last occurrence of the specified
value, or -1 if not found.
localeCompare()
6 Returns a number indicating whether a reference string comes before or after or is the
same as the given string in sort order.
match()
7
Used to match a regular expression against a string.
replace()
8
Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
search()
9
Executes the search for a match between a regular expression and a specified string.
slice()
10
Extracts a section of a string and returns a new string.
split()
11
Splits a String object into an array of strings by separating the string into substrings.
substr()
12 Returns the characters in a string beginning at the specified location through the
specified number of characters.
substring()
13
Returns the characters in a string between two indexes into the string.
toLocaleLowerCase()
14 The characters within a string are converted to lower case while respecting the current
locale.
toLocaleUpperCase()
15 The characters within a string are converted to upper case while respecting the current
locale.
toLowerCase()
16
Returns the calling string value converted to lower case.
toString()
17
Returns a string representing the specified object.
toUpperCase()
18
Returns the calling string value converted to uppercase.
valueOf()
19
Returns the primitive value of the specified object.

FUNCTIONS

What is a Function?
A function is a subprogram designed to perform a particular task.
Functions are executed when they are called. This is known as invoking a function.
Values can be passed into functions and used within the function.
Functions always return a value. In JavaScript, if no return value is specified, the function
will return undefined.

Define a Function.
There are a few different ways to define a function in JavaScript:
A Function Declaration defines a named function. To create a function declaration you use
the function keyword followed by the name of the function. When using function
declarations, the function definition is hoisted, thus allowing the function to be used before it
is defined.
function name(parameters){
statements
}

A Function Expressions defines a named or anonymous function. An anonymous function is


a function that has no name. Function Expressions are not hoisted, and therefore cannot be
used before they are defined. In the example below, we are setting the anonymous function
object equal to a variable.

let name = function(parameters){


statements
}

An Arrow Function Expression is a shorter syntax for writing function expressions. Arrow
functions do not create their own this value.

let name = (parameters) => {


statements
}

Parameters vs. Arguments.


If you’re new to JavaScript, you may have heard the terms parameters and arguments used
interchangeably. While very similar, there is an important distinction to make between these
two keywords.
Parameters are used when defining a function, they are the names created in the function
definition. In fact, during a function definition, we can pass in up to 255 parameters!
Parameters are separated by commas in the (). Here’s an example with two parameters —
param1 & param2:

const param1 = true;


const param2 = false;function twoParams(param1, param2){
console.log(param1, param2);
}

Arguments, on the other hand, are the values the function receives from each parameter when
the function is executed (invoked). In the above example, our two arguments are true & false.
Invoking a Function.
Functions execute when the function is called. This process is known as invocation. You can
invoke a function by referencing the function name, followed by an open and closed
parenthesis: ().

Lets explore an example.


If you’re using Google Chrome, open up your dev console so you can code along with these
examples: [WINDOWS]: Ctrl + Shift + J [MAC]: Cmd + Opt + J
First, we’ll define a function named logIt. This function will take one parameter, name. When
executed, the function will log that name back to the console:
function logIt(name){
console.log(name);
}

To invoke our function, we call it, while passing in the singular parameter. Here I am calling
this function with the name Joe:
logIt('Joe');
// Joe
If your function has no parameters, you can invoke it with an empty set of parenthesis:

function logIt2(){
console.log('The second one');
}logIt2();
// The second one

Function Return.
Every function in JavaScript returns undefined unless otherwise specified.
Let’s test this by creating and invoking an empty function:

function test(){};test();
// undefined

Awesome, as expected, undefined is returned.


Now, we can customize what is returned in our function by using the return keyword
followed by our return value. Take a look at the code below:
function test(){
return true;
};test();
// true
In this example we explicitly tell the function to return true. When we invoke the function,
that’s exactly what happens.
But why is this important?
It’s important because the value that a function returns, is actually returned to the caller of the
function. Take a look at this code:
let double = function(num) {
return num * 2;
}
This is a function expression that creates a function that will return two times the value of our
input parameter num. We can then invoke the function and save the return value to a variable:
let test = double(3);
When we log out our test value, we get 6:
console.log(test);
// 6
Awesome! The return variable not only returns values from a function, but it assigns them to
whatever called the function!
Another important rule of the return statement is that it stops function execution immediately.
Consider this example where we have two return statements in our test function:
function test(){
return true;
return false;
};test();
// true
The first return statement immediately stops execution of our function and causes our
function to return true. The code on line three: return false; is never executed.
Function Objects.
Functions are function objects. In JavaScript, anything that is not a primitive type ( undefined,
null,boolean, number, or string) is an object. Objects in JavaScript are extremely versatile.
Because of this, we can even pass a function as a parameter into another function.
When a function accepts another function as a parameter, or returns a function, it is called a
higher-order function. You’ve probably already used a bunch of higher order functions and
don’t even know it: Array.prototype.mapand Array.prototype.filter are higher order functions
(Just to name a couple). You can check out some of my previous articles to learn more about
objects and higher order functions in JavaScript…

Pass by Value - Pass by Reference

Pass by Value:
In Pass by Value, Function is called by directly passing the value of the variable as the
argument. Changing the argument inside the function doesn’t affect the variable passed from
outside the function.

Javascript always pass by value so changing the value of the variable never changes the
underlying primitive (String or number).
function callByValue(varOne, varTwo) {
console.log("Inside Call by Value Method");
varOne = 100;
varTwo = 200;
console.log("varOne =" + varOne +"varTwo =" +varTwo);
} let varOne = 10;
let varTwo = 20; console.log("Before Call by Value Method");
console.log("varOne =" + varOne +"varTwo =" +varTwo); callByValue(varOne,
varTwo) console.log("After Call by Value Method");
console.log("varOne =" + varOne +"varTwo =" +varTwo);
output will be :
---------------
Before Call by Value Method
varOne =10 varTwo =20
Inside Call by Value Method
varOne =100 varTwo =200
After Call by Value Method
varOne =10 varTwo =20
However, when a variable refers to an object which includes array, the value is the reference
to the object.

Pass by Reference:
In Pass by Reference, Function is called by directly passing the reference/address of the
variable as the argument. Changing the argument inside the function affect the variable
passed from outside the function. In Javascript objects and arrays follows pass by reference.
function callByReference(varObj) {
console.log("Inside Call by Reference Method");
varObj.a = 100;
console.log(varObj);
}
let varObj = {a:1};console.log("Before Call by Reference Method");
console.log(varObj);callByReference(varObj) console.log("After Call by Reference
Method");
console.log(varObj);output will be :
--------------- Before Call by Reference Method
{a: 1}
Inside Call by Reference Method
{a: 100}
After Call by Reference Method
{a: 100}
so if we are passing object or array as an argument to the method, then there is a possibility
that value of the object can change.

Call by Value - Call by Reference


Call by Value in JavaScript
The concept of Call by Value is , when we want to pass any parameter as a function argument
then there are two types of arguments. An argument that is passed when the function is called
is called an Actual Argument and the argument that takes the value in the caller's function is
called a Formal Argument. Here is a sample example.
//Here name is formal argument
Function testFunction(name ){
}
//the string(Sourav) is actual parameter.
testFunction('Sourav');
Now, we will implement the same concept in a real application.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<script>
function testFun(name) {
name = name + 'Kayal';
console.log("Modified name:- " + name);
}
var name = 'Sourav'
testFun(name);
console.log("Old Name:- " + name);
</script>
</body>
</html>

Within the function we are modifying the Formal Argument value and then outside of the
function we are printing the value of the old variable and we are seeing that the value within
the function has been changed though it is not reflected outside of the function.
The reason is, when are sending data to the function the new copy of the same variable is
being created within the calling function and the modification is happening to this local
variable, it's not effecting the original variable. This is the example of Call by Value in
JavaScript.

Call by Reference in JavaScript


Now, in this section we will understand the concept of "Call by Reference". The theory is,
when we want to implement a Call by Reference, we need to send the reference of the object.
In C and C++ we use the address of ("&") operator and in C# 'ref' to send the address of a
variable. In JavaScript the situation is a little different. We need to send the actual object as a
function argument to send the reference of an object. Try to understand the following code.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<script>
function testFun(person) {
person.name = 'Ajay';
person.surname = 'Joshi';
}
var person = {
name: 'Sourav',
surname:'Kayal'
};
testFun(person);
console.log("Name:- " + person.name);
console.log("Surname:- " + person.surname);
</script>
</body>
</html>
Here is another code for sending an object, basically both are the same and the object
creation part is a little different.
<script>
function testFun(person) {
person.name = 'Ajay';
person.surname = 'Joshi';
}
var person = new Object();
person.name = 'Sourav';
person.surname='Kayal'
testFun(person);
console.log("Name:- " + person.name);
console.log("Surname:- " + person.surname);
</script>
In both case the output is the same.

In this example we are sending a "person" object as a function argument and within the
function we are modifying a value (read property) of the object and we are seeing that that
actual object is affected. So, in an actual scenario, we are not sending a copy of an object,
we are sending an actual object as its reference.

Overloading
JavaScript does not support Function Overloading. The following shows function
overloading −
function funcONE(x,y) {
return x*y;}function funcONE(z) {
return z;}
The above will not show an error, but you won't get desired results. On calling,
// prints 5
funcONE(5);
// prints 5, not 30
funcONE(5,6);
JavaScript does not support function overloading natively. If we will add functions with the
same name and different arguments, it considers the last defined function.

Overriding
The JavaScript supports overriding, not overloading. When you define multiple functions
which have the same name, the last one defined will override all the previously defined ones
and every time when you invoke a function, the last defined one will get executed. The
following example overrides the user-defined function.
JavaScript Demo - Overriding user-defined function
<script type="text/javascript">
function multiplyNum(x, y, z) {
return x * y * z;
}

function multiplyNum(x, y) {
return x * y;
}
var result = multiplyNum(1, 2, 3);
document.write(result);
Output
2

Looking at the above example, the value of multiplication will be equal to 2 instead of 6.
In this case, the only function available is multiplyNum(x, y). So if we think we are making a
call to multiplyNum(x, y, z), it's actually calling multiplyNum(x, y). The remaining
parameter(s) will be ignored.

We can also override Javascript built-in functions. The following example overrides the
built-in JavaScript alert() function.

JavaScript Demo - Overriding built-in function


<script type="text/javascript">
var alert = function(message) {
document.write(message);
}
// The following calls will invoke the overridden alert() function
alert("Learn ");
alert("JavaScript");
</script>
Output

Learn JavaScript

By default, alert() function displays the message in the alert box. But here we have
overridden it. Now it is displaying the message in the document.

Recursive
Recursive function is a technique for iterating over an operation by having a function call
itself repeatedly until it arrives at a result. Most loops can be rewritten in a recursive style,
and in some functional languages this approach to looping is the default.
The three key features of recursion
All recursive functions should have three key features:
A Termination Condition
Simply put: if(something bad happened){ STOP }; The Termination Condition is our
recursion fail-safe. Think of it like your emergency brake. It’s put there in case of bad input
to prevent the recursion from ever running.
In our factorial example, if (x < 0) return; is our termination condition. It’s not possible to
factorial a negative number and thus, we don’t even want to run our recursion if a negative
number is input.

A Base Case
Simply put: if(this happens) { Yay! We're done }; The Base Case is similar to our termination
condition in that it also stops our recursion.
But remember, the termination condition is a catch-all for bad data. Whereas the base case is
the goal of our recursive function. Base cases are usually within an if statement.
In the factorial example, if (x === 0) return 1; is our base case. We know that once we’ve
gotten x down to zero, we’ve succeeded in determining our factorial!

The Recursion
Simply put: Our function calling itself. In the factorial example, return x * factorial(x — 1);
is where the recursion actually happens. We’re returning the value of the number x multiplied
by the value of whatever factorial(x-1) evaluates to.
function factorial(x) {

// TERMINATION
if (x < 0) return;
// BASE
if (x === 0) return 1;
// RECURSION
return x * factorial(x - 1);
}factorial(3);
// 6
Factorial Function Flow
Lets examine exactly what happens when we call our Factorial Function:
1. We first call our function passing in the value of 3.
factorial(3);
2. This results in the function being run. Both if statements fail and our recursion line runs.
We return the integer 3 multiplied by the value of factorial(3-1).
return 3 * factorial(2);
3. When factorial(2) is run, both if statements fail again and recursion occurs. We return the
integer 2 multiplied by the value of factorial(2-1).
return 2 * factorial(1);
4. When factorial(1) is run, both if statements fail again and recursion occurs. We return the
integer 1 multiplied by the value of factorial(1-1).
return 1 * factorial(0);
5. When factorial(0) is run, something different happens. Zero is our base case, so that if
statement passes and our function returns 1.
if (x === 0)
return 1;
DERIVED DATA TYPES
Array
Objects allow you to store keyed collections of values. That’s fine.
But quite often we find that we need an ordered collection, where we have a 1st, a 2nd, a 3rd
element and so on.
For example, we need that to store a list of something: users, goods, HTML elements etc.
It is not convenient to use an object here, because it provides no methods to manage the order
of elements. We can’t insert a new property “between” the existing ones.
Objects are just not meant for such use.
There exists a special data structure named Array, to store ordered collections.

There are two syntaxes for creating an empty array:


let arr = new Array();let arr = [];

Almost all the time, the second syntax is used. We can supply initial elements in the brackets:
let fruits = ["Apple", "Orange", "Plum"];

Array elements are numbered, starting with zero.


We can get an element by its number in square brackets:
let fruits = ["Apple", "Orange", "Plum"];
alert( fruits[0] ); // Apple
alert( fruits[1] ); // Orange
alert( fruits[2] ); // Plum

We can replace an element:


fruits[2] = 'Pear'; // now ["Apple", "Orange", "Pear"]

…Or add a new one to the array:


fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"]

The total count of the elements in the array is its length:


let fruits = ["Apple", "Orange", "Plum"];
alert( fruits.length ); // 3

We can also use alert to show the whole array.


let fruits = ["Apple", "Orange", "Plum"];
alert( fruits ); // Apple,Orange,Plum
An array can store elements of any type.
For instance:
// mix of values
let arr = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ];
// get the object at index 1 and then show its name
alert( arr[1].name ); // John
// get the function at index 3 and run it
arr[3](); // hello

Methods pop/push, shift/unshift


A queue is one of the most common uses of an array. In computer science, this means an
ordered collection of elements which supports two operations:
 push appends an element to the end.
 shift get an element from the beginning, advancing the queue, so that the 2nd element
becomes the 1st.

Arrays support both operations.


In practice we need it very often. For example, a queue of messages that need to be shown
on-screen.
There’s another use case for arrays – the data structure named stack.
It supports two operations:
 push adds an element to the end.
 pop takes an element from the end.
So new elements are added or taken always from the “end”.
A stack is usually illustrated as a pack of cards: new cards are added to the top or taken from
the top:

For stacks, the latest pushed item is received first, that’s also called LIFO (Last-In-First-Out)
principle. For queues, we have FIFO (First-In-First-Out).
Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove
elements both to/from the beginning or the end.
In computer science the data structure that allows it is called deque.
Performance

Methods push/pop run fast, while shift/unshift are slow.

Why is it faster to work with the end of an array than with its beginning? Let’s see what
happens during the execution:

fruits.shift(); // take 1 element from the start

It’s not enough to take and remove the element with the number 0. Other elements need to be
renumbered as well.

The shift operation must do 3 things:

Remove the element with the index 0.

Move all elements to the left, renumber them from the index 1 to 0, from 2 to 1 and so on.

Update the length property.

The more elements in the array, the more time to move them, more in-memory
operations.
The similar thing happens with unshift: to add an element to the beginning of the array, we
need first to move existing elements to the right, increasing their indexes.
And what’s with push/pop? They do not need to move anything. To extract an element from
the end, the pop method cleans the index and shortens length.
The actions for the pop operation:
fruits.pop(); // take 1 element from the end

JavaScript Array Methods

The Array object has many properties and methods which help developers to handle arrays
easily and efficiently. You can get the value of a property by specifying arrayname.property
and the output of a method by specifying arrayname.method().

 length property --> If you want to know the number of elements in an array, you can
use the length property.
 prototype property --> If you want to add new properties and methods, you can use the
prototype property.
 reverse method --> You can reverse the order of items in an array using a reverse
method.
 sort method --> You can sort the items in an array using sort method.
 pop method --> You can remove the last item of an array using a pop method.
 shift method --> You can remove the first item of an array using shift method.
 push method --> You can add a value as the last item of the array.

USER DEFINED DATA TYPES

Union
Union is a collection of variables of different data types, in case of union information can
only be stored In one field at any one time.
A unionis a special data type available in C that enables you to store different data types in
the same memory location. You can define a union with many members, but only one
member can contain a value at any given time.
Unions provide an efficient way of using the same memory location for multi-purpose.
Declaring Union
union union-name {
data_type var-name;
data_type var-name;
};
The union tagis optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition.
At the end of the union's definition, before the final semicolon, you can specify one or more
union variables but it is optional.
Here is the way you would define a union type named Data which has the three members i, f,
and str.
Now, a variable of Datatype can store an integer, a floating-point number, or a string of
characters. This means that a single variable ie. same memory location can be used to store
multiple types of data.
You can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the
union.
For example, in above example Data type will occupy 20 bytes of memory space because this
is the maximum space which can be occupied by character string. Following is the example
which will display total memory size occupied by the above union:
Accessing a Member of a Union
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;}
Dot operator can be used to access a member of the union . The member access operator is
coded as a period between the union variable name and the union member that we wish to
access. You would use union keyword to define variables of union type.

Enum
Enums or enumerations are a new data type supported in TypeScript. Most object-oriented
languages like Java and C# use enums. This is now available in TypeScript too.
In simple words, enums allow us to declare a set of named constants i.e. a collection of
related values that can be numeric or string values.
There are three types of enums:
 Numeric enum
 String enum
 Heterogeneous enum
Numeric Enum
Numeric enums are number-based enums i.e. they store string values as numbers.
Enums can be defined using the keyword enum. Let's say we want to store a set of print
media types. The corresponding enum in TypeScript would be:

Example: Numeric Enum


enum PrintMedia {
Newspaper,
Newsletter,
Magazine,
Book
}
In the above example, we have an enum named PrintMedia. The enum has four values:
Newspaper, Newsletter, Magazine, and Book. Here, enum values start from zero and
increment by 1 for each member. It would be represented as:
Newspaper = 0
Newsletter = 1
Magazine = 2
Book = 3
Enums are always assigned numeric values when they are stored. The first value always takes
the numeric value of 0, while the other values in the enum are incremented by 1.
We also have the option to initialize the first numeric value ourselves. For example, we can
write the same enum as:
enum PrintMedia {
Newspaper = 1,
Newsletter,
Magazine,
Book
}
The first member, Newspaper, is initialized with the numeric value 1. The remaining
members will be incremented by 1 from the numeric value of the first value.
Thus, in the above example, Newsletter would be 2, Magazine would be 3 and Book would
be 4.
It is not necessary to assign sequential values to Enum members. They can have any values.
enum PrintMedia {
Newspaper = 1,
Newsletter = 5,
Magazine = 5,
Book = 10
}
The enum can be used as a function parameter or return type, as shown below:

Example: Enum as Return Type


enum PrintMedia {
Newspaper = 1,
Newsletter,
Magazine,
Book
}
function getMedia(mediaName: string): PrintMedia {
if ( mediaName === 'Forbes' || mediaName === 'Outlook') {
return PrintMedia.Magazine;
}
}
let mediaType: PrintMedia = getMedia('Forbes'); // returns Magazine
In the above example, we declared an enum PrintMedia. Next, we declare a function
getMedia() that takes in an input parameter mediaName of the type string.
This function returns an enum PrintMedia. In the function, we check for the type of media. If
the media name matches 'Forbes' or 'Outlook', we return enum member
PrintMedia.Magazine.

Computed Enums:
Numeric enums can include members with computed numeric value. The value of an enum
member can be either a constant or computed.
The following enum includes members with computed values.

Example: Computed Enum


enum PrintMedia {
Newspaper = 1,
Newsletter = getPrintMediaCode('newsletter'),
Magazine = Newsletter * 3,
Book = 10
}
function getPrintMediaCode(mediaName: string): number {
if (mediaName === 'newsletter') {
return 5;
}
}

PrintMedia.Newsetter; // returns 5
PrintMedia.Magazine; // returns 15

When the enum includes computed and constant members, then uninitiated enum members
either must come first or must come after other initialized members with numeric constants.
The following will give an error.
enum PrintMedia {
Newsletter = getPrintMediaCode('newsletter'),
Newspaper, // Error: Enum member must have initializer
Book,
Magazine = Newsletter * 3,
}
The above enum can be declared as below.
enum PrintMedia {
Newspaper,
Book,
Newsletter = getPrintMediaCode('newsletter'),
Magazine = Newsletter * 3
}// orenum PrintMedia {
Newsletter = getPrintMediaCode('newsletter'),
Magazine = Newsletter * 3,
Newspaper = 0,
Book,
}

String Enum
String enums are similar to numeric enums, except that the enum values are initialized with
string values rather than numeric values.
The benefits of using string enums is that string enums offer better readability. If we were to
debug a program, it is easier to read string values rather than numeric values.
Consider the same example of a numeric enum, but represented as a string enum:

Example: String Enum


enum PrintMedia {
Newspaper = "NEWSPAPER",
Newsletter = "NEWSLETTER",
Magazine = "MAGAZINE",
Book = "BOOK"
}// Access String Enum
PrintMedia.Newspaper; //returns NEWSPAPER
PrintMedia['Magazine'];//returns MAGAZINE
In the above example, we have defined a string enum, PrintMedia, with the same values as
the numeric enum above, with the difference that these enum values are initialized with string
literals.
The difference between numeric and string enums is that numeric enum values are
auto-incremented, while string enum values need to be individually initialized.

Heterogeneous Enum
Heterogeneous enums are enums that contain both string and numeric values.
Example: Heterogeneous Enum
enum Status {
Active = 'ACTIVE',
Deactivate = 1,
Pending
}

Reverse Mapping
Enum in TypeScript supports reverse mapping. It means we can access the value of a member
and also a member name from its value. Consider the following example.
Example: Reverse Mapping
enum PrintMedia {
Newspaper = 1,
Newsletter,
Magazine,
Book
}

PrintMedia.Magazine; // returns 3
PrintMedia["Magazine"];// returns 3
PrintMedia[3]; // returns Magazine
As you can see in the above example, PrintMedia[3] returns its member name "Magazine".
This is because of reverse mapping.
Let's see how TypeScript implements reverse mapping using the following example.
enum PrintMedia {
Newspaper = 1,
Newsletter,
Magazine,
Book
}
console.log(PrintMedia)
The above example gives the following output in the browser console.
{
'1': 'Newspaper',
'2': 'Newsletter',
'3': 'Magazine',
'4': 'Book',
Newspaper: 1,
Newsletter: 2,
Magazine: 3,
Book: 4
}
You will see that each value of the enum appears twice in the internally stored enum object.
We know that num values can be retrieved using the corresponding enum member value.
But it is also true that enum members can be retrieved using their values. This is called
reverse mapping.
TypeScript can compile the above enum into the following JavaScript function.

Example: Compiled JavaScript of Enum


var PrintMedia;
(function (PrintMedia) {
PrintMedia[PrintMedia["Newspaper"] = 1] = "Newspaper";
PrintMedia[PrintMedia["Newsletter"] = 2] = "Newsletter";
PrintMedia[PrintMedia["Magazine"] = 3] = "Magazine";
PrintMedia[PrintMedia["Book"] = 4] = "Book";
})(PrintMedia || (PrintMedia = {}));
PrintMedia is an object in JavaScript which includes both value and name as properties and
that's why enum in TypeScript supports reverse mapping.
So, both the following mappings are true to enums: name -> value, and value -> name.

STRUCTURE:
A Structure is a user defined data type that can store related information together.
The variable within a structure are of different data types and each has a name that is used to
select it from the structure.C arrays allow you to define type of variables that can hold several
data items of the same kind but structure is another user defined data type available in C
programming, which allows you to combine data items of different kinds.
Structures are used to represent a record, Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book:
•Title
•Author
•Subject
•Book ID
Structure Declaration It is declared using a keyword struct followed by the name of the
structure. The variables of the structure are declared within the structure.
Example:
Struct struct-name {
data_type var-name;
data_type var-name; };
Structure Initialization Assigning constants to the members of the structure is called
initializing ofstructure.
Syntax:
struct struct_name {
data _type member_name1;
data _type member_name2;
}
struct_var={constant1,constant2};
Accessing the Members of a structure A structure member variable is generally accessed
using a ‘.’ operator.
Syntax:
strcut_var. member_name;
The dot operator is used to select a particular member of the structure.
To assign value to the individual Data members of the structure variable stud, we write,
stud.roll=01;
stud.name=”Rahul”;
To input values for data members of the structure variable stud, can be written as,
scanf(“%d”,&stud.roll);scanf(‘’%s”,&stud.name);
To print the values of structure variablestud, can be written as:
printf(“%s”,stud.roll);printf(“%f”,stud.name);

NESTED STRUCTURES
The structure that contains another structure as its members is called a nested structure or a
structure within a structure is called nested structure.
The structure should be declared separately and then be grouped into high level structure.

Passing Structures through pointers Pointer to a structure is a variable that holds the address
of a structure.
The syntax to declare pointer to a structure can be given as:
strcut struct_name *ptr;
To assign address of stud to the pointer using address operator(&) we would write
ptr_stud=&stud;
To access the members of the structure (->) operator is used. for example
Ptr_stud->name=Raj;

SELF REFERENTIAL STRUCTURE


Self –referential structures are those structures that contain a reference to data of its same
type as that of structure.
Example
struct node {
int val;
struct node*next;
};
Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to any other
variable as follows:
struct books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable.
To find the address of a structure variable, place the & operator before the structure's name as
follows:
struct_pointer = &book1;
To access the members of a structure using a pointer to that structure, you must use the ->
operator as follows:
struct_pointer->title;

OBJECT ORIENTED PROGRAMMING:


JavaScript is an Object Oriented Programming (OOP) language. A programming language
can be called object-oriented if it provides four basic capabilities to developers −
 Encapsulation − the capability to store related information, whether data or methods,
together with an object.
 Aggregation − the capability to store one object inside another object.
 Inheritance − the capability of a class to rely upon another class (or number of
classes) for some of its properties and methods.
 Polymorphism − the capability to write one function or method that works in a
variety of different ways.
Objects are composed of attributes. If an attribute contains a function, it is considered to be a
method of the object, otherwise, the attribute is considered a property.
What is OOPS Concept in JavaScript?
Many times, variables or arrays are not sufficient to simulate real-life situations. JavaScript
allows you to create objects that act like real life objects.
A student or a home can be an object that have many unique characteristics of their own. You
can create properties and methods to your objects to make programming easier.
If your object is a student, it will have properties like first name, last name, id etc and
methods like calculateRank, changeAddress etc.
If your object is a home, it will have properties like a number of rooms, paint color, location
etc and methods like calculateArea, changeOwner etc.

How to Create an Object


You can create an object like this:
var objName = new Object();
objName.property1 = value1;
objName.property2 = value2;
objName.method1 = function()
{
line of code
}
OR
var objName= {property1:value1, property2:value2, method1: function()

{ lines of code} };

Access Object Properties and Methods


You can access properties of an object like this:
objectname.propertyname;

You can access methods of an object like this:


objectname.methodname();

Try this Example yourself:


<html>
<head>
<title>Objects!!!</title>
<script type="text/javascript">
var student = new Object();
student.fName = "John";
student.lName = "Smith";
student.id = 5;
student.markE = 76;
student.markM = 99;
student.markS = 87;
student.calculateAverage = function()
{
return (student.markE + student.markM + student.markS)/3;
};
student.displayDetails = function()
{
document.write("Student Id: " + student.id + "<br />");
document.write("Name: " + student.fName + " " + student.lName +
"<br />");
var avg = student.calculateAverage();
document.write("Average Marks: " + avg);
};
student.displayDetails();
</script>
</head>
<body>
</body>
</html>

OOPS Constructor
But creating objects of this kind is not that useful because here also, you will have to create
different objects for different students. Here comes object constructor into picture. Object
constructor helps you create an object type which can be reused to meet the need of
individual instance.
<html>
<head>
<script type="text/javascript">
function Student(first, last, id, english, maths, science)
{
this.fName = first;
this.lName = last;
this.id = id;
this.markE = english;
this.markM = maths;
this.markS = science;
this.calculateAverage = function()
{
return (this.markE + this.markM + this.markS)/3;
}
this.displayDetails = function()
{
document.write("Student Id: " + this.id + "<br />");
document.write("Name: " + this.fName + " " + this.lName + "<br
/>");
var avg = this.calculateAverage();
document.write("Average Marks: " + avg + "<br /><br />");
}
}
var st1 = new Student("John", "Smith", 15, 85, 79, 90);
var st2 = new Student("Hannah", "Turner", 23, 75, 80, 82);
var st3 = new Student("Kevin", "White", 4, 93, 89, 90);
var st4 = new Student("Rose", "Taylor", 11, 55, 63, 45);
st1.displayDetails();
st2.displayDetails();
st3.displayDetails();
st4.displayDetails();
</script>
</head>
<body>
</body>
</html>

Loop Through the Properties of an Object


Syntax:
for (variablename in objectname)
{
lines of code to be executed
}
The for/in a loop is usually used to loop through the properties of an object. You can give any
name for the variable, but the name of the object should be the same as that of an already
existing object which you need to loop through.
<html>
<head>
<script type="text/javascript">
var employee={first:"John", last:"Doe", department:"Accounts"};
var details = "";
document.write("<b>Using for/in loops </b><br />");
for (var x in employee)
{
details = x + ": " + employee[x];
document.write(details + "<br />");
}
</script>
</head>
<body>
</body>
</html>

EXCEPTIONAL HANDLING
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c)
Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming
languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missing a closing
parenthesis.
<script type = "text/javascript">
<!--
window.print(;
//-->
</script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as
the syntax error is affected and the rest of the code in other threads gets executed assuming
nothing in them depends on the code containing the error.

Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is correct, but
at runtime, it is trying to call a method that does not exist.
<script type = "text/javascript">
<!--
window.printme();
//-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to
continue normal execution.
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the
result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic
that drives your script and you do not get the result you expected.
You cannot catch those errors, because it depends on your business requirement what type of
logic you want to put in your program.

The try...catch...finally Statement


The latest versions of JavaScript added exception handling capabilities. JavaScript
implements the try...catch...finally construct as well as the throw operator to handle
exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch
JavaScript syntax errors.
Here is the try...catch...finally block syntax −
<script type = "text/javascript">
<!--
try {
// Code to run
[break;]
}
catch ( e ) {
// Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//--></script>

The try block must be followed by either exactly one catch block or one finally block (or
one of both). When an exception occurs in the try block, the exception is placed in e and the
catch block is executed. The optional finally block executes unconditionally after try/catch.

Examples
Here is an example where we are trying to call a non-existing function which in turn is
raising an exception. Let us see how it behaves without try...catch−
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script> </head>

<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body></html>
Now let us try to catch this exception using try...catch and display a user-friendly message.
You can also suppress this message, if you want to hide this error from a user.

<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body></html>
You can use finally block which will always execute unconditionally after the try/catch. Here
is an example.
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body></html>

The throw Statement


You can use throw statement to raise your built-in exceptions or your customized exceptions.
Later these exceptions can be captured and you can take an appropriate action.
Example
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
var b = 0;
try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//--> </script>

</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body></html>
UNIT - II
ADVANCED JAVA SCRIPT
DOCUMENT OBJECT MODEL
What is Document Object Model (DOM)
The Document Object Model (DOM) is an API for manipulating HTML and XML
documents.
The DOM represents a document as a tree of nodes. It provides API that allows you to add,
remove, and modify parts of the document effectively.
Note that the DOM is cross-platform and language-independent ways of manipulating HTML
and XML documents.
A document as a hierarchy of nodes
The DOM represents an HTML or XML document as a hierarchy of nodes. Consider the
following HTML document:
<html>
<head>
<title>JavaScript DOM</title>
</head>
<body>
<p>Hello DOM!</p>
</body>
</html>
The following tree represents the above HTML document:
In this DOM tree, the root node is a document node. The root node has only one child which
is the <html> element. The html element is called the document element.
Each document can have only one document element. In HTML pages, the document element
is the <html> element. Each markup can be represented by a node in the tree.
Node Types
Each node in the DOM tree is identified by a node type. JavaScript uses integer numbers to
determine node types. The following table illustrates the node type constants:
Constant Value Description
Node.ELEMENT_NODE 1 An Element node like <p> or <div>.
The actual Text inside an Element or
Node.TEXT_NODE 3
Attr.
A CDATASection, such as
Node.CDATA_SECTION_NODE 4
<!CDATA[[ … ]]>.
A ProcessingInstruction of an XML
Node.PROCESSING_INSTRUCTION_NODE 7 document, such as
<?xml-stylesheet … ?>.
Node.COMMENT_NODE 8 A Comment node, such as <!-- … -->.
Node.DOCUMENT_NODE 9 A Document node.
A DocumentType node, such as
Node.DOCUMENT_TYPE_NODE 10
<!DOCTYPE html>.
Node.DOCUMENT_FRAGMENT_NODE 11 A DocumentFragment node.

To get the type of a node, you use the nodeType property:


node.nodeType

Node and Element


A node is a generic name for any object in the DOM hierarchy. A node can be one of the
built-in DOM elements such as a document. Or it could be an HTML tag specified in the
HTML like <div> or <section>. It could be a text node created to hold a text inside an
element.
An element is a node with a specific type Node.ELEMENT_NODE. An element always has
the node type of 1.
The getElementById() or querySelector() returns an element with the Element type while
getElementsByTagName() or querySelectorAll() returns a collection of nodes with the
type NodeList.
The following picture illustrate the relationship between the Node and Element types:
Node Relationships
All nodes in the DOM tree have relationships to other nodes. The relationships are the same
as the one described in a traditional family tree.
For example, <body> is a child node of the <html> node, and <html> is the parent of the
<body> node.
The <body> node is the sibling of the <head> node because they share the same immediate
parent, which is the <html> element.
The following picture illustrates the relationships between nodes:
The DOM gives youaccess to all the elements on a web page.Using JavaScript, you cancreate,
modify and remove elements in the page dynamically.
The getElementById method is the simplestway to access a specific element in a page. The
getElementById method returns objects called DOM nodes.
Every element in anXHTML page is modeled in the web browser by a DOM node. All the
nodes in a docu-ment make up the page’s DOM tree, which describes the relationships
among elements. Nodes are related to each other through child-parent relationships.
An XHTML elementinside another element is said to be a child of the containing element.
The containing ele-ment is known as the parent.
A node may have multiple children, but only one parent.Nodes with the same parent node are
referred to as siblings.

The document node (shown as #document) at the top of the tree is called the root
node,because it has no parent. The HEAD and BODY nodes are siblings, since they are both
children of the HTMLnode.
The HEAD contains two #comment nodes, representing lines 5–6. The TITLE node has a
child text node (#text) containing the text DOM Tree Demonstration, visible in theright pane
of the DOM inspector when the text node is selected.
The BODY node containsnodes representing each of the elements in the page. Note that the
LI nodes are childrenof the UL node, since they are nested inside it.
The DOM gives you access to the elements of a document, allowing you to modify
thecontents of a page dynamically using event-driven JavaScript.
Each element has an idattribute, which is also displayed at the beginning of the element in
square brackets.
Forexample, the id of the h1 element in lines
<body onload ="currentNode = document.getElementById( 'bigheading' )">
<h1 id = "bigheading"class = "highlighted">
[bigheading] DHTML Object Model
</h1>
is set to bigheading, and the headingtext begins with [bigheading]. This allows the user to
see the id of each element in thepage.
The HTML DOM model is constructed as a tree of Objects

With a programmable object model, JavaScript gets all the power it needs to create dynamic
HTML:
•JavaScript can change all the HTML elements in the page
•JavaScript can change all the HTML attributes in the page
•JavaScript can change all the CSS styles in the page
•JavaScript can react to all the events in the page

Finding HTML Elements


Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are a couple of ways to do this:
 Finding HTML elements by id
 Finding HTML elements by tag name
 Finding HTML elements by class name

Finding HTML Elements by Id


The easiest way to find HTML elements in the DOM, is by using the element id.This
example finds the element with id="intro":
Example
var x=document.getElementById("intro");
If the element is found, the method will return the element as an object (in x).If the element is
not found, x will contain null.
Finding HTML Elements by Tag Name
This example finds the element with id="main", and then finds all <p> elements inside
"main":Examplevar
x=document.getElementById("main");
var y=x.getElementsByTagName("p");

Changing the HTML Output Stream


JavaScript can create dynamic HTML content:
Date: Mon Mar 18 2013 22:09:51 GMT+0000 (WET)
In JavaScript, document.write() can be used to write directly to the HTML output stream:
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>

Changing HTML Content


The easiest way to modify the content of an HTML element is by using the innerHTML
property.To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML=new HTML
This example changes the content of a <p> element:
Example
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>
This example changes the content of an <h1> element:
Example
<!DOCTYPE html>
<html>
<body>
<h1 id="header">Old Header</h1>
<script>
var element=document.getElementById("header");
element.innerHTML="New Header";
</script>
</body>
</html>
Example explained:
 The HTML document above contains an <h1> element with id="header"
 We use the HTML DOM to get the element with id="header"
 A JavaScript changes the content (innerHTML) of that element

Changing an HTML Attribute


To change the attribute of an HTML element, use this syntax:
document.getElementById(id).attribute=new value
This example changes the src attribute of an <img> element:
Example
<!DOCTYPE html>
<html>
<body>
<img id="image" src="smiley.gif">
<script>
document.getElementById("image").src="landscape.jpg";
</script>
</body>
</html>

Changing HTML Style


To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
The following example changes the style of a <p> element:
Example
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color="blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
This example changes the style of the HTML element with id="id1", when the user clicks a
button:
Example
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button" onclick="document.getElementById('id1').style.color='red'">Click
Me!</button>
</body>
</html>

Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML
element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event
attribute:
onclick=JavaScript
Examples of HTML events:
•When a user clicks the mouse
•When a web page has loaded
•When an image has been loaded
•When the mouse moves over an element
•When an input field is changed
•When an HTML form is submitted
•When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks on it:
Example
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>

HTML Event Attributes


To assign events to HTML elements you can use event attributes.ExampleAssign an onclick
event to a button element:
<button onclick="displayDate()">Try it</button>
In the above function named displayDate will be executed when the button is clicked.
Assign Events Using the HTML DOM
The HTML DOM allows you to assign events to HTML elements using JavaScript:
Example

Assign an onclick event to a button element:


<script>
document.getElementById("myBtn").onclick=function(){
displayDate()
};
</script>
In the example above, a function named displayDate is assigned to an HTML element with
the id=myButn".
The function will be executed when the button is clicked.

The onload and onunload Events


The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and
load the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
Example
<body onload="checkCookies()">

The onchange Event


The onchange event are often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called
when a user changes the content of an input field.
Example
<input type="text" id="fname" onchange="upperCase()">

The onmouseover and onmouseout Events


The onmouseover and onmouseout events can be used to trigger a function when the user
mouses over, or out of, an HTML element.

The onmousedown, onmouseup and onclick Events


The onmousedown, onmouseup, and onclick events are all parts of a mouse-click.
First when a mouse-button is clicked, the onmousedown event is triggered, then, when the
mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is
completed, the onclick event is triggered
Creating New HTML Elements
To add a new element to the HTML DOM, you must create the element (element node) first,
and then append it to an existing element.
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
</script>

Example Explained
This code creates a new <p> element:
var para=document.createElement("p");
To add text to the <p> element, you must create a text node first.
This code creates a text node:
var node=document.createTextNode("This is a new paragraph.");
Then you must append the text node to the <p> element:
para.appendChild(node);
Finally you must append the new element to an existing element.This code finds an existing
element:
var element=document.getElementById("div1");
This code appends the new element to the existing element:
element.appendChild(para);

Removing Existing HTML Elements


To remove an HTML element, you must know the parent of the element:
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>
Example Explained
This HTML document contains a <div> element with two child nodes (two <p> elements):
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
Find the element with id="div1":
var parent=document.getElementById("div1");
Find the <p> element with id="p1":
var child=document.getElementById("p1");
Remove the child from the parent:
parent.removeChild(child);

INTRODUCTION - ARRAYS
In JavaScript, an array is an ordered list of data. An array has the following special
characteristics in comparison with the array of other programming languages such as Java
and C/C++.
1. First, an array can hold data of the different types in each slot i.e., an array can hold
elements with mixed of numbers, strings, objects, etc.
2. Second, the length of an array is dynamically sized and auto-growing.

ONE DIMENSIONAL ARRAY


Creating JavaScript arrays
JavaScript provides you with two ways to create an array. The first one is to use the Array
constructor as follows:

let scores = new Array();

The scores array is empty i.e. it holds no element.


If you know the number of elements that the array will hold, you can create an array with an
initial size as shown in the following example:
let scores = Array(10);
To create an array with initial elements, you pass the elements as a comma-separated list in
the Array() constructor. The following example creates the scores array that holds five
numbers:
let scores = new Array(9,10,8,7,6);
It’s important to notice that if you use the array constructor to create an array and pass in a
number, you are creating an array with an initial size. However, if you pass in one argument
of another type, you create an array that holds that element.
See the following examples:
let athletes = new Array(3); // creates an array with initial size 3
let scores = new Array(1, 2, 3); // create an array with three numbers 1,2 3
let signs = new Array('Red'); // creates an array with one element 'Red'
JavaScript allows you to omit the new operator when you use the array constructor. For
example, the following statement creates the artists array.
let artists = Array();
The second way, maybe the more preferred way, to create an array is by using the array
literal notation as follows:

let array_name = [element1, element2, element3];

The array literal form uses the square brackets [] to wrap a comma-separated list of elements.
For example, the following statement creates colors array of three colors:

let colors = ['red', 'green', 'blue'];

It’s possible to create an empty array by using empty square brackets.

let emptyArray = [];

The following example creates an array of two undefined elements.


let nonEmptyArry = [,,];
console.log(nonEmptyArray); // [undefined, undefined]

Accessing JavaScript array elements


You can access elements of an array by using the square brackets []. The first element of the
array start with 0, the second element starts with 1, and so on.
For example, the following example creates an array of three strings.

let mountains = ['Everest', 'Fuji', 'Nanga Parbat'];

The following statements show how to access the elements of the mountains array.

console.log(mountains[0]); // 'Everest'
console.log(mountains[1]); // 'Fuji'
console.log(mountains[2]); // 'Nanga Parbat'

To change the value of an element in the array, you use assign that element a value as
follows:
mountains[2] = 'K2';
The size of an array
The array uses the length property to store the current number of elements it holds. You can
access get the value of the length property as shown in the following example.
console.log(mountains.length); // 3

The length property is writable therefore you can insert or delete elements by changing the
value of the length property.
If you set the length property to a value that is greater than the number of elements in the
array, the new elements will be added with the initial values of undefined.
For example, we change the length property of the mountains array to 4 to append one
element with an initial value of undefined at the end of the array.
// append 1 element
mountains.length = 4;
console.log(mountains[3]); // undefined

Similarly, the following example sets the length property of the mountains array to 2 to
remove the last two elements of the array. When we access the third element of the array, it
returns undefined.
// remove the last 2 elements
mountains.length = 2;
console.log(mountains[2]); // undefined

Note that the maximum number of elements that the JavaScript array can hold is
4,294,967,295 which is sufficient enough for a typical application.
Basic operations on arrays
All arrays are instances of the Array type. Therefore, the typeof of an array variable returns
object as shown in the following example:
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
console.log(typeof seas); // object

To check if a variable is an array, you use Array.isArray() method as follows:


console.log(Array.isArray(seas)); // true

When you call the toString() and valueOf() methods of an array, you get a string represented
as a comma-separated list of elements as shown in the following example:
console.log(seas.toString()); // Black Sea,Caribbean Sea,North Sea,Baltic Sea
console.log(seas.valueOf());
If you want to have a string representation of an array differently, you can use the join()
method.
The following example uses the join() method to returns a string representation of the
mountains array. However, the elements are separated by the pipe (|) character instead.
console.log(seas.join('|'));
// Black Sea|Caribbean Sea|North Sea|Baltic Sea

If an element of the array is null or undefined, the toString(), valueOf(), and join() will treats
it as an empty string in the resulting string. Here is an example.
let mixedValues = [1, 2, null, 'A', undefined, 3];
console.log(mixedValues.toString()); // 1,2,,A,,3

TWO DIMENSIONAL ARRAY


Introduction to JavaScript multidimensional array
JavaScript does not provide the multidimensional array natively. However, you can create a
multidimensional array by defining an array of elements, where each element is also another
array. For this reason, we can say that a JavaScript multidimensional array is an array of
arrays.
The easiest way to define a multidimensional array is to use the array literal notation. The
following example defines a two-dimensional array named activities.
var activities = [
['Work', 9],
['Eat', 2],
['Commute', 2],
['Play Game', 2],
['Sleep', 7]
];

In the activities array, the first dimension represents the activity and the second one shows
the number of hours spent per day for each.
The following figure illustrates the activities array:

To access an element of the multidimensional array, you first use square brackets to access an
element of the outer array that returns an inner array; and use another square bracket to
access the element of the inner array.
The following example returns the second element of the first inner array in the activities
array above.

console.log(activities[0][1]); // 9

Adding an element to the JavaScript multidimensional array


You can use the array methods to manipulate a multidimensional array as normal. For
example, to add a new element to a multidimensional array, you use the push() method as in
the following example.

activities.push(['Study',2]);

This example calculates the percentage of the hours spent on each activity and appends the
percentage to the inner array.

for (var i = 0; i < activities.length; i++) {


var percentage = ((activities[i][1] / 24) * 100).toFixed();
activities[i][2] = percentage + '%';
}
console.log(activities.join('\n'));

The following shows the output in the web console.


Work,9,38%
Eat,2,8%
Commute,2,8%
Play Game,2,8%
Sleep,7,29%
Date,2,8%

Removing an element from the JavaScript multidimensional array


To remove an element from an array, you use the pop() method. For example, the following
statement removes the last element of the activities array.
activities.pop();
console.log(activities.join('\n'));
The output of the script on the console window:
Work,9,38%
Eat,2,8%
Commute,2,8%
Play Game,2,8%
Sleep,7,29%

Similarly, you can remove the elements from the inner array of the multidimensional array by
using the pop() method.
Here is an example of removing the percentage element from the inner arrays of the activities
array.
for (var i = 0; i < activities.length; i++) {
activities[i].pop(2);
}
console.log(activities.join('\n'));
Work,9
Eat,2
Commute,2
Play Game,2
Sleep,7

Iterating a JavaScript multidimensional array


To iterate a multidimensional array, you use a nested for loop as in the following example.
// loop the outer array
for (var i = 0; i < activities.length; i++) {
// get the size of the inner array
var innerArrayLength = activities[i].length;
// loop the inner array
for (var j = 0; j < innerArrayLength; j++) {
console.log('[' + i + ',' + j + '] = ' + activities[i][j]);
}
}
The first loop iterates over the elements of the outer array, while the nested one iterates over
the inner array.

The following shows the output of the script in the web console.
[0,0] = Work
[0,1] = 9
[1,0] = Eat
[1,1] = 2
[2,0] = Commute
[2,1] = 2
[3,0] = Play Game
[3,1] = 2
[4,0] = Sleep
[4,1] = 7

CALLBACK FUNCTIONS

Callback Definition
A callback function is a function that is passed as an argument to another function, to be
“called back” at a later time. A function that accepts other functions as arguments is called a
higher-order function, which contains the logic for when the callback function gets
executed. It’s the combination of these two that allow us to extend our functionality.
To implement a callback function, the JavaScript code in a page must first define the function.
The following sample code defines a function and stores a variable reference to it:
var callbackDefinition = function(numParam) {
alert(numParam);
};
The function uses a numerical parameter for demonstration.
The callback function can contain any JavaScript code a standard function could include. The
code will now be able to pass a reference to the function as parameter to another function,
using the variable name.

Callback Parameter
Once a script has a function defined as a variable, it can pass that variable as parameter to
another function. The following sample code demonstrates the technique:
mainFunction(10, callbackDefinition);
This code calls a named function, passing a number parameter and the name of the variable
storing the callback function code.
The outline of the function being called here must match these two parameters. The function
receiving the callback variable will be able to call the function it stores.

Function Execution
Once passed to the main function, a callback function can be executed. The following sample
code demonstrates:
function mainFunction(myNum, callbackFn) {
alert(myNum); callbackFn(myNum*2);
}
For demonstration, this code first outputs a JavaScript alert which will cause a dialog to
appear in the user's browser. Once this code executes, the function calls the callback function
using the name specified as parameter.
The callback function call includes a numerical parameter, which is expected by the function
that was initially defined as a variable.

Function Call
Once a page has a function defined, including a callback, it can execute this code. Often,
developers instruct the browser to listen for a user event, executing functions when this
occurs.
For example, the following HTML code calls a function:
Here is a click-able section
If the function specified as parameter contains the callback variable definition and the call to
the main function, this will create the callback effect, as follows:
function doCallback() {
var callFn = function(numParam) { alert(numParam); };
mainFunction(10, callFn);
}
Once the main function executes its own code content, it calls the callback function.
To illustrate callbacks, let’s start with a simple example:
function createQuote(quote, callback){
var myQuote = "Like I always say, " + quote;
callback(myQuote); // 2}
function logQuote(quote){
console.log(quote);}
createQuote("eat your vegetables!", logQuote); // 1
// Result in console:
// Like I always say, eat your vegetables!

In the above example, createQuote is the higher-order function, which accepts two arguments,
the second one being the callback.
The logQuote function is being used to pass in as our callback function.
When we execute the createQuote function (1), notice that we are not appending parentheses
to logQuote when we pass it in as an argument.
This is because we do not want to execute our callback function right away, we simply want
to pass the function definition along to the higher-order function so that it can be executed
later.
Also, we need to ensure that if the callback function we pass in expects arguments, that we
supply those arguments when executing the callback (2).
In the above example, that would be the callback(myQuote); statement, since we know that
logQuote expects a quote to be passed in.
Additionally, we can pass in anonymous functions as callbacks. The below call to
createQuote would have the same result as the above example:

createQuote("eat your vegetables!", function(quote){


console.log(quote);
});

Incidentally, you don’t have to use the word “callback” as the name of your argument,
Javascript just needs to know that it’s the correct argument name.
Based on the above example, the below function will behave in exactly the same manner.
function createQuote(quote, functionToCall) {
var myQuote = "Like I always say, " + quote;
functionToCall(myQuote);
}

Passing JavaScript Functions as Variables Revisited


function functionName(var1, var 2) {
// some code
}

functionName(argument1, argument2);

When you call a function, you can pass along some values to it, these values are called
arguments or parameters.
These arguments can then be used inside of the function.
You can send as many arguments as you like, separated by commas (,)
To use the arguments inside of the function, you must declare the arguments as variables
when defining the function
The variables and arguments must be in expected order.
That is, the first argument gets assigned to the first variable.

function functionOne(x) { return x; };


function functionTwo(var1) {
// some code
}

functionTwo(functionOne);
Because you can assign functions to variables, and because functions are objects in
JavaScript, you can pass functions to other functions as variables
Which means that in this case, we are passing functionOne as a variable to be used inside of
functionTwo
Inside of functionTwo, var1's value will be functionOne
This is how you can pass functions to other functions in JavaScript.
In this case, functionTwo can use functionOne inside of it.
FORM HANDLING

GET/POST METHOD

GET vs. POST


Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 =>
value3, ...)). This array holds key/value pairs, where keys are the names of the form controls
and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which
means that they are always accessible, regardless of scope - and you can access them from
any function, class or file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?


Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL). GET also has limits on the amount of information to
send. The limitation is about 2000 characters. However, because the variables are displayed
in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.

When to use POST?


Information sent from a form with the POST method is invisible to others (all names/values
are embedded within the body of the HTTP request) and has no limits on the amount of
information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark
the page.

FORM VALIDATION
Form validation normally used to occur at the server, after the client had entered all the
necessary data and then pressed the Submit button. If the data entered by a client was
incorrect or was simply missing, the server would have to send all the data back to the client
and request that the form be resubmitted with correct information. This was really a lengthy
process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to
the web server. Form validation generally performs two functions.
 Basic Validation − First of all, the form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop through each field in the form and check
for data.
 Data Format Validation − Secondly, the data that is entered must be checked for
correct form and value. Your code must include appropriate logic to test correctness of
data.

Example
We will take an example to understand the process of validation. Here is a simple form in
html format.
<html> <head>
<title>Form Validation</title>
<script type = "text/javascript">
<!-- // Form validation code will come here. //-->
</script>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit =
"return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body></html>

Basic Form Validation


First let us see how to do a basic form validation. In the above form, we are calling validate()
to validate data when onsubmit event is occurring. The following code shows the
implementation of this validate() function.
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {

if( document.myForm.Name.value == "" ) {


alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 ) {

alert( "Please provide a zip in the format #####." );


document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//--></script>

Data Format Validation


Now we will see how we can validate our entered form data before submitting it to the web
server.
The following example shows how to validate an entered email address. An email address
must contain at least a ‘@’ sign and a dot (.).
Also, the ‘@’ must not be the first character of the email address, and the last dot must at
least be one character after the ‘@’ sign.

Example
Email validation.
<script type = "text/javascript">
<!--
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");

if (atpos < 1 || ( dotpos - atpos < 2 )) {


alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//--></script>
Accessing form Data
Accessing and manipulating the various elements on a Web page is a common endeavor that
is easily accomplished with JavaScript and the HTML Document Object Model (DOM). In
this article, I examine the various ways to access page elements and describe how to create
them.
The HTML DOM
To quote the W3C, "The Document Object Model is a platform- and language-neutral
interface that will allow programs and scripts to dynamically access and update the content,
structure and style of documents."
All HTML elements, along with their containing text and attributes, can be accessed through
the DOM. An element's contents can be modified or deleted as well as the creation of new
elements.
When working with the DOM and page elements, the most important object is document. It is
contained within the windows object, but you can just type document in JavaScript code and
use it. It represents the entire HTML document while providing access to all of the elements
in a page. You may access page elements via collections, properties, and methods. For this
article, I will focus on accessing fields on a Web page using various approaches.
Accessing data
As you work with a page and its data, you will often need to gain access to an element and
massage the data associated with it. The following methods are available via the DOM and
JavaScript to access individual page elements.
 getElementById(): Returns a reference to the first object with the specified id passed to
the method.
 getElementsByName(): Returns a collection of objects with the specified name passed to
the method.
 getElementsByTagName(): Returns a collection of objects with the specified tag name
passed to the method.
Listing A contains a simple example that uses the first two methods in the previous list. It
includes a form with two fields, and the data must be entered in the two fields before the
document may be submitted. The getElementById method is used to access the first field
with the correct id (i.e., the value assigned to the input field via its ID attribute) passed to it.
The getElementsByName method is used to access the second field via the value assigned to
its name attribute. The getElementsByName method returns an array of values, so I am only
concerned with the first value (i.e., the zero array index value).
I could opt for a different approach for this situation by using the getElementsByTagName
method. This allows you to populate an array object with all of the elements within a page
with a specific tag name. For example, the following line assembles an array of all table cell
(td) elements on the page:
var columns = document.getElementsByTagName("td");
For my example, I am interested in the input fields on the form. Listing B alters the previous
example to utilize the getElementsByTagName method as opposed to the other methods. I
simply check each element of the array for values to perform validation.
The two examples utilize input fields, so I don't want to imply they are the only elements that
may be accessed via the document object and its methods. Listing C takes data entered into
one of the input fields and places it in a paragraph element. The paragraph element is
populated once the user selects the Submit button.

Password Validation
Sometimes a password validation in a form is essential. You can create a password in
different ways, it's structure may be simple, reasonable or strong. Here we validate various
type of password structure through JavaScript codes and regular expression.
 Check a password between 7 to 16 characters which contain only characters, numeric
digits and underscore and first character must be a letter.
 Check a password between 6 to 20 characters which contain at least one numeric digit,
one uppercase and one lowercase letter.
 Check a password between 7 to 15 characters which contain at least one numeric
digit and a special character.
 Check a password between 8 to 15 characters which contain at least one lowercase letter,
one uppercase letter, one numeric digit, and one special character.
Following code blocks contain actual codes for the said validations. We have kept the CSS
code part common for all the validations.
To check a password between 7 to 16 characters which contain only characters, numeric
digits, underscore and first character must be a letter
To validate the said format we use the regular expression ^[A-Za-z]\w{7,15}$, where \w
matches any word character (alphanumeric) including the underscore (equivalent to
[A-Za-z0-9_]). Next the match() method of string object is used to match the said regular
expression against the input value. Here is the complete web document.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - Password Checking - 1</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input Password and Submit [7 to 15 characters which contain only
characters, numeric digits, underscore and first character must be a
letter]</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li class="rq">*Enter numbers only.</li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit"
value="Submit"
nclick="CheckPassword(document.form1.text1)"/> </li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="check-password-1.js"></script>
</body>
</html>

function CheckPassword(inputtxt) {
var passw= /^[A-Za-z]\w{7,14}$/;
if(inputtxt.value.match(passw)) {
alert('Correct, try another...')
return true; }
else {
alert('Wrong...!') return false;
}
}

Number Validation
The validating phone number is an important point while validating an HTML form. In this
page we have discussed how to validate a phone number (in different format) using
JavaScript :
At first, we validate a phone number of 10 digits with no comma, no spaces, no punctuation
and there will be no + sign in front the number. Simply the validation will remove all
non-digits and permit only phone numbers with 10 digits. Here is the function.
function phonenumber(inputtxt) {
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno)) {
return true; }
else {
alert("message");
return false; }
}

HTML Events
Events are actions or occurrences that happen in the system you are programming, which the
system tells you about so you can respond to them in some way if desired. For example, if the
user clicks a button on a webpage, you might want to respond to that action by displaying an
information box.

5.2.4.1. Predefined Events


The most common event types and event names:
mouse events (MouseEvent):
mousedown, mouseup, click, dblclick, mousemove, mouseover, mousewheel, mouseout,
contextmenu
touch events (TouchEvent):
touchstart, touchmove, touchend, touchcancel
keyboard events (KeyboardEvent):
keydown, keypress, keyup
form events:
focus, blur, change, submit
window events:
scroll, resize, hashchange, load, unload
You might be wondering when to use touch events versus mouse events, since they're so
similar.
Touch events are only triggered on touch-enabled devices like smartphones and touch-screen
laptops. Mouse events like click and mousemove are triggered on the majority of browsers
and devices. However, in most smartphones, the mouseover event isn't triggered at all,
because they can't detect a finger hovering over the phone. Some smartphones are adding
sensors for that though, so more smartphones will detect mouseover in the future.
In most cases, you'll want to listen to mouse events instead of touch events, because those are
the most universal.

5.2.4.2. Event Driven Programming


Event-driven programming with JavaScript is a useful way to create interactive websites.
Typically, after the webpage has loaded the JavaScript program continues to run waiting for
an event. If you connect this event to a JavaScript function then the function will run when
the event occurs.

There are few main ideas behind event driven programming.


Creating XHTML Body
Create a webpage using XHTML in the body of a document. This page can be as complex as
you want. Later you will be able to modify the page using JavaScript.

Attaching Events
Attach events to any tag by adding a special attribute to that tag. The name of the attribute
specifies the event and you set the attribute equal to a string that contains a function call.
Every time the event occurs the function is executed.
<h1 onclick="myFunction()">

Accessing Tags
Your event connected JavaScript functions can modify the tags in your document. First, the
JavaScript needs to know which tag you want to modify. You can use the id attribute inside
any of the XHTML tags to give a tag a name. Later you can access the object associated with
that tag by using its id.
<img id="cat" src="cat.jpg"/>
You can access this image object using the JavaScript code
object=document.getElementById("cat");
The variable object now refers to the image object that was created by the previous img tag.

Modifying Tags
Once you have an object you can access or modify it in various ways
You can modify the text in the tag.
Given a tag (object) you modify the text inside the tag using the innerHTML property.
object.innerHTML="Hello World"
You can change the style.
Given a tag (object) you modify a style using the style name.
object.style.fontSize="20pt"
Warning: the style name is changed slightly because JavaScript interprets a - as subtraction.
Therefore font-size becomes fontSize.
You can change the style class.
Given a tag (object) you modify a class using the className property. Remember that the
class name must already be defined with CSS.
object.className="center"
You can modify some of the tag attributes.
Given a tag (object) you modify a tag attribute using it name.
object.src="hat.jpg";
The previous example will only work for an img object because it has a src attribute. Almost
any legal attribute of a tag can be changed: event attributes, id attributes, etc..
An attribute that is often used inside input tags is the value attribute. You can use this
attribute to see what a user has typed into an input and change to the value of the input.
object.value="Hello World";

Notice that you don't have to modify the tag. You can also just check it's value perhaps to
compare it to something else. However most of the time you will want to modify the tag.
Timer Events
One type of useful event is not based on user input but is based on the time. The
window.setInterval() function allows you to tell JavaScript to repeatedly run a function at a
set interval of time.
var interval=window.setInterval("func()",10);
The previous statement causes the function func() to execute every 10 milliseconds.
Often one wants to stop a interval from running. In the previous example, we created a
variable called interval that stored what was returned from window.setInterval("func()",10).
This variable holds an identifier for the interval function. We need this identifier to turn off
the interval function. (You probably will need to make this identifier variable global.)
window.clearInterval(interval);
The previous statement turns off the previous interval. The identifier is necessary because
one can have several interval functions running at the same time and JavaScript needs to
know which one you want to turn off.

5.2.4.3. Events, Action and Listeners


Although you can start functions when your page loads, many times you'll want to start
functions when a user clicks a link, enters a form, scrolls, moves his or her mouse over an
object, or does something else. These actions are called events. You can set specific functions
to run when the user performs an event. These functions "listen" for an event and then initiate
the function.

Common Event Listeners


The following are common events:
onload //when the page loads
onclick //when a user clicks something
onmouseover //when a user mouses over something
onfocus //when a user puts the cursor in a form field
onblur //When a user leaves a form field
Note that each event listener begins with on and is entirely lowercase.

Adding Event Listeners


You can add an event listener directly in the HTML code in the following way:
<button onclick="alert('Hello, world');"></button>
However, mixing the JavaScript code with the HTML directly is generally a poor practice for
the same reason that you don't integrate style commands into HTML but rather reference the
styles in a separate CSS file.
A more common way to integrate the event listeners is by identifying the element and adding
the event listener as a method. The general format for doing this is as follows:
myelement.onclick = function() {
//run your event handler code…
};
In this example, myelement would be a variable that refers to a specific style on your page.
Note that the word function is written without a name because its code is specified in the
code block that immediately follows.
Also note that the statement ends with a semicolon ; after the closing curly brace }.
Associating Events with IDs
If you have a specific ID in your web page that uniquely identifies a section, you can
associate an event with that ID. Here's an example:
//set a variable to refer to a specific ID
var specialSection = document.getElementById("specialSection");
//initiate this function when the user clicks the ID
specialSection.onclick = function() {
alert("Hello World")
};

Adding the addEventListener Method


You can also add event listeners using a method called addEventListener.
However, this method isn't supported in Internet Explorer 8, so if you use this method, you
need to add some conditional functions to check for browser functionality before running the
function.
Some JavaScript libraries, like jQuery, automatically include checks for cross-browser
functionality.
The format for adding events using this method is as follows:
document.addEventListener('click', myfunction, false);
In the above format, you start by adding the method to the Document object. In the
parentheses, list the event listener but without the on.
You then add the function to run. (The function is declared elsewhere.) The false refers to an
advanced, rarely used parameter for event handling.

Referencing Event Handlers


If your event handler refers to a specific element on the page, and you call your script before
the element loads, the script won't work because the element isn't available at the time the
script runs.
You could insert the script before the closing body tag to ensure the elements load first, but
let's say you need your script to run earlier — before the element loads. You can use
the prepareEventHandlers function to load the function when the page loads.

First, add the prepareEventHandlers function:


//declare the function
function prepareEventHandlers() {
//get a specific page ID and assign it as a variable
var specialSection = document.getElementById("specialSection");
//initiate this function when the ID is clicked
specialSection.onclick = function() {
alert("Hello World");
}
}
Now call the prepareEventHandlers function when the window loads:
window.onload = function() {
prepareEventHandlers();
}
Using this technique, the event will be loaded and ready even if it is referenced before the
element it's listening for. Note that you can call the window.onload function only once per
page.

onblur and onfocus Events


onblur and onfocus events refer to the way users interact with forms. When a user clicks a
form field, an onfocus event occurs. When a user clicks out of the field, an onblur event
occurs.
Here's an example. Let's say that your HTML form has an ID called namefield:
<input type="text" value="your name" name="name"
id="namefield" tabindex="10" />

First, get the namefield element, and then add an event to it.
//get the ID and assign it as a variable
var nameField = document.getElementbyId("name");
//when the ID is clicked, run this function
nameField.onfocus = function() {
//if the field has the value "your name", leave it blank
if ( nameField.value == "your name" ) {
nameField.value = "";
}
};
You can also add an onblur event to take place when the user leaves the field.
//get the ID and assign it as a variable
var nameField = document.getElementbyId("name");
//when the user leaves the ID, run this function
nameField.onblur = function() {
//if the field's value is "your name", don't write anything
if ( nameField.value == "your name" ) {
emailField.value = "";
}
};
Timers
You can add events that have a time delay. For example, if you want a pop-up message to
appear after the user has been on the page for 10 seconds, you can do this through
the setTimeOut method.
For example, let's say you have a simple message:
function welcomeVisitor() {alert("Welcome to the site");}
However, you don't want this message to appear until the user has been on the page for a
while. You delay the action through the setTimeOut function:
setTimeOut(welcomeVisitor,8000);
The setTimeOut function has two parameters. The first allows you to call a function (which
we declared earlier), and the second refers to the timer. The function will not be called for
8000 milliseconds.
There are other timer functions, such as setInterval, that initiate the function at the interval
you specify.

Keyboard and Mouse Event


Mouse events basics
In this chapter we’ll get into more details about mouse events and their properties.
Please note: such events may come not only from “mouse devices”, but are also from other
devices, such as phones and tablets, where they are emulated for compatibility.
Mouse event types
We can split mouse events into two categories: “simple” and “complex”
Simple events
The most used simple events are:
mousedown/mouseup
Mouse button is clicked/released over an element.
mouseover/mouseout
Mouse pointer comes over/out from an element.
mousemove
Every mouse move over an element triggers that event.
contextmenu
Triggers when opening a context menu is attempted. In the most common case, that
happens when the right mouse button is pressed. Although, there are other ways to
open a context menu, e.g. using a special keyboard key, so it’s not exactly the mouse
event.
Complex events
click
Triggers after mousedown and then mouseup over the same element if the left mouse
button was used.
dblclick
Triggers after a double click over an element.
Complex events are made of simple ones, so in theory we could live without them.
But they exist, and that’s good, because they are convenient.

Keyboard: keydown and keyup


Before we get to keyboard, please note that on modern devices there are other ways to “input
something”. For instance, people use speech recognition (especially on mobile devices) or
copy/paste with the mouse.
So if we want to track any input into an <input> field, then keyboard events are not enough.
There’s another event named input to track changes of an <input> field, by any means. And it
may be a better choice for such task. We’ll cover it later in the chapter Events: change, input,
cut, copy, paste.
Keyboard events should be used when we want to handle keyboard actions (virtual keyboard
also counts). For instance, to react on arrow keys Up and Down or hotkeys (including
combinations of keys).
UNIT - III

JQuery
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML
document traversal and manipulation, event handling, animation, and Ajax much simpler
with an easy-to-use API that works across a multitude of browsers. With a combination of
versatility and extensibility, jQuery has changed the way that millions of people write
JavaScript.

Javascript Frameworks
The five JavaScript frameworks that currently dominate the market in terms of popularity and
usage are:
React - React is a JavaScript library for building user interfaces.
Vue - Vue is a progressive framework for building user interfaces. Unlike other monolithic
frameworks, Vue is designed from the ground up to be incrementally adoptable. The core
library is focused on the view layer only, and is easy to pick up and integrate with other
libraries or existing projects.
Angular - Angular is an app-design framework and development platform for creating
efficient and sophisticated single-page apps.
Ember - Ember.js is a productive, battle-tested JavaScript framework for building modern
web applications. It includes everything you need to build rich UIs that work on any device.
Backbone.js - Backbone.js gives structure to web applications by providing models with
key-value binding and custom events, collections with a rich API of enumerable
functions, views with declarative event handling, and connects it all to your existing API over
a RESTful JSON interface.

Introduction to JQuery
jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice
motto: Write less, do more. jQuery simplifies HTML document traversing, event handling,
animating, and Ajax interactions for rapid web development.
jQuery is a JavaScript toolkit designed to simplify various tasks by writing less code. Here is
the list of important core features supported by jQuery:
DOM manipulation: The jQuery made it easy to select DOM elements, negotiate them and
modifying their content by using cross-browser open source selector engine called Sizzle.
Event handling: The jQuery offers an elegant way to capture a wide variety of events, such as
a user clicking on a link, without the need to clutter the HTML code itself with event
handlers.
AJAX Support: The jQuery helps you a lot to develop a responsive and feature-rich site using
AJAX technology.
Animations: The jQuery comes with plenty of built-in animation effects which you can use in
your websites.
Lightweight: The jQuery is very lightweight library - about 19KB in size (Minified and
gzipped). Cross Browser Support: The jQuery has cross-browser support, and works well
in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+
Latest Technology: The jQuery supports CSS3 selectors and basic XPath syntax.

Why Use jQuery


When you first get started with jQuery, it takes a while to get used to the syntax; jQuery
looks a little funny at first glance compared to JavaScript.
The ultimate goal of jQuery is to make things you do often in JavaScript just a bit easier; to
simplify common tasks. Here's a quote from the jQuery.com website:
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing,
event handling, animating, and Ajax interactions for rapid web development.
Once you begin writing more complex jQuery code, you'll find the jQuery convenience
methods extremely handy.
You'll also find that many of the things you do using jQuery are much simpler than their
equivalents in JavaScript.
That's a good thing! In addition, jQuery is one of the most popular JavaScript libraries in the
world! So knowing how to read and write jQuery code will be a huge benefit in your career
as a web developer.

Jquery Functions - Show - Hide - Fadein - Fadeout


jQuery Fading Effects
In this topic you will learn how to fade in and out elements using jQuery.
jQuery fadeIn() and fadeOut() Methods
You can use the jQuery fadeIn() and fadeOut() methods to display or hide the HTML
elements by gradually increasing or decreasing their opacity.
<script>
$(document).ready(function(){
// Fading out displayed paragraphs
$(".out-btn").click(function(){
$("p").fadeOut();
}); // Fading in hidden paragraphs
$(".in-btn").click(function(){
$("p").fadeIn();
});
});
</script>
Like other jQuery effects methods, you can optionally specify the duration or speed
parameter for the fadeIn() and fadeOut() methods to control how long the fading animation
will run. Durations can be specified either using one of the predefined string 'slow' or 'fast', or
in a number of milliseconds; higher values indicate slower animations.

<script>
$(document).ready(function(){
// Fading out displayed paragraphs with different speeds
$(".out-btn").click(function(){
$("p.normal").fadeOut();
$("p.fast").fadeOut("fast");
$("p.slow").fadeOut("slow");
$("p.very-fast").fadeOut(50);
$("p.very-slow").fadeOut(2000);
});
// Fading in hidden paragraphs with different speeds
$(".in-btn").click(function(){
$("p.normal").fadeIn();
$("p.fast").fadeIn("fast");
$("p.slow").fadeIn("slow");
$("p.very-fast").fadeIn(50);
$("p.very-slow").fadeIn(2000);
});
});
</script>

jQuery fadeToggle() Method


The jQuery fadeToggle() method display or hide the selected elements by animating their
opacity in such a way that if the element is initially displayed, it will be fade out; if hidden, it
will be fade in (i.e. toggles the fading effect).
<script> $(document).ready(function(){
// Toggles paragraphs display with fading
$(".toggle-btn").click(function(){
$("p").fadeToggle();
});
});
</script>
jQuery show() and hide() Methods
The hide() method simply sets the inline style display: none for the selected elements.
Conversely, the show() method restores the display properties of the matched set of elements
to whatever they initially were—typically block, inline, or inline-block—before the inline
style display: none was applied to them. Here's is an example.

<script>
$(document).ready(function(){
// Hide displayed paragraphs
$(".hide-btn").click(function(){
$("p").hide();
});
// Show hidden paragraphs
$(".show-btn").click(function(){
$("p").show();
});
});
</script>

You can optionally specify the duration (also referred as speed) parameter for making the
jQuery show hide effect animated over a specified period of time.
Durations can be specified either using one of the predefined string 'slow' or 'fast', or in a
number of milliseconds, for greater precision; higher values indicate slower animations.

<script>
$(document).ready(function(){
// Hide displayed paragraphs with different speeds
$(".hide-btn").click(function(){
$("p.normal").hide();
$("p.fast").hide("fast");
$("p.slow").hide("slow");
$("p.very-fast").hide(50);
$("p.very-slow").hide(2000);
});
// Show hidden paragraphs with different speeds
$(".show-btn").click(function(){
$("p.normal").show();
$("p.fast").show("fast");
$("p.slow").show("slow");
$("p.very-fast").show(50);
$("p.very-slow").show(2000);
});
});
</script>

jQuery toggle() Method


The jQuery toggle() method show or hide the elements in such a way that if the element is
initially displayed, it will be hidden; if hidden, it will be displayed (i.e. toggles the visibility).
<script>
$(document).ready(function(){
// Toggles paragraphs display
$(".toggle-btn").click(function(){
$("p").toggle();
});
});
</script>

Smooth Scrolling using JQuery


$(document).ready(function() {

var scrollLink = $('.scroll');

// Smooth scrolling
scrollLink.click(function(e) {
e.preventDefault();
$('body,html').animate({
scrollTop: $(this.hash).offset().top
}, 1000 );
});

// Active link switching


$(window).scroll(function() {
var scrollbarLocation = $(this).scrollTop();

scrollLink.each(function() {

var sectionOffset = $(this.hash).offset().top - 20;

if ( sectionOffset <= scrollbarLocation ) {


$(this).parent().addClass('active');
$(this).parent().siblings().removeClass('active');
}
})

})

})

Building an Image Slider


Image sliders are useful for showing multiple images with cool animations to catch a user's
attention. Having an image slider/slideshow is a very common functionality that you may
find on any website. Creating a simple image slider is pretty easy and it can be implemented
easily with jQuery. There are tons of plugins available for creating image sliders using
jQuery plugins, but one should be careful while using jQuery plugins as jQuery plugins
consumes bandwidth and may increase page load time. If things can be done with jQuery
code, one should not use any plugin. In this post, let’s see how to create simple image
slider using jQuery.
HTML Markup
First, let’s take a look at HTML markup. There is a parent div element and a child div
element which contains all the image tags. Here, the child div element tag will be used for
rotation of the images in the jQuery code.
<div id="sliderContainer">
<div id="sliderWrapper">
<img src="img/1.jpg" />
<img src="img/2.jpg" />
<img src="img/3.jpg" />
<img src="img/4.jpg" />
<img src="img/5.jpg" />
</div>
</div>
CSS
Below CSS code, used for parent slide container and for the individual images. This code will
set the width of slider container to 800 pixels. It’s important to note that overflow: hidden
property is applied to hide other images except the current one, otherwise all images would
be visible on the screen. One thing to also note here that if your images are greater than
800px then you may need to adjust the width property accordingly.

#sliderContainer {
width: 800px;
margin: 0;
padding: 0px;
position: relative;
overflow: hidden;
}
#sliderContainer .slider {
margin: 0;
padding: 0;
width: 800px;
float: left;
position: relative;
}

jQuery Code
First, define few variables.
The first variable curPos, indicates the current position and it is set to 0.
Second variable is slider which gets the references of all images with CSS class
“.slider” .
Third variable is cntImages, which gets the count of total number of images which are part of
slider.
And the fourth variable is sliderWidth, which gets the width of slider container.
There were 2 div element defined in the HTML markup sliderContainer and sliderWrapper.
The logic of creating image slider is, assign the total width to sliderWrapper which is
sliderWidth * cntImages. So in this case, this value comes to 4000px (800x5). But it
won’t be visible on the screen as parent element is having overflow:hidden property.
Next, create a function called SlideImage, which will be called by setInterval function with
delay of 2 seconds. This ensures that images rotates automatically. Inside this function,
First checks, if the current image is the last image. If yes, then set curPos variable to 0 so that
first image is shown again. And if not, then we increment the value of curPos variable.
To show next image as part of image slider, we play with the margin-left property of
sliderWrapper so that next image becomes part of slider visible area. We
use animate method of jQuery which provides us the slide animation. And we set
margin-left property to sliderWidth * (-curPos). So the value for image 2 would be -800,
-1600 for third image, -2400 for fourth image and -3200 for last image. And again back to 0
for first image. And that would make images to rotate.
Here is complete jQuery code.
$(function() {
var curPos = 0;
var slider = $('.slider');
var cntImages= slider.length;
var sliderWidth = slider.width();
$('#sliderWrapper').css('width', sliderWidth * cntImages);
setInterval(SlideImage, 2000);
function SlideImage() {
if (curPos == cntImages - 1)
curPos = 0;
else
curPos++;
$('#sliderWrapper').animate({
'marginLeft': sliderWidth * (-curPos)
});
}
});

Developing Client Side Quiz Application


Now create 3 files & follow the steps I have given below. File names are:
index.html
style.css
question.js
Index.html
Paste these codes are five below in index.html file you have created.
ex.html
XHTML
<!DOCTYPE html>
<!-- code by webdevtrick (https://webdevtrick.com) -->
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Quiz in JavaScript Webdevtrick.com</h1>
<hr style="margin-bottom: 20px">

<p id="question"></p>

<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
<button id="btn3"><span id="choice3"></span></button>
</div>

<hr style="margin-top: 50px">


<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>

<script src="question.js"></script>

</body>
</html>

le.css
CSS

/** code by webdevtrick (https://webdevtrick.com) **/


body {
background-color: #413D3D;
}

.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border: 2px solid #cbcbcb;

.grid h1 {
font-family: "sans-serif";
background-color: #01BBFF;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;

#score {
color: #01BBFF;
text-align: center;
font-size: 30px;
}

.grid #question {
font-family: "monospace";
font-size: 30px;
color: #01BBFF;
}

.buttons {
margin-top: 30px;
}

#btn0, #btn1, #btn2, #btn3 {


background-color: #01BBFF;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}

#btn0:hover, #btn1:hover, #btn2:hover, #btn3:hover {


cursor: pointer;
background-color: #01BBFF;
}

#btn0:focus, #btn1:focus, #btn2:focus, #btn3:focus {


outline: 0;
}

#progress {
color: #2b2b2b;
font-size: 18px;

// code by webdevtrick (https://webdevtrick.com)


function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}

Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}

Quiz.prototype.guess = function(answer) {
if(this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}

this.questionIndex++;
}

Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}

function Question(text, choices, answer) {


this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}

function populate() {
if(quiz.isEnded()) {
showScores();
}
else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;

// show options
var choices = quiz.getQuestionIndex().choices;
for(var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}

showProgress();
}
};

function guess(id, guess) {


var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};

function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " +
quiz.questions.length;
};

function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};

// create questions here


var questions = [
new Question("Hyper Text Markup Language Stand For?", ["JavaScript",
"XHTML","CSS", "HTML"], "HTML"),
new Question("Which language is used for styling web pages?", ["HTML", "JQuery",
"CSS", "XML"], "CSS"),
new Question("Which is not a JavaScript Framework?", ["Python Script",
"JQuery","Django", "NodeJS"], "Django"),
new Question("Which is used for Connect To Database?", ["PHP", "HTML", "JS",
"All"], "PHP"),
new Question("Webdevtrick.com is about..", ["Web Design", "Graphic Design", "SEO
& Development", "All"], "All")
];

// create quiz
var quiz = new Quiz(questions);

// display quiz
populate();

File Handling Import and Export Data


Excel is one of most popular file format used to store tabular data into spreadsheet.We can
use Excel format data to import and export data and stored into excel file.This jQuery
Datatables tutorial help to create export datatable to excel format using HTML5 and buttons
table tools. The excel file format are using .xls and .xlsx extension.
You can use this functionality only latest browsers and above IE8. The Buttons extension for
DataTables provides three plug-ins that provide overlapping functionality for data export.

HTML5 export buttons – makes use of HTML5 APIs to create files client-side
Flash export buttons – uses Adobe Flash for legacy browsers
Print button
You can also check other tutorials of export table data,
Exporting a DataTable into PDF File
Exporting a DataTable to CSV
DataTables Export to Excel using HTML5
Popular JavaScript and jQuery PDF Viewer Plugins
I am extending excelHtml5 so that you can use export to excel only on latest browser not on
legacy browser.I am explaining steps by step jQuery datatable export to excel tutorial, I am
extending previous tutorial that’s why i will change extension format and label from
previous Export jQuery datatable to pdf tutorial.
We have learn Export Datatable to CSV and Export Datatable to PDF in earlier datatables
tutorial, Now i am extending this datatables tutorial and adding export datatable to Excel file.
Exporting jQuery Datatables data to Excel File
Step 1: We need to include all datatables library files in head section of index.html file.

<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" type="text/css"
href="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,
b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.css"/>
<script type="text/javascript"
src="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmak

Step 2: Created HTML layout for jQuery datatables listing in index.html file.
<thead>
<tr>
<th>User ID</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>

Step 3: Fetched data from restful web service and processed data as required for jQuery
datatables.
var arrayReturn = [];
$.ajax({
url: "http://jsonplaceholder.typicode.com/posts",
async: true,
dataType: 'json',
success: function (data) {
for (var i = 0, len = data.length; i < len; i++) {
var desc = data[i].body;
var title = data[i].title;
var id = (data[i].id).toString();
arrayReturn.push([id, '<a href="http://google.com" target="_blank">'+title.substring(0,
20)+'</a>', desc.substring(0, 120)]);
}
inittable(arrayReturn);
}
});
Step 4: Now I will passed formatted data to jQuery datatables "aaData" property.

function inittable(data) {
$('#listing').DataTable({
"aaData": data,
"dom": 'lBfrtip',
buttons: [
{
extend: 'excelHtml5',
text: 'Export to Excel',
title: 'js-tutorials.com : Export to datatable data to Excel',
download: 'open',
orientation:'landscape',
exportOptions: {
columns: ':visible'
}
}] } ); }

XML Parsing
Parses a string into an XML document.
In web application response may be in the form of XML. With the help of that xml response
you are going to display your web contents.
Create Sample Xml String
In below example nothing special to explain . Here I have taken employee details xml
example and assigned to xml variable. First you need to parsexml using this code $xml =
$( $.parseXML( xml ) ); and then find the respected xml tag using find method.

1. <employees>
2. <employee id="1000">
3. <first_name>Yashwant</first_name>
4. <last_name>Chavan</last_name>
5. </employee>
6.
7. <employee id="2000">
8. <first_name>Mahesh</first_name>
9. <last_name>Divan</last_name>
10. </employee>
11. </employees>';
Complete Code to Parse Xml Suing Jquery

1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">


2. <html>
3. <head>
4. <scripttype="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
5. <script>
6. varxml='<employees><employee
id="1000"><first_name>Yashwant</first_name><last_name>Chavan</last_name></
employee><employee
id="2000"><first_name>Mahesh</first_name><last_name>Divan</last_name></em
ployee></employees>';
7.
8. $(document).ready(function () {
9. $xml = $( $.parseXML( xml ) );
10. $xml.find("employee").each(function(){
11. $("#container").append(" Employee Id:- " + $(this).attr("id"));
12. $("#container").append(" First Name:- " + $(this).find("first_name").text() + "<br
/>");
13. });
14. });
15. </script>
16. </HEAD>
17.
18. <body>
19. <div id="container"/>
20. </body>
21. </html>

JSON Parsing
Takes a well-formed JSON string and returns the resulting JavaScript value.
Passing in a malformed JSON string results in a JavaScript exception being thrown. For
example, the following are all invalid JSON strings:
 "{test: 1}" (test does not have double quotes around it).
 "{'test': 1}" ('test' is using single quotes instead of double quotes).
 "'test'" ('test' is using single quotes instead of double quotes).
 ".1" (a number must start with a digit; "0.1" would be valid).
 "undefined" (undefined cannot be represented in a JSON string; null, however, can be).
 "NaN" (NaN cannot be represented in a JSON string; direct representation of Infinity is
also not permitted).
The JSON standard does not permit "control characters" such as a tab or newline. An
example like $.parseJSON( '{ "testing":"1\t2\n3" }' ) will throw an error in most
implementations because the JavaScript parser converts the string's tab and newline escapes
into literal tab and newline; doubling the backslashes like "1\\t2\\n3" yields expected results.
This problem is often seen when injecting JSON into a JavaScript file from a server-side
language such as PHP.
Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse
the string. For details on the JSON format, see https://json.org/.
Prior to jQuery 1.9, $.parseJSON returned null instead of throwing an error if it was passed
an empty string, null, or undefined, even though those are not valid JSON.
Example
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

Animation using Javascript and Jquery


The .animate() method allows us to create animation effects on any numeric CSS property.
The only required parameter is a plain object of CSS properties. This object is similar to the
one that can be sent to the .css() method, except that the range of properties is more
restrictive.
Animation Properties and Values
All animated properties should be animated to a single numeric value, except as noted below;
most properties that are non-numeric cannot be animated using basic jQuery functionality
(For example, width, height, or left can be animated but background-color cannot be, unless
the jQuery.Color plugin is used). Property values are treated as a number of pixels unless
otherwise specified. The units em and % can be specified where applicable.
In addition to style properties, some non-style properties such as scrollTop and scrollLeft, as
well as custom properties, can be animated.
Shorthand CSS properties (e.g. font, background, border) are not fully supported. For
example, if you want to animate the rendered border width, at least a border style and border
width other than "auto" must be set in advance. Or, if you want to animate font size, you
would use fontSize or the CSS equivalent 'font-size' rather than simply 'font'.
In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'.
These shortcuts allow for custom hiding and showing animations that take into account the
display type of the element. In order to use jQuery's built-in toggle state tracking,
the 'toggle' keyword must be consistently given as the value of the property being animated.
Animated properties can also be relative. If a value is supplied with a
leading += or -= sequence of characters, then the target value is computed by adding or
subtracting the given number from the current value of the property.
Duration
Durations are given in milliseconds; higher values indicate slower animations, not faster ones.
The default duration is 400 milliseconds. The strings 'fast' and 'slow' can be supplied to
indicate durations of 200 and 600 milliseconds, respectively.
Callback Functions
If supplied, the start, step, progress, complete, done, fail, and always callbacks are called on
a per-element basis; this is set to the DOM element being animated. If no elements are in the
set, no callbacks are called. If multiple elements are animated, the callback is executed once
per matched element, not once for the animation as a whole. Use the .promise() method to
obtain a promise to which you can attach callbacks that fire once for an animated set of any
size, including zero elements.
Basic Usage

To animate any element, such as a simple image:


<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123"
style="position: relative; left: 10px;">
To animate the opacity, left offset, and height of the image simultaneously:
$( "#clickme" ).click(function() {
$( "#book" ).animate({
opacity: 0.25,
left: "+=50",
height: "toggle"
}, 5000, function() {
// Animation complete.
});
});

Note that the target value of the height property is 'toggle'. Since the image was visible before,
the animation shrinks the height to 0 to hide it. A second click then reverses this transition:
The opacity of the image is already at its target value, so this property is not animated by the
second click. Since the target value for left is a relative value, the image moves even farther
to the right during this second animation.
Directional properties (top, right, bottom, left) have no discernible effect on elements if
their position style property is static, which it is by default.
Step Function
The second version of .animate() provides a step option — a callback function that is fired at
each step of the animation. This function is useful for enabling custom animation types or
altering the animation as it is occurring. It accepts two arguments (now and fx), and this is set
to the DOM element being animated.
now: the numeric value of the property being animated at each step
fx: a reference to the jQuery.fx prototype object, which contains a number of properties
such as elem for the animated element, start and end for the first and last value of the
animated property, respectively, and prop for the property being animated.
For example, given two list items, the step function fires four times at each step of the
animation:
$( "li" ).animate({
opacity: .5,
height: "50%"
}, {
step: function( now, fx ) {
var data = fx.elem.id + " " + fx.prop + ": " + now;
$( "body" ).append( "<div>" + data + "</div>" );
}
});

Easing
The remaining parameter of .animate() is a string naming an easing function to use. An
easing function specifies the speed at which the animation progresses at different points
within the animation. The only easing implementations in the jQuery library are the default,
called swing, and one that progresses at a constant pace, called linear. More easing functions
are available with the use of plug-ins, most notably the jQuery UI suite.
Per-property Easing
As of jQuery version 1.4, you can set per-property easing functions within a
single .animate() call. In the first version of .animate(), each property can take an array as its
value: The first member of the array is the CSS property and the second member is an easing
function. If a per-property easing function is not defined for a particular property, it uses the
value of the .animate() method's optional easing argument. If the easing argument is not
defined, the default swing function is used.
For example, to simultaneously animate the width and height with the swing easing function
and the opacity with the linear easing function:
$( "#clickme" ).click(function() {
$( "#book" ).animate({
width: [ "toggle", "swing" ],
height: [ "toggle", "swing" ],
opacity: "toggle"
}, 5000, "linear", function() {
$( this ).after( "<div>Animation complete.</div>" );
});
});
UNIT - IV

CSS Frameworks - Saas framework

SASS Based CSS Framework


Why do you need a CSS framework?
Faster Web Development: If you are a beginner you will require more time to develop than
skilled people. In this case, a framework will help the beginner to develop faster as it requires
minimal coding skills and comes with many useful widgets. Frameworks not only help
non-skilled people but it also helps skilled people. When you use a framework, there is no
need to write code from scratch every-time. With a framework your time will be saved and
you can do whatever you want in this free time.
Creative Responsive Design: Your developed site should render properly across all types of
devices. Because different people use different devices and if your site doesn’t load correctly
on a single device, you might lose your valuable traffic. A framework that supports
responsive web design will save your time and you will be able to develop without any
worry.
Producing Prototypes: To speed up the design and development process, prototype and
wireframes help a lot. You can produce prototypes and wireframes very much faster with a
framework.

Bulma
Bulma is one of the free open source CSS framework that is based on Flexbox. Now it has
become widely popular and more than 150000 developers are using this framework without
any worries. This framework is meant to include only the minimum requirements to get you
started on your web development project. This lightweight framework is absolutely
responsive and based on a 12 column grid system. If you are a newbie then you can learn
very easier and faster with Bulma. In case of problems, a huge community is available for
this framework.
Once you know how to use Bulma, you can quickly customize your website. This framework
has 33.3K stars on github repo and updated very frequently.
Pros:
Very quick to customize.
It integrates in any JS environment.
Cons:
CSS only - doesn’t include any JS or jQuery plugins.
UIKIT
UIKIT is a very lightweight and highly modular front-end framework that helps to develop
powerful and fast web interfaces. This mighty fact that includes in this framework is, it
includes both Sass and LESS CSS preprocessors.
UIKit has become one of the most popular front-end frameworks out there with an array of
nimble responsive components with consistent naming conventions. This framework comes
with more than 30+ extendable, modular components which can be combined for even more
versatility.
It includes elements like HTML forms and tables; navigation components like side
navigation bars; JavaScript components like modal dialogs and off-canvas bars; common
elements like badges, buttons, and overlays; and layout components with an entirely
responsive grid system.
Currently, UIKIT has 14k stars in github repository and updated regularly.
Pros:
Outstandingly modular, so that you can add components to the stylesheet without
negatively impacting your overall style.
Highly customizable.
Create advanced user interfaces with components like nestables.
Cons:
The number of resources is very low due to relative newness.

Bootstrap
incomplete without the most popular, faster and user-friendly framework, Bootstrap. This
framework is released in 2011 and created by Twitter developers. Currently, there are
millions of amazing websites across the web that are running this amazing framework. You
can check its popularity by counting its stars at GitHub repo, its more than 131K.
Like the all other effective front-end frameworks, Bootstrap includes HTML, CSS, and
JavaScript. You can easily develop responsive sites of all sizes and complexities. As this
framework is updated regularly, it always includes the best and latest features.
Quickly build your entire app or prototype your ideas with Bootstraps Sass variables and
mixins. Earlier it was based on LESS but as the popularity is increasing to SASS, Bootstrap
made its version 4 in SASS. Our classic version of Quix Joomla page builder is built with
Bootstrap version 3, which is based on LESS.
Pros:
Extensive documentation.
Responsive web design support, which can also be disabled if required.
Cons:
An immoderate number of DOM elements and HTML classes can be confusing and
messy.
Out of the box file size of 276kB due to an excessive number of rarely used styles.
Foundation
Foundation framework is one of the highly advanced frameworks that has been created by a
web design company called Zurb. It is an enterprise grade front end framework that is ideal
for developing a responsive website, nimbles. Many popular organizations like FaceBook,
eBay, Mozilla, Adobe, hp, Cisco, Disney, and other popular organizations use this framework
on their sites.
If you are a newbie than definitely, this is not the framework you are looking for. It is fairly
complex and not suitable for persons who are unknown with frameworks. If you have earlier
experience, you can easily design beautiful apps, emails, and websites that will look
mindblowing on any device. Foundation is readable, flexible, semantic and entirely
customizable.
Foundation comes with GPU acceleration for lightning fast and smooth animations. It offers
Fastclick.js for fast rendering at mobile devices. This versatile framework runs on Sass
preprocessor and includes data interchange attribute that is developed by Foundation.
This attribute lets you load heavier HTML sections for larger screens and lightweight HTML
sections for mobile screens. Currently, this framework has more than 28K stars in the GitHub
repository with a big user community.
Pros:
Great flexibility as no style lock-in.
Instead of pixels uses REMS, eliminates the need of explicitly state height, width and
other attributes for each device.
Cons:
Size is fairly big out of the box.
A bit of complex for the beginners.

Materialize
Materialize is a responsive, modern front-end development framework that is based on
Google’s material design specifications. This framework comes with ready to use icons,
buttons, forms, cards, and other components. It is offered in both standard version and one
that runs on SASS, use any that you like.
The convenient IZ column grid feature is included with Materialize so that it can be used for
website layouts. This framework is loaded with CSS, which is ready to use out of the box for
material design colors, shadows, typography, and other features.
Additional features of this framework include drag out mobile menus, SASS mixins, ripple
effect animation and more. This framework is rated with 35K+ stars on the GitHub
repository. Pros:
A huge number of components.
Support for all types of devices.
Cons:
Very large size.
No flexbox model support.

CSS Preprocessors
A CSS preprocessor is a program that lets you generate CSS from the preprocessor's own
unique syntax. There are many CSS preprocessors to choose from, however most CSS
preprocessors will add some features that don't exist in pure CSS, such as mixin, nesting
selector, inheritance selector, and so on. These features make the CSS structure more
readable and easier to maintain.
Sass is a stylesheet language that’s compiled to CSS. It allows you to use variables, nested
rules, mixins, functions, and more, all with a fully CSS-compatible syntax. Sass helps keep
large stylesheets well-organized and makes it easy to share design within and across projects.
 If you’re looking for an introduction to Sass, check out the tutorial.
 If you want to look up a built-in Sass function, look no further than the built-in module
reference.
 If you’re calling Sass from JavaScript, you may want the JS API documentation.
 Or the Dart API documentation if you’re calling it from Dart.
 Otherwise, use the table of contents for the language reference!

Introduction and Basics - Setup


Sass supports two different syntaxes. Each one can load the other, so it's up to you and your
team which one to choose.
The Indented Syntax
The indented syntax was Sass’s original syntax, and so it uses the file extension .sass.
Because of this extension, it’s sometimes just called “Sass”. The indented syntax supports all
the same features as SCSS, but it uses indentation instead of curly braces and semicolons to
describe the format of the document.
In general, any time you’d write curly braces in CSS or SCSS, you can just indent one level
deeper in the indented syntax. And any time a line ends, that counts as a semicolon. There are
also a few additional differences in the indented syntax that are noted throughout
the reference.
The indented syntax looks like this:
@mixin button-base()
@include typography(button)
@include ripple-surface
@include ripple-radius-bounded

display: inline-flex
position: relative
height: $button-height
border: none
vertical-align: middle

&:hover
cursor: pointer

&:disabled
color: $mdc-button-disabled-ink-color
cursor: default
pointer-events: none

Variables
Sass variables are simple: you assign a value to a name that begins with $, and then you can
refer to that name instead of the value itself. But despite their simplicity, they're one of the
most useful tools Sass brings to the table. Variables make it possible to reduce repetition, do
complex math, configure libraries, and much more.
A variable declaration looks a lot like a property declaration: it’s written <variable>:
<expression>. Unlike a property, which can only be declared in a style rule or at-rule,
variables can be declared anywhere you want. To use a variable, just include it in a value.

$base-color: #c6538c
$border-dark: rgba($base-color, 0.88)
.alert
border: 1px solid $border-dark

Default Values
Normally when you assign a value to a variable, if that variable already had a value, its old
value is overwritten. But if you’re writing a Sass library, you might want to allow your users
to configure your library’s variables before you use them to generate CSS.
To make this possible, Sass provides the !default flag. This assigns a value to a variable only
if that variable isn’t defined or its value is null. Otherwise, the existing value will be used.

Built-in Variables
Variables that are defined by a built-in module cannot be modified.
@use "sass:math" as math;
// This assignment will fail.math.$pi: 0;
Operators
Sass supports a handful of useful operators for working with different values. These include
the standard mathematical operators like + and *, as well as operators for various other types:
 == and != are used to check if two values are the same.
 +, -, *, /, and % have their usual mathematical meaning for numbers, with special
behaviors for units that matches the use of units in scientific math.
 <, <=, >, and >= check whether two numbers are greater or less than one another.
 and, or, and not have the usual boolean behavior. Sass considers every value “true”
except for false and null.
 +, -, and / can be used to concatenate strings.

Order of Operations
Sass has a pretty standard order of operations, from tightest to loosest:
 The unary operators not, +, -, and /.
 The *, /, and % operators.
 The + and - operators.
 The >, >=, < and <= operators.
 The == and != operators.
 The and operator.
 The or operator.
 The = operator, when it’s available.

Equality Operators
The equality operators return whether or not two values are the same. They’re
written <expression> == <expression>, which returns whether two expressions are equal,
and <expression> != <expression>, which returns whether two expressions are not equal.
Two values are considered equal if they’re the same type and the same value, which means
different things for different types:
 Numbers are equal if they have the same value and the same units, or if their values are
equal when their units are converted between one another.
 Strings are unusual in that unquoted and quoted strings with the same contents are
considered equal.
 Colors are equal if they have the same red, green, blue, and alpha values.
 Lists are equal if their contents are equal. Comma-separated lists aren’t equal to
space-separated lists, and bracketed lists aren’t equal to unbracketed lists.
 Maps are equal if their keys and values are both equal.
 true, false, and null are only equal to themselves.
 Functions are equal to the same function. Functions are compared by reference, so even
if two functions have the same name and definition they’re considered different if they
aren’t defined in the same place.
Example
@debug 1px == 1px // true@debug 1px != 1em

Relational Operators
Relational operators determine whether numbers are larger or smaller than one another. They
automatically convert between compatible units.
 <expression> < <expression> returns whether the first expression’s value is less than
the second’s.
 <expression> <= <expression> returns whether the first expression’s value is less than or
equal to the second’s.
 <expression> > <expression> returns whether the first expression’s value is greater than
to the second’s.
 <expression> >= <expression>, returns whether the first expression’s value is greater
than or equal to the second’s.

Example
@debug 100 > 50 // true
@debug 10px < 17px // true
@debug 96px >= 1in // true
@debug 1000ms <= 1s // true

Numeric Operators
Sass supports the standard set of mathematical operators for numbers. They automatically
convert between compatible units.
<expression> + <expression> adds the first expression’s value to the second’s.
<expression> - <expression> subtracts the first expression’s value from the second’s.
<expression> * <expression> multiplies the first expression’s value by the second’s.
<expression> / <expression> divides the first expression’s value by the second’s.
<expression> % <expression> returns the remainder of the first expression’s value
divided by the second’s. This is known as the modulo operator.

Example
@debug 10s + 15s // 25s
@debug 1in - 10px // 0.8958333333in
@debug 5px * 3px // 15px*px
@debug (12px/4px) // 3
@debug 1in % 9px // 0.0625in
String Operators
Sass supports a few operators that generate strings:
<expression> + <expression> returns a string that contains both expressions’ values. If
the either value is a quoted string, the result will be quoted; otherwise, it will be unquoted.
<expression> / <expression> returns an unquoted string that contains both expressions’
values, separated by /.
<expression> - <expression> returns an unquoted string that contains both expressions’
values, separated by -. This is a legacy operator, and interpolation should generally be
used instead.

Example
@debug "Helvetica" + " Neue" // "Helvetica Neue"
@debug sans- + serif // sans-serif
@debug #{10px + 5px} / 30px // 15px/30px
@debug sans - serif // sans-serif

These operators don’t just work for strings! They can be used with any values that can be
written to CSS, with a few exceptions:
 Numbers can’t be used as the left-hand value, because they have their own operators.
 Colors can’t be used as the left-hand value, because they used to have their own
operators.
@debug "Elapsed time: " + 10s // "Elapsed time: 10s";
@debug true + " is a boolean value" // "true is a boolean value";

Boolean Operators
Unlike languages like JavaScript, Sass uses words rather than symbols for
its boolean operators.
not <expression> returns the opposite of the expression’s value:
it turns true into false and false into true.
<expression> and <expression> returns true if both expressions’ values are true,
and false if either is false.
<expression> or <expression> returns true if either expression’s value is true, and false if
both are false.
Example
@debug not true // false
@debug not false // true
@debug true and true // true
@debug true and false // false
@debug true or false // true
@debug false or false // false
Funtions
Functions can be values too! You can’t directly write a function as a value, but you can pass a
function’s name to the [meta.get-function() function][] to get it as a value. Once you have a
function value, you can pass it to the meta.call() function to call it. This is useful for
writing higher-order functions that call other functions.
@use "sass:list"@use "sass:meta"@use "sass:string"
/// Return a copy of $list with all elements for which $condition returns `true`
/// removed.@function remove-where($list, $condition)
$new-list: ()
$separator: list.separator($list)
@each $element in $list
@if not meta.call($condition, $element)
$new-list: list.append($new-list, $element, $separator: $separator)

@return $new-list

$fonts: Tahoma, Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif


content
@function contains-helvetica($string)
@return string.index($string, "Helvetica")

font-family: remove-where($fonts, meta.get-function("contains-helvetica"))

Arguments
Arguments allow functions’ behavior to be customized each time they’re called. The
arguments are specified in the @function rule after the function’s name, as a list of variable
names surrounded by parentheses. The function must be called with the same number of
arguments in the form of SassScript expressions. The values of these expression are available
within the function’s body as the corresponding variables.
Optional Arguments
Normally, every argument a function declares must be passed when that function is included.
However, you can make an argument optional by defining a default value which will be used
if that arguments isn’t passed. Default values use the same syntax as variable declarations:
the variable name, followed by a colon and a SassScript expression. This makes it easy to
define flexible function APIs that can be used in simple or complex ways.
@function invert($color, $amount: 100%)
$inverse: change-color($color, $hue: hue($color) + 180)
@return mix($inverse, $color, $amount)
$primary-color: #036.header
background-color: invert($primary-color, 80%)

Keyword Arguments
When a function is called, arguments can be passed by name in addition to passing them by
their position in the argument list. This is especially useful for functions with multiple
optional arguments, or with boolean arguments whose meanings aren’t obvious without a
name to go with them. Keyword arguments use the same syntax as variable
declarations and optional arguments.
$primary-color: #036.banner
background-color: $primary-color
color: scale-color($primary-color, $lightness: +40%)
Taking Arbitrary Arguments
Sometimes it’s useful for a function to be able to take any number of arguments. If the last
argument in a @function declaration ends in ..., then all extra arguments to that function are
passed to that argument as a list. This argument is known as an argument list
@function sum($numbers...)
$sum: 0
@each $number in $numbers
$sum: $sum + $number

@return $sum

.micro
width: sum(50px, 30px, 100px)
Taking Arbitrary Keyword Arguments
Argument lists can also be used to take arbitrary keyword
arguments. The meta.keywords() function takes an argument list and returns any extra
keywords that were passed to the function as a map from argument names (not including $)
to those arguments’ values.
Passing Arbitrary Arguments
Just like argument lists allow functions to take arbitrary positional or keyword arguments, the
same syntax can be used to pass positional and keyword arguments to a function. If you pass
a list followed by ... as the last argument of a function call, its elements will be treated
as additional positional arguments. Similarly, a map followed by ... will be treated as
additional keyword arguments. You can even pass both at once!
@return
The @return at-rule indicates the value to use as the result of calling a function. It’s only
allowed within a @function body, and each @function must end with a @return.
When a @return is encountered, it immediately ends the function and returns its result.
Returning early can be useful for handling edge-cases or cases where a more efficient
algorithm is available without wrapping the entire function in an @else block.
@use "sass:string"
@function str-insert($string, $insert, $index)
// Avoid making new strings if we don't need to. @if string.length($string) == 0
@return $insert

$before: string.slice($string, 0, $index)


$after: string.slice($string, $index)
@return $before + $insert + $after

Types of Functions
CSS defines many functions, and most of them work just fine with Sass’s normal function
syntax. They’re parsed as function calls, resolved to plain CSS functions, and compiled as-is
to CSS. There are a few exceptions, though, which have special syntax that can’t just be
parsed as a SassScript expression. All special function calls return unquoted strings
url()
The url() function is commonly used in CSS, but its syntax is different than other functions:
it can take either a quoted or unquoted URL. Because an unquoted URL isn’t a valid
SassScript expression, Sass needs special logic to parse it.
If the url()’s argument is a valid unquoted URL, Sass parses it as-is,
although interpolation may also be used to inject SassScript values. If it’s not a valid
unquoted URL—for example, if it contains variables or function calls—it’s parsed as a
normal plain CSS function call.
$roboto-font-path: "../fonts/roboto"
@font-face
// This is parsed as a normal function call that takes a quoted string.
src: url("#{$roboto-font-path}/Roboto-Thin.woff2") format("woff2")

font-family: "Roboto"
font-weight: 100

calc(), element(), progid:...(), and expression()


The calc() and element() functions are defined in the CSS spec. Because calc()’s
mathematical expressions conflict with Sass’s arithmetic, and element()’s IDs could be
parsed as colors, they need special parsing.
expression() and functions beginning with progid: are legacy Internet Explorer features that
use non-standard syntax. Although they’re no longer supported by recent browsers, Sass
continues to parse them for backwards compatibility.
Sass allows any text in these function calls, including nested parentheses. Nothing is
interpreted as a SassScript expression, with the exception that interpolation can be used to
inject dynamic values.
.logo
$width: 800px
width: $width
position: absolute
left: calc(50% - #{$width / 2})
top: 0
min() and max()
CSS added support for min() and max() functions in Values and Units Level 4, from where
they were quickly adopted by Safari to support the iPhoneX. But Sass supported its
own min() and max() functions long before this, and it needed to be backwards-compatible
with all those existing stylesheets. This led for the need for extra-special syntactic cleverness.
If a min() or max() function call is valid plain CSS, it will be compiled to
a CSS min() or max() call. “Plain CSS” includes nested calls to calc(), env(), var(), min(),
or max(), as well as interpolation. As soon as any part of the call contains a SassScript feature
like variables or function calls, though, it’s parsed as a call to Sass’s
core min() or max() function instead.

$padding: 12px
.post
// Since these max() calls don't use any Sass features other than
// interpolation, they're compiled to CSS max() calls.
padding-left: max(#{$padding}, env(safe-area-inset-left))
padding-right: max(#{$padding}, env(safe-area-inset-right))

.sidebar
// Since these refer to a Sass variable without interpolation, they call
// Sass's built-in max() function.
padding-left: max($padding, 20px)
padding-right: max($padding, 20px)

Inheritance
The @extend directive lets you share a set of CSS properties from one selector to another.
The @extend directive is useful if you have almost identically styled elements that only differ
in some small details.
The following Sass example first creates a basic style for buttons (this style will be used for
most buttons). Then, we create one style for a "Report" button and one style for a "Submit"
button. Both "Report" and "Submit" button inherit all the CSS properties from
the .button-basic class, through the @extend directive. In addition, they have their own colors
defined:
.button-basic {
border: none;
padding: 15px 30px;
text-align: center;
font-size: 16px;
cursor: pointer;
}

.button-report {
@extend .button-basic;
background-color: red;
}

.button-submit {
@extend .button-basic;
background-color: green;
color: white;
}
By using the @extend directive, you do not need to specify several classes for an element in
your HTML code, like this: <button class="button-basic button-report">Report this</button>.
You just need to specify .button-report to get both sets of styles.
The @extend directive helps keep your Sass code very DRY.

Media Queris
What are media queries and why should I care?
If you've ever created a print style sheet you've used media-specific CSS. In that case you
called a separate CSS file just for print by setting the media attribute of a link:
<link rel="stylesheet" href="paper.css" media="print" />
This gave us some control over media types, but that's it. Then CSS3 introduced the concept
of using a query in that space as well. You can add your query in the <link> tag, or join the
cool kids and use the @media rule in CSS. More on that later.
First let's look at what kind of queries we can write. If you look at the W3C Spec you'll see a
dazzling array of different properties you can check. The ones I'm most interested in are the
ones concerning width, height, orientation, and ratio. By swapping out different rules based
on these properties you can change the size and shape of your design to truly fit the viewing
area.
Here's a simple query in the <link> tag that will load a css file for small screens.
<link rel="stylesheet" media="screen and (max-width: 480px)" href="small.css" />
This is great, but if we want to manage a lot of different options these files can add up
quickly. Fortunately we have the @media rule. You can use these inside any CSS file to
apply specific rules only when the query expression is true.
Here I'm setting the font-size of an <h1> to be larger on a large screen.
// set a variable for the font size$h1-size: 36px
h1 {
font-size: $h1-size;}
// this will only affect wide screens@media screen and (min-width: 1024px) {
h1 {
font-size: $h1-size * 1.5;
}}
Which compiles to:
h1 {
font-size: 36px;}@media screen and (min-width: 1024px) {
h1 {
font-size: 54px;
}}
You can use these in Sass just fine, and inside a query you can use all the Sass features you
like. In the above example I used and manipulated a variable. You should note, however, that
you can't use variables in the query declaration itself. It would be nice to write the following,
but it won't work.
$breakpoint: 1024px;
@media screen and (min-width: $breakpoint) {
content: "this won't work :(";}
@media Bubbling
Sass does provide what I consider to be a pretty killer feature for authoring @media when
you nest them inside other selectors. If you add a @media query by nesting it inside a
selector Sass will "bubble" that @media query and the new rule outside of the nest and back
out to the root of your style sheet.
I use @media un-nested (as mentioned above) when I'm setting up large-scale changes like a
responsive master grid, but I find that I need to make small adjustments much more often.
For example, lets say you have a profile picture that looks great large and floated to the left
on a desktop, but needs to shrink on a smaller screen. It also needs to stop floating on a really
wide screen.
In Sass we can write that like this.
.profile-pic {
float: left;
width: 250px;
@media screen and (max-width: 320px) {
width: 100px;
}
@media screen and (min-width: 1200px) {
float: none;
}}
Sass will see this and know that you want to apply that query to the selector it's nested in. It
compiles to CSS like so:
.profile-pic {
float: left;
width: 250px;}@media screen and (max-width: 320px) {
.profile-pic {
width: 100px;
}}@media screen and (min-width: 1200px) {
.profile-pic {
float: none;
}}

Mixins - Partials
Mixins allow you to define styles that can be re-used throughout your stylesheet. They make
it easy to avoid using non-semantic classes like .float-left, and to distribute collections of
styles in libraries.
Mixins are defined using the @mixin at-rule, which is written @mixin <name>
{ ... } or @mixin name(<arguments...>) { ... }. A mixin’s name can be any Sass identifier,
and it can contain any statement other than top-level statements. They can be used to
encapsulate styles that can be dropped into a single style rule; they can contain style rules of
their own that can be nested in other rules or included at the top level of the stylesheet; or
they can just serve to modify variables.
Mixins are included into the current context using the @include at-rule, which is
written @include <name> or @include <name>(<arguments...>), with the name of the mixin
being included.
Example
@mixin reset-list
margin: 0
padding: 0
list-style: none

@mixin horizontal-list
@include reset-list

li
display: inline-block
margin:
left: -2px
right: 2em
nav ul
@include horizontal-list
UNIT - V

Less framework

Scaling Scrum starts with understanding standard one-team Scrum. From that point, your
organization must be able to understand and adopt LeSS, which requires examining the
purpose of one-team Scrum elements and figuring out how to reach the same purpose while
staying within the constraints of the standard Scrum rules.
Agile development with Scrum requires a deep organizational change to become agile.
Therefore, neither Scrum nor LeSS should be considered as merely a practice. Rather, they
form an organizational design framework.
Two Agile Scaling Frameworks
LeSS provides two different large-scale Scrum frameworks. Most of the scaling elements of
LeSS are focused on directing the attention of all of the teams onto the whole product instead
of “my part.” Global and “end-to-end” focus are perhaps the dominant problems to solve in
scaling. The two frameworks – which are basically single-team Scrum scaled up – are:
 LeSS: Up to eight teams (of eight people each).
 LeSS Huge: Up to a few thousand people on one product.
What does it mean to be the same as One-Team Scrum?
LeSS is a scaled up version of one-team Scrum, and it maintains many of the practices and
ideas of one-team Scrum. In LeSS, you will find:
 a single Product Backlog (because it’s for a product, not a team),
 one Definition of Done for all teams,
 one Potentially Shippable Product Increment at the end of each Sprint,
 one Product Owner,
 many complete, cross-functional teams (with no single-specialist teams),
 one Sprint.
In LeSS all Teams are in a common Sprint to deliver a common shippable product, every
Sprint.
What’s Different in LeSS?
 Sprint Planning Part 1: In addition to the one Product Owner, it includes people from all
teams. Let team members self-manage to decide their division of Product Backlog Items.
Team members also discuss opportunities to find shared work and cooperate, especially
for related items.
 Sprint Planning Part 2: This is held independently (and usually in parallel) by each Team,
though sometimes for simple coordination and learning two or more Teams may hold it
in the same room (in different areas).
 Daily Scrum: This is also held independently by each Team, though a member of Team
A may observe Team B’s Daily Scrum, to increase information sharing.
 Coordination: Just Talk, Communicate in Code, Travelers, Open Space, and
Communities.
 Overall PBR: There may be an optional and short overall Product Backlog Refinement
(PBR) meeting that includes the one Product Owner and people from all teams. The key
purpose is to decide which teams are likely to implement which items and therefore
select those items for later in-depth single-team PBR. It is also a chance to increase
alignment with the Product Owner and all teams.
 Product Backlog Refinement: The only requirement in LeSS is single-team PBR, the
same as in one-team Scrum. But a common and useful variation is multi-team PBR,
where two or more Teams are in the same room together, to increase learning and
coordination.
 Sprint Review: In addition to the one Product Owner, it includes people from all teams,
and relevant customers/users and other stakeholders. For the phase of inspecting the
product increment and new items, consider a “bazaar” or “science fair” style: a large
room with multiple areas, each staffed by team members, where the items developed by
teams are shown and discussed.
 Overall Retrospective: This is a new meeting not found in one-team Scrum, and its
purpose is to explore improving the overall system, rather than focusing on one Team.
The maximum duration is 45 minutes per week of Sprint. It includes the Product Owner,
Scrum Masters, and rotating representatives from each Team.

Introduction and Basics


Less (which stands for Leaner Style Sheets) is a backwards-compatible language extension
for CSS. This is the official documentation for Less, the language and Less.js, the JavaScript
tool that converts your Less styles to CSS styles.
Because Less looks just like CSS, learning it is a breeze. Less only makes a few convenient
additions to the CSS language, which is one of the reasons it can be learned so quickly.
 For detailed documentation on Less language features, see Features
 For a list of Less Built-in functions, see Functions
 For detailed usage instructions, see Using Less.js
 For third-party tools for Less, see Tools

Variables
These are pretty self-explanatory:
@width: 10px;@height: @width + 10px;
#header {
width: @width;
height: @height;
}
Outputs:
#header {
width: 10px;
height: 20px;
}
It's not uncommon to see the same value repeated dozens if not hundreds of times across your
stylesheets:
a,.link {
color: #428bca;
}.widget {
color: #fff;
background: #428bca;
}
Variables make your code easier to maintain by giving you a way to control those values
from a single location:
// Variables@link-color: #428bca; // sea blue@link-color-hover:
darken(@link-color, 10%);
// Usagea,.link {
color: @link-color;
}a:hover {
color: @link-color-hover;
}.widget {
color: #fff;
background: @link-color;
}
Variable Interpolation
The examples above focused on using variables to control values in CSS rules, but they can
also be used in other places as well, such as selector names, property names, URLs
and @import statements.
Selectors
v1.4.0
// Variables@my-selector: banner;
// Usage.@{my-selector} {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}
Compiles to:
.banner {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}

Variable Variables
In Less, you can define a variable's name using another variable.
@primary: green;@secondary: blue;
.section {
@color: primary;

.element {
color: @@color;
}
}
Which compiles to:
.section .element {
color: green;
}
Lazy Evaluation
Variables do not have to be declared before being used.
Valid Less snippet:
.lazy-eval {
width: @var;
}
@var: @a;@a: 9%;
this is valid Less too:
.lazy-eval {
width: @var;
@a: 9%;
}
@var: @a;@a: 100%;
both compile into:
.lazy-eval {
width: 9%;
}
When defining a variable twice, the last definition of the variable is used, searching from the
current scope upwards. This is similar to css itself where the last property inside a definition
is used to determine the value.
For instance:
@var: 0;.class {
@var: 1;
.brass {
@var: 2;
three: @var;
@var: 3;
}
one: @var;
}
Compiles to:
.class {
one: 1;
}.class .brass {
three: 3;
}
Essentially, each scope has a "final" value, similar to properties in the browser, like this
example using custom properties:
.header {
--color: white;
color: var(--color); // the color is black
--color: black;
}
This means that, unlike other CSS pre-processing languages, Less variables behave very
much like CSS's.
Properties as Variables (NEW!)
v3.0.0
You can easily treat properties like variables using the $prop syntax. Sometimes this can
make your code a little lighter.
.widget {
color: #efefef;
background-color: $color;
}
Compiles to:
.widget {
color: #efefef;
background-color: #efefef;
}
Note that, like variables, Less will choose the last property within the current/parent scope as
being the "final" value.
.block {
color: red;
.inner {
background-color: $color;
}
color: blue;
}
Compiles to:
.block {
color: red;
color: blue;
} .block .inner {
background-color: blue;
}

Default Variables
We sometimes get requests for default variables - an ability to set a variable only if it is not
already set. This feature is not required because you can easily override a variable by putting
the definition afterwards.
For instance:
// library@base-color: green;@dark-color: darken(@base-color, 10%);
// use of library@import "library.less";@base-color: red;
This works fine because of Lazy Loading - @base-color is overridden and @dark-color is a
dark red.
Functions
Less provides a variety of functions which transform colors, manipulate strings and do maths.
They are documented fully in the function reference.
Using them is pretty straightforward. The following example uses percentage to convert 0.5
to 50%, increases the saturation of a base color by 5% and then sets the background color to
one that is lightened by 25% and spun by 8 degrees:
@base: #f04615;@width: 0.5;
.class {
width: percentage(@width); // returns `50%`
color: saturate(@base, 5%);
background-color: spin(lighten(@base, 25%), 8);
}

Types of Functions
Logical Functions
if
Returns one of two values depending on a condition.
Parameters:
condition: A boolean expression
value1: A value returned if condition is true.
value2: A value returned if condition is not true.
Released: v3.0.0 Updated: v3.6.0
Examples:
@some: foo;
div {
margin: if((2 > 1), 0, 3px);
color: if((iscolor(@some)), darken(@some, 10%), black);
}
Result:
div {
margin: 0;
color: black;
}
A boolean expression supported as the conditional parameter are the same as of Guard
Statements.
if(not (true), foo, bar);
if((true) and (2 > 1), foo, bar);
if((false) or (isstring("boo!")), foo, bar);
before Less 3.6, the condition required a set of parentheses.
if(2 > 1, blue, green); // Causes an error in 3.0-3.5.3
if((2 > 1), blue, green); // Ok 3.0+
boolean
Evaluates to true or false
You can "store" a boolean test for later evaluation in a guard or if().
Parameters:
condition: A boolean expression
Released: v3.0.0 Updated: v3.6.0
Examples:
@bg: black;@bg-light: boolean(luma(@bg) > 50%);
div {
background: @bg;
color: if(@bg-light, black, white);
}
Result:
div {
background: black;
color: white;
}

String Functions
Applies URL-encoding to special characters found in the input string.
These characters are not encoded: ,, /, ?, @, &, +, ', ~, ! and $.
Most common encoded characters are: \<space\>, #, ^, (, ), {, }, |, :, >, <, ;, ], [ and =.
Parameters: string: a string to escape.
Returns: escaped string content without quotes.
Example:
escape('a=1')
Output:
a%3D1
If the parameter is not a string, output is not defined. The current implementation
returns undefined on color and unchanged input on any other kind of argument. This behavior
should not be relied on and may change in the future.
String escaping.
It expects string as a parameter and return its content as is, but without quotes. It can be used
to output CSS value which is either not valid CSS syntax, or uses proprietary syntax which
Less doesn't recognize.
Parameters: string - a string to escape.
Returns: string - the escaped string, without quotes.
Example:
@mscode: "ms:alwaysHasItsOwnSyntax.For.Stuff()"
filter: e(@mscode);
Output:
filter: ms:alwaysHasItsOwnSyntax.For.Stuff();
% format
The function %(string, arguments ...) formats a string.
The first argument is string with placeholders. All placeholders start with percentage
symbol % followed by letter s,S,d,D,a, or A. Remaining arguments contain expressions to
replace placeholders. If you need to print the percentage symbol, escape it by another
percentage %%.
Use uppercase placeholders if you need to escape special characters into their utf-8 escape
codes. The function escapes all special characters except ()'~!. Space is encoded as %20.
Lowercase placeholders leave special characters as they are.
Placeholders:
d, D, a, A - can be replaced by any kind of argument (color, number, escaped value,
expression, ...). If you use them in combination with string, the whole string will be used -
including its quotes. However, the quotes are placed into the string as they are, they are not
escaped by "/" nor anything similar.
s, S - can be replaced by any expression. If you use it with string, only the string value is used
- quotes are omitted.
Parameters:
string: format string with placeholders,
anything* : values to replace placeholders.
Returns: formatted string.
Example:
format-a-d:%("repetitions:%a file: %d", 1 + 2, "directory/file.less");
format-a-d-upper: %('repetitions: %A file: %D', 1 + 2, "directory/file.less");
format-s: %("repetitions: %s file: %s", 1 + 2, "directory/file.less");
format-s-upper: %('repetitions: %S file: %S', 1 + 2, "directory/file.less");
Output:
format-a-d: "repetitions:
3 file: "directory/file.less"";format-a-d-upper: "repetitions:
3 file: %22directory%2Ffile.less%22";format-s: "repetitions:
3 file: directory/file.less";format-s-upper: "repetitions:
3 file: directory%2Ffile.less";
replace
Replaces a text within a string.
Released v1.7.0
Parameters:
string: The string to search and replace in.
pattern: A string or regular expression pattern to search for.
replacement: The string to replace the matched pattern with.
flags: (Optional) regular expression flags.
Returns: a string with the replaced values.
Example:
replace("Hello, Mars?", "Mars\?", "Earth!");
replace("One + one = 4", "one", "2", "gi");
replace('This is a string.', "(string)\.$", "new $1.");
replace(~"bar-1", '1', '2');
Result:
"Hello, Earth!";
"2 + 2 = 4";
'This is a new string.';
bar-2;

List Functions
length
Returns the number of elements in a value list.
Parameters
list - a comma or space separated list of values.
Example: length(1px solid #0080ff);
Output: 3
Example:
@list: "banana", "tomato", "potato", "peach";n: length(@list);
Output:
n: 4;
extract
Returns the value at a specified position in a list.
Parameters
list - a comma or space separated list of values.
index - an integer that specifies a position of a list element to return.
Example: extract(8px dotted red, 2);
Output: dotted
Example:
@list: apple, pear, coconut, orange;value: extract(@list, 3);
Output:
value: coconut;
range
Released v3.9.0
Generate a list spanning a range of values
Parameters
start - (optional) The start value e.g. 1 or 1px
end - The end value e.g. 5px
step - (optional) The amount to increment by
Examples:
value: range(4);
Outputs:
value: 1 2 3 4;
The output of each value in the range will be the same unit as the end value. For example:
value: range(10px, 30px, 10);
Outputs:
value: 10px 20px 30px;
each
Released v3.7.0
Bind the evaluation of a ruleset to each member of a list.
Parameters
list - a comma or space separated list of values.
rules - An anonymous ruleset/mixin
Example:
@selectors: blue, green, red;
each(@selectors, {
.sel-@{value} {
a: b;
}
});
Outputs:
.sel-blue {
a: b;
}.sel-green {
a: b;
}.sel-red {
a: b;
}
By default, each ruleset is bound, per list member, to a @value, @key, and @index variable.
For most lists, @key and @index will be assigned the same value (numerical position,
1-based). However, you can also use rulesets themselves as structured lists. As in:
@set: {
one: blue;
two: green;
three: red;
}
.set {
each(@set, {
@{key}-@{index}: @value;
});
}
This will output:
.set {
one-1: blue;
two-2: green;
three-3: red;
}
Since you can, of course, call mixins with guards for each ruleset call, this makes each() a
very powerful function.
Setting variable names in each()
You don't have to use @value, @key, and @index in your each() function. In Less 3.7, with
the each() function, Less is introducing the concept of anonymous mixins, which may expand
to other parts of the syntax at a later date.
An anonymous mixin uses the form of #() or .() starting with . or # just like a regular mixin
would. In each(), you can use it like this:
.set-2() {
one: blue;
two: green;
three: red;
}.set-2 {
// Call mixin and iterate each rule
each(.set-2(), .(@v, @k, @i) {
@{k}-@{i}: @v;
});
}
This outputs, as expected:
.set-2 {
one-1: blue;
two-2: green;
three-3: red;
}
The each() function will take the variable names defined in the anonymous mixin and bind
them to the @value, @key and @index values, in that order. If you only write each(@list,
#(@value) {}), then neither @key nor @index will be defined.
Creating a for loop using range and each
Requires Less v3.9.0
You can emulate a for loop simply by generating a numerical list and using each to expand it
to a ruleset.
Example:
each(range(4), {
.col-@{value} {
height: (@value * 50px);
}
});
Outputs:
.col-1 {
height: 50px;
}.col-2 {
height: 100px;
}.col-3 {
height: 150px;
}.col-4 {
height: 200px;
}
Math Functions

ceil
Rounds up to the next highest integer.
Parameters: number - a floating point number.
Returns: integer
Example: ceil(2.4)
Output: 3
floor
Rounds down to the next lowest integer.
Parameters: number - a floating point number.
Returns: integer
Example: floor(2.6)
Output: 2
percentage
Converts a floating point number into a percentage string.
Parameters: number - a floating point number.
Returns: string
Example: percentage(0.5)
Output: 50%
round
Applies rounding.
Parameters:
number: A floating point number.
decimalPlaces: Optional: The number of decimal places to round to. Defaults to 0.
Returns: number
Example: round(1.67)
Output: 2
Example: round(1.67, 1)
Output: 1.7
sqrt
Calculates square root of a number. Keeps units as they are.
Parameters: number - floating point number.
Returns: number
Example:
sqrt(25cm)
Output:
5cm
Example:
sqrt(18.6%)
Output:
4.312771730569565%;
abs
Calculates absolute value of a number. Keeps units as they are.
Parameters: number - a floating point number.
Returns: number
Example #1: abs(25cm)
Output: 25cm
Example #2: abs(-18.6%)
Output: 18.6%;
sin
Calculates sine function.
Assumes radians on numbers without units.
Parameters: number - a floating point number.
Returns: number
Example:
sin(1); // sine of 1 radiansin(1deg); // sine of 1 degreesin(1grad); // sine of 1 gradian
Output:
0.8414709848078965; // sine of 1 radian
0.01745240643728351; // sine of 1 degree
0.015707317311820675; // sine of 1 gradian
asin
Calculates arcsine (inverse of sine) function.
Returns number in radians e.g. a number between -π/2 and π/2.
Parameters: number - floating point number from [-1, 1] interval.
Returns: number
Example:
asin(-0.8414709848078965)asin(0)asin(2)
Output:
-1rad
0rad
NaNrad
cos
Calculates cosine function.
Assumes radians on numbers without units.
Parameters: number - a floating point number.
Returns: number
Example:
cos(1) // cosine of 1 radiancos(1deg) // cosine of 1 degreecos(1grad) // cosine of 1 gradian
Output:
0.5403023058681398 // cosine of 1 radian
0.9998476951563913 // cosine of 1 degree
0.9998766324816606 // cosine of 1 gradian
acos
Calculates arccosine (inverse of cosine) function.
Returns number in radians e.g. a number between 0 and π.
Parameters: number - a floating point number from [-1, 1] interval.
Returns: number
Example:
acos(0.5403023058681398)acos(1)acos(2)
Output:
1rad
0rad
NaNrad
tan
Calculates tangent function.
Assumes radians on numbers without units.
Parameters: number - a floating point number.
Returns: number
Example:
tan(1) // tangent of 1 radiantan(1deg) // tangent of 1 degreetan(1grad) // tangent of 1 gradian
Output:
1.5574077246549023 // tangent of 1 radian
0.017455064928217585 // tangent of 1 degree
0.015709255323664916 // tangent of 1 gradian
atan
Calculates arctangent (inverse of tangent) function.
Returns number in radians e.g. a number between -π/2 and π/2.
Parameters: number - a floating point number.
Returns: number
Example:
atan(-1.5574077246549023)atan(0)round(atan(22), 6) // arctangent of 22 rounded to 6
decimal places
Output:
-1rad
0rad
1.525373rad;
pi
Returns π (pi);
Parameters: none
Returns: number
Example:
pi()
Output:
3.141592653589793
pow
Returns the value of the first argument raised to the power of the second argument.
Returned value has the same dimension as the first parameter and the dimension of the
second parameter is ignored.
Parameters:
number: base -a floating point number.
number: exponent - a floating point number.
Returns: number
Example:
pow(0cm, 0px)pow(25, -2)pow(25, 0.5)pow(-25, 0.5)pow(-25%, -0.5)
Output:
1cm
0.0016
5
NaN
NaN%
mod
Returns the value of the first argument modulus second argument.
Returned value has the same dimension as the first parameter, the dimension of the second
parameter is ignored. The function is able to handle also negative and floating point numbers.
Parameters:
number: a floating point number.
number: a floating point number.
Returns: number
Example:
mod(0cm, 0px)mod(11cm, 6px);mod(-26%, -5);
Output:
NaNcm;
5cm
-1%;
min
Returns the lowest of one or more values.
Parameters: value1, ..., valueN - one or more values to compare.
Returns: the lowest value.
Example: min(5, 10);
Output: 5
Example: min(3px, 42px, 1px, 16px);
Output: 1px
max
Returns the highest of one or more values.
Parameters: value1, ..., valueN - one or more values to compare.
Returns: the highest value.
Example: max(5, 10);
Output: 10
Example: max(3%, 42%, 1%, 16%);
Output: 42%

Type Functions
isnumber
Returns true if a value is a number, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a number, false otherwise.
Example:
isnumber(#ff0); // false
isnumber(blue); // false
isnumber("string"); // false
isnumber(1234); // true
isnumber(56px); // true
isnumber(7.8%); // true
isnumber(keyword); // false
isnumber(url(...)); // false
isstring
Returns true if a value is a string, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a string, false otherwise.
Example:
isstring(#ff0); // false
isstring(blue); // false
isstring("string"); // true
isstring(1234); // false
isstring(56px); // false
isstring(7.8%); // false
isstring(keyword); // false
isstring(url(...)); // false
iscolor
Returns true if a value is a color, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a color, false otherwise.
Example:
iscolor(#ff0); // true
iscolor(blue); // true
iscolor("string"); // false
iscolor(1234); // false
iscolor(56px); // false
iscolor(7.8%); // false
iscolor(keyword); // false
iscolor(url(...)); // false
iskeyword
Returns true if a value is a keyword, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a keyword, false otherwise.
Example:
iskeyword(#ff0); // false
iskeyword(blue); // false
iskeyword("string"); // false
iskeyword(1234); // false
iskeyword(56px); // false
iskeyword(7.8%); // false
iskeyword(keyword); // true
iskeyword(url(...)); // false
isurl
Returns true if a value is a url, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a url, false otherwise.
Example:
isurl(#ff0); // false
isurl(blue); // false
isurl("string"); // false
isurl(1234); // false
isurl(56px); // false
isurl(7.8%); // false
isurl(keyword); // false
isurl(url(...)); // true
ispixel
Returns true if a value is a number in pixels, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a pixel, false otherwise.
Example:
ispixel(#ff0); // false
ispixel(blue); // false
ispixel("string"); // false
ispixel(1234); // false
ispixel(56px); // true
ispixel(7.8%); // false
ispixel(keyword); // false
ispixel(url(...)); // false
isem
Returns true if a value is an em value, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is an em value, false otherwise.
Example:
isem(#ff0); // false
isem(blue); // false
isem("string"); // false
isem(1234); // false
isem(56px); // false
isem(7.8em); // true
isem(keyword); // false
isem(url(...)); // false
ispercentage
Returns true if a value is a percentage value, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a percentage value, false otherwise.
Example:
ispercentage(#ff0); // false
ispercentage(blue); // false
ispercentage("string"); // false
ispercentage(1234); // false
ispercentage(56px); // false
ispercentage(7.8%); // true
ispercentage(keyword); // false
ispercentage(url(...)); // false
isunit
Returns true if a value is a number in specified units, false otherwise.
Parameters:
value - a value or variable being evaluated.
unit - a unit identifier (optionally quoted) to test for.
Returns: true if value is a number in specified units, false otherwise.
Example:
isunit(11px, px); // true
isunit(2.2%, px); // false
isunit(33px, rem); // false
isunit(4rem, rem); // true
isunit(56px, "%"); // false
isunit(7.8%, '%'); // true
isunit(1234, em); // false
isunit(#ff0, pt); // false
isunit("mm", mm); // false
isruleset
Returns true if a value is a ruleset, false otherwise.
Parameters:
value - a variable being evaluated.
Returns: true if value is a ruleset, false otherwise.
Example:
@rules: {
color: red;
}
isruleset(@rules); // true
isruleset(#ff0); // false
isruleset(blue); // false
isruleset("string"); // false
isruleset(1234); // false
isruleset(56px); // false
isruleset(7.8%); // false
isruleset(keyword); // false
isruleset(url(...)); // false

Misc Functions
color
Parses a color, so a string representing a color becomes a color.
Parameters: string: a string of the specified color.
Returns: color
Example: color("#aaa");
Output: #aaa
image-size
Gets the image dimensions from a file.
Parameters: string: the file to get the dimensions for.
Returns: dimension
Example: image-size("file.png");
Output: 10px 10px
Note: this function needs to be implemented by each environment. It is currently only
available in the node environment.
Added in: v2.2.0
image-width
Gets the image width from a file.
Parameters: string: the file to get the dimensions for.
Returns: dimension
Example: image-width("file.png");
Output: 10px
Note: this function needs to be implemented by each environment. It is currently only
available in the node environment.
Added in: v2.2.0
image-height
Gets the image height from a file.
Parameters: string: the file to get the dimensions for.
Returns: dimension
Example: image-height("file.png");
Output: 10px
Note: this function needs to be implemented by each environment. It is currently only
available in the node environment.
Added in: v2.2.0
convert
Convert a number from one unit into another.
The first argument contains a number with units and second argument contains units. If the
units are compatible, the number is converted. If they are not compatible, the first argument
is returned unmodified.
See unit for changing the unit without conversion.
Compatible unit groups:
lengths: m, cm, mm, in, pt and pc,
time: s and ms,
angle: rad, deg, grad and turn.
Parameters:
number: a floating point number with units.
identifier, string or escaped value: units
Returns: number
Example:
convert(9s, "ms")convert(14cm, mm)convert(8, mm) // incompatible unit types
Output:
9000ms
140mm
8
data-uri
Inlines a resource and falls back to url() if the ieCompat option is on and the resource is too
large, or if you use the function in the browser. If the MIME type is not given then node uses
the mime package to determine the correct mime type.
Parameters:
mimetype: (Optional) A MIME type string.
url: The URL of the file to inline.
If there is no mimetype, data-uri function guesses it from filename suffix. Text and svg files
are encoded as utf-8 and anything else is encoded as base64.
If user provided mimetype, the function uses base64 if mimetype argument ends with ;base64.
For example, image/jpeg;base64 is encoded into base64 while text/html is encoded into utf-8.
Example: data-uri('../data/image.jpg');
Output: url('data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==');
Output in browser: url('../data/image.jpg');
Example:
data-uri('image/jpeg;base64', '../data/image.jpg');
Output:
url('data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==');
Example:
data-uri('image/svg+xml;charset=UTF-8', 'image.svg');
Output:
url("data:image/svg+xml;charset=UTF-8,%3Csvg%3E%3Ccircle%20r%3D%229%22%2F%
3E%3C%2Fsvg%3E");
default
Available only inside guard conditions and returns true only if no other mixin
matches, false otherwise.
Example:
.mixin(1) {x: 11}.
mixin(2) {y: 22}.
mixin(@x) when (default()) {z: @x}
div {
.mixin(3);
}
div.special {
.mixin(1);
}
Output:
div {
z: 3;
}div.special {
x: 11;
}
It is possible to use the value returned by default with guard operators. For example .mixin()
when not(default()) {} will match only if there's at least one more mixin definition that
matches.mixin() call:
.mixin(@value) when (ispixel(@value)) {width: @value}.mixin(@value) when not(default())
{padding: (@value / 5)}
div-1 {
.mixin(100px);
}
div-2 {
/* ... */
.mixin(100%);
}
result:
div-1 {
width: 100px;
padding: 20px;
}div-2 {
/* ... */
}
It is allowed to make multiple default() calls in the same guard condition or in a different
conditions of a mixins with the same name:
div {
.m(@x) when (default()), not(default()) {always: @x}
.m(@x) when (default()) and not(default()) {never: @x}

.m(1); // OK
}
However Less will throw a error if it detects a potential conflict between multiple mixin
definitions using default():
div {
.m(@x) when (default()) {}
.m(@x) when not(default()) {}

.m(1); // Error
}
In above example it is impossible to determine what value each default() call should return
since they recursively depend on each other.
Advanced multiple default() usage:
.x {
.m(red) {case-1: darkred}
.m(blue) {case-2: darkblue}
.m(@x) when (iscolor(@x)) and (default()) {default-color: @x}
.m('foo') {case-1: I am 'foo'}
.m('bar') {case-2: I am 'bar'}
.m(@x) when (isstring(@x)) and (default()) {default-string: and I am the default}

&-blue {.m(blue)}
&-green {.m(green)}
&-foo {.m('foo')}
&-baz {.m('baz')}
}
Result:
.x-blue {
case-2: #00008b;
}.x-green {
default-color: #008000;
}.x-foo {
case-1: I am 'foo';
}.x-baz {
default-string: and I am the default;
}
The default function is available as a Less built-in function only inside guard expressions. If
used outside of a mixin guard condition it is interpreted as a regular CSS value:
Example:
div {
foo: default();
bar: default(42);
}
Result:
div {
foo: default();
bar: default(42);
}
unit
Remove or change the unit of a dimension
Parameters:
dimension: A number, with or without a dimension.
unit: (Optional) the unit to change to, or if omitted it will remove the unit.
See convert for changing the unit with conversion.
Example: unit(5, px)
Output: 5px
Example: unit(5em)
Output: 5
get-unit
Returns units of a number.
If the argument contains a number with units, the function returns its units. The argument
without units results in an empty return value.
Parameters:
number: a number with or without units.
Example: get-unit(5px)
Output: px
Example: get-unit(5)
Output: //nothing
svg-gradient
Generates multi-stop svg gradients.
Svg-gradient function generates multi-stop svg gradients. It must have at least three
parameters. First parameter specifies gradient type and direction and remaining parameters
list colors and their positions. The position of first and last specified color are optional,
remaining colors must have positions specified.
The direction must be one of to bottom, to right, to bottom right, to top right, ellipse or ellipse
at center. The direction can be specified as both escaped value ~'to bottom' and space
separated list of words to bottom.
The direction must be followed by two or more color stops. They can be supplied either
inside a list or you can specify each color stops in separate argument.
Parameters - colors stops in list:
escaped value or list of identifiers: direction
list - all colors and their positions in list
Parameters - color stops in arguments:
escaped value or list of identifiers: direction
color [percentage] pair: first color and its relative position (position is optional)
color percent pair: (optional) second color and its relative position
...
color percent pair: (optional) n-th color and its relative position
color [percentage] pair: last color and its relative position (position is optional)
Returns: url with "URI-Encoded" svg gradient.
Example - colors stops in list:
div {
@list: red, green 30%, blue;
background-image: svg-gradient(to right, @list);
}
equivalent - color stops in arguments:
div {
background-image: svg-gradient(to right, red, green 30%, blue);
}

Mixins
"mix-in" properties from existing styles
You can mix-in class selectors and id selectors, e.g.
.a, #b {
color: red;
}.mixin-class {
.a();
}.mixin-id {
#b();
}
which results in:
.a, #b {
color: red;
}.mixin-class {
color: red;
}.mixin-id {
color: red;
}
Currently and historically, the parentheses in a mixin call are optional, but optional
parentheses are deprecated and will be required in a future release.
.a(); .a; // currently works, but deprecated; don't use
Not Outputting the Mixin
If you want to create a mixin but you do not want that mixin to be in your CSS output, put
parentheses after the mixin definition.
.my-mixin {
color: black;
}.my-other-mixin() {
background: white;
}.class {
.my-mixin();
.my-other-mixin();
}
outputs
.my-mixin {
color: black;
}.class {
color: black;
background: white;
}
Selectors in Mixins
Mixins can contain more than just properties, they can contain selectors too.
For example:
.my-hover-mixin() {
&:hover {
border: 1px solid red;
}
}button {
.my-hover-mixin();
}
Outputs
button:hover {
border: 1px solid red;
}

Operations
Arithmetical operations +, -, *, / can operate on any number, color or variable. If it is possible,
mathematical operations take units into account and convert numbers before adding,
subtracting or comparing them. The result has leftmost explicitly stated unit type. If the
conversion is impossible or not meaningful, units are ignored. Example of impossible
conversion: px to cm or rad to %.
// numbers are converted into the same units@conversion-1: 5cm + 10mm;
// result is 6cm@conversion-2: 2 - 3cm - 5mm; // result is -1.5cm
// conversion is impossible@incompatible-units: 2 + 5px - 3cm; // result is 4px
// example with variables@base: 5%;@filler: @base * 2;
// result is 10%@other: @base + @filler; // result is 15%
Multiplication and division do not convert numbers. It would not be meaningful in most cases
- a length multiplied by a length gives an area and css does not support specifying areas. Less
will operate on numbers as they are and assign explicitly stated unit type to the result.
@base: 2cm * 3mm; // result is 6cm
You can also do arithmetic on colors:
@color: #224488 / 2; //results in #112244background-color: #112244 + #111; //
result is #223355
However, you may find Less's Color Functions more useful.
calc() exception
For CSS compatibility, calc() does not evaluate math expressions, but will evaluate variables
and math in nested functions.
@var: 50vh/2;width: calc(50% + (@var - 20px)); // result is calc(50% + (25vh -
20px))

Nesting
Less gives you the ability to use nesting instead of, or in combination with cascading. Let's
say we have the following CSS:
#header {
color: black;
}#header .navigation {
font-size: 12px;
}#header .logo {
width: 300px;
}
In Less, we can also write it this way:
#header {
color: black;
.navigation {
font-size: 12px;
}
.logo {
width: 300px;
}
}
The resulting code is more concise, and mimics the structure of your HTML.
You can also bundle pseudo-selectors with your mixins using this method. Here's the classic
clearfix hack, rewritten as a mixin (& represents the current selector parent):
.clearfix {
display: block;
zoom: 1;

&:after {
content: " ";
display: block;
font-size: 0;
height: 0;
clear: both;
visibility: hidden;
}
}
Nested At-Rules and Bubbling
At-rules such as @media or @supports can be nested in the same way as selectors. The
at-rule is placed on top and relative order against other elements inside the same ruleset
remains unchanged. This is called bubbling.
.component {
width: 300px;
@media (min-width: 768px) {
width: 600px;
@media (min-resolution: 192dpi) {
background-image: url(/img/retina2x.png);
}
}
@media (min-width: 1280px) {
width: 800px;
}
}

outputs:
.component {
width: 300px;
}@media (min-width: 768px) {
.component {
width: 600px;
}
}@media (min-width: 768px) and (min-resolution: 192dpi) {
.component {
background-image: url(/img/retina2x.png);
}
}@media (min-width: 1280px) {
.component {
width: 800px;
}
}

Scope
Scope in Less is very similar to that of CSS. Variables and mixins are first looked for locally,
and if they aren't found, it's inherited from the "parent" scope.
@var: red;
#page {
@var: white;
#header {
color: @var; // white
}
}
Like CSS custom properties, mixin and variable definitions do not have to be placed before a
line where they are referenced. So the following Less code is identical to the previous
example:
@var: red;
#page {
#header {
color: @var; // white
}
@var: white;
}

Escaping
Escaping allows you to use any arbitrary string as property or variable value. Anything
inside ~"anything" or ~'anything' is used as is with no changes except interpolation.
@min768: ~"(min-width: 768px)";.element {
@media @min768 {
font-size: 1.2rem;
}
}
results in:
@media (min-width: 768px) {
.element {
font-size: 1.2rem;
}
}
Note, as of Less 3.5, you can simply write:
@min768: (min-width: 768px);.element {
@media @min768 {
font-size: 1.2rem;
}
}

Namespaces and Accessors


Sometimes, you may want to group your mixins, for organizational purposes, or just to offer
some encapsulation. You can do this pretty intuitively in Less. Say you want to bundle some
mixins and variables under #bundle, for later reuse or distributing:
#bundle() {
.button {
display: block;
border: 1px solid black;
background-color: grey;
&:hover {
background-color: white;
}
}
.tab { ... }
.citation { ... }
}
Now if we want to mixin the .button class in our #header a, we can do:
#header a {
color: orange;
#bundle.button(); // can also be written as #bundle > .button
}

Maps
As of Less 3.5, you can also use mixins and rulesets as maps of values.
#colors() {
primary: blue;
secondary: green;
}
.button {
color: #colors[primary];
border: 1px solid #colors[secondary];
}
This outputs, as expected:
.button {
color: blue;
border: 1px solid green;
}

Comments
Both block-style and inline comments may be used:
/* One heck of a block
* style comment! */@var: red;
// Get in line!@var: white;

Imports
Importing works pretty much as expected. You can import a .less file, and all the variables in
it will be available. The extension is optionally specified for .less files.
@import "library"; // library.less@import "typo.css";

CSS Guards
Like Mixin Guards, guards can also be applied to css selectors, which is syntactic sugar for
declaring the mixin and then calling it immediately.
For instance, before 1.5.0 you would have had to do this:
.my-optional-style() when (@my-option = true) {
button {
color: white;
}
}.my-optional-style();
Now, you can apply the guard directly to a style.
button when (@my-option = true) {
color: white;
}
You can also achieve an if type statement by combining this with the & feature, allowing you
to group multiple guards.
& when (@my-option = true) {
button {
color: white;
}
a{
color: blue;
}
}
Note that you can also achieve a similar pattern by using the actual if() function and a
variable call. As in:
@dr: if(@my-option = true, {
button {
color: white;
}
a{
color: blue;
}
});@dr();

You might also like