You are on page 1of 105

JAVASCRIPT

SRINIVASA RAO KANAPARTHI


JavaScript
Javascript is a dynamic computer programming language.
It is lightweight and most commonly used as a part of web pages,
whose implementations allow client-side script to interact with the
user and make dynamic pages.
Client-side JavaScript is the most common form of the language.
The script should be included in or referenced by an HTML document for the
code to be interpreted by the browser.
It is an interpreted programming language with object-oriented
capabilities.
Open and cross-platform.
Syntax
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you web page, but it
is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags
as a script.
A simple syntax of your JavaScript will appear as follows.
<script language="javascript" type="text/javascript">
JavaScript code
</script>
The script tag takes two important attributes:
Language: This attribute specifies what scripting language you are using. Typically, its value will be javascript.
Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
Type: This attribute is what is now recommended to indicate the scripting language in use and its value should
be set to "text/javascript".
Syntax
Let us take a sample example to print out "Hello World".
We added an optional HTML comment that surrounds our JavaScript code. This is to save our
code from a browser that does not support JavaScript.
The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add that to
prevent a browser from reading the end of the HTML comment as a piece of JavaScript code.
Next, we call a function document.write which writes a string into our HTML document.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
</body>
</html>
Syntax
Whitespace and Line Breaks
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
You can use spaces, tabs, and newlines freely in your program and you are free to
format and indent your programs in a neat and consistent way that makes the code
easy to read and understand.
Semicolons are Optional
Simple statements in JavaScript are generally followed by a semicolon character, just
as they are in C, C++, and Java. JavaScript, however, allows you to omit this
semicolon if each of your statements are placed on a separate line.
Case Sensitivity
JavaScript is a case-sensitive language.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:
Any text between a // and the end of a line is treated as a comment and is
ignored by JavaScript.
Any text between the characters /* and */ is treated as a comment. This
may span multiple lines.
JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the //
comment.
The HTML comment closing sequence --> is not recognized by JavaScript
so it should be written as //-->.
Placement
There is a flexibility given to include JavaScript code anywhere in an
HTML document.
However the most preferred ways to include JavaScript in an HTML
file are as follows:
Script in <head>...</head> section.
Script in <body>...</body> section.
Script in <body>...</body> and <head>...</head> sections.
Script in an external file and then include in <head>...</head> section.
Placement Script in <head>, Script in <body>
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
Placement Script in <head> and <body>
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
Placement - Script in an external file and include in <head> section
<html>
<head>
<script type="text/javascript" src="filename.js">
</script>
</head>
<body>
.......
</body>
</html>

filename.js
function sayHello() {
alert("Hello World")
}
JavaScript Datatypes
One of the most fundamental characteristics of a programming language is
the set of data types it supports.
These are the type of values that can be represented and manipulated in a
programming language.
JavaScript allows you to work with three primitive data types:
Numbers, e.g., 123, 120.50 etc.
Strings of text, e.g. "This text string" etc.
Boolean, e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of
which defines only a single value.
In addition to these primitive data types, JavaScript supports a composite
data type known as object.
JavaScript Variables
Like many other programming languages, JavaScript has variables.
Variables can be thought of as named containers.
You can place data into these containers and then refer to the data simply by naming the
container.
Before you use a variable in a JavaScript program, you must declare it.
Variables are declared with the var keyword as follows.
var age;
var name;
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.
var name = "Ali";
var money;
money = 2000.50;
JavaScript Variables
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
Local JavaScript Variables
Variables declared within a JavaScript function, become LOCAL to the function. Local variables have local scope: They can only be accessed within the function.
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions. Local variables are created when a
function starts, and deleted when the function is completed.
// code here can not use carName
function myFunction() {
var carName = "Volvo";
// code here can use carName
}

Global JavaScript Variables


A variable declared outside a function, becomes GLOBAL.A global variable has global scope: All scripts and functions on a web page can access it.
var carName = " Volvo";
// code here can use carName
function myFunction() {
// code here can use carName
}

Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
This code example will declare a global variable carName, even if the value is assigned inside a function.
myFunction();
// code here can use carName
function myFunction() {
carName = "Volvo";
}
JavaScript Variable Names
While naming your variables in JavaScript, keep the following rules in
mind.
You should not use any of the JavaScript reserved keywords as a variable
name. These keywords are mentioned in the next section. For example, break
or boolean variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must
begin with a letter or an underscore character. For example, 123test is an
invalid variable name but _123test is a valid one.
JavaScript variable names are case-sensitive. For example, Name and name
are two different variables.
JavaScript Variable Scope
let allows you to declare variables that are limited in scope to the block, statement, or expression
on which it is used.
This is unlike the var keyword, which defines a variable globally, or locally to an entire function
regardless of block scope.

function varTest() { function letTest() {


var x = 1; let x = 1;
if (true) { if (true) {
var x = 2; // same variable! let x = 2; // different variable
console.log(x); // 2 console.log(x); // 2
} }
console.log(x); // 2 console.log(x); // 1
} }
JavaScript Reserved Words
The reserved words in EMCAScript-262 are the Keywords, Future Reserved Words, NullLiteral, and BooleanLiterals,
where the Keywords are
break do instanceof typeof
case else new var
catch finally return void
continue for switch while
debugger function this with
default if throw
delete in try
the Future Reserved Words are
abstract export interface static
boolean extends long super
byte final native synchronized
char float package throws
class goto private transient
const implements protected volatile
double import public
enum int short
the Null Literal is
null
and the Boolean Literals are
true
false
JavaScript Reserved Words typeof and
debugger
You can use the JavaScript typeof operator to find the type of a JavaScript variable.

var length = 16; // Number


var lastName = "Johnson"; // String
var x = {firstName:"John", lastName:"Doe"}; // Object

document.write(typeof(length));
document.write(typeof(lastName));
document.write(typeof(x));

With the debugger turned on, this code should stop executing before it executes the third line:

var x = 15 * 5;
debugger;
document.getElementbyId("demo").innerHTML = x;
JavaScript Reserved Words - Delete
The delete operator removes a property from an object.

delete expression, where expression should evaluate to a property reference, e.g.:


delete object.property
delete object['property']

var Employee = {
age: 28,
name: 'abc',
designation: 'developer'
}

console.log(delete Employee.name); // returns true


console.log(delete Employee.age); // returns true

// When trying to delete a property that does not exist, true is returned
console.log(delete Employee.salary); // returns true

When a property is marked as non-configurable, delete won't have any effect, and will return false. In strict mode this will raise a SyntaxError.

var Employee = {};


Object.defineProperty(Employee, 'name', {configurable: false});

console.log(delete Employee.name); // returns false


JavaScript Reserved Words - instanceof
The instanceof operator tests whether an object in its prototype chain has the prototype property of a constructor.

Syntax: object instanceof constructor

// defining constructors
function C() {}
function D() {}

var o = new C();

o instanceof C; // true, because: Object.getPrototypeOf(o) === C.prototype


o instanceof D; // false, because D.prototype is nowhere in o's prototype chain
o instanceof Object; // true, because: C.prototype instanceof Object // true

C.prototype = {};
var o2 = new C();

o2 instanceof C; // true

o instanceof C; // false, because C.prototype is nowhere in o's prototype chain anymore

D.prototype = new C(); // add C to [[Prototype]] linkage of D


var o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true since C.prototype is now in o3's prototype chain
Operators
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
Arithmetic Operators
+ (Addition) Adds two operands Ex: A + B will give 30
- (Subtraction) Subtracts the second operand from the first Ex: A - B will
give -10
* (Multiplication) Multiply both operands Ex: A * B will give 200
/ (Division) Divide the numerator by the denominator Ex: B / A will give 2
% (Modulus) Outputs the remainder of an integer division Ex: B % A will
give 0
++ (Increment) Increases an integer value by one Ex: A++ will give 11
-- (Decrement) Decreases an integer value by one Ex: A-- will give 9
Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will
give "a10".
Comparison Operators
== (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes true.
Ex: (A == B) is not true.
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then the condition becomes true.
Ex: (A != B) is true.
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
< (Less than)
Checks if the value of the left operand is less than the value of the right operand, if yes, then the condition becomes true.
Ex: (A < B) is true.
>= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
<= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.
Logical Operators
&& (Logical AND)
If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
|| (Logical OR)
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 operator will make it false.
Ex: ! (A && B) is false.
Bitwise Operators
& (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
| (BitWise OR)
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. Exclusive OR means that either operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.
~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
<< (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 operands value is moved right by the number of 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 always zero.
Ex: (A >>> 1) is 1.
Assignment Operators
= (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
+= (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
-= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left operand.
Ex: C -= A is equivalent to C = C A
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left operand.
Ex: C *= A is equivalent to C = C * A
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left operand.
Ex: C /= A is equivalent to C = C / A
%= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A

Note: Same logic applies to Bitwise operators, so they will become <<=, >>=,>>=, &=, |= and ^=.
Conditional Statements
JavaScript supports conditional statements which are used to perform
different actions based on different conditions.
Different types of conditional statements supported by JavaScript are
if..else statement.
if...else ifelse statements
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the if block, are
executed.
If the expression is false, then the given statement(s) in the else block are executed.
The if...else if...else statement is an advanced form of ifelse that allows JavaScript to make a correct decision out of
several conditions.
a switch statement
The objective of a switch statement is to give an expression to evaluate and several different statements to execute
based on the value of the expression.
The interpreter checks each case against the value of the expression until a match is found.
If nothing matches, a default condition will be used.
Conditional Statements
var book = "maths"; var grade='A';
switch (grade)
if( book == "history" ){ {
document.write("<b>History Book</b>"); case 'A': document.write("Good job<br />");
} break;
else if( book == "maths" ){ case 'B': document.write("Pretty good<br />");
document.write("<b>Maths Book</b>"); break;
} case 'C': document.write("Passed<br />");
break;
else if( book == "economics" ){ case 'D': document.write("Not so good<br />");
document.write("<b>Economics Book</b>"); break;
} case 'F': document.write("Failed<br />");
else{ break;
document.write("<b>Unknown Book</b>"); default: document.write("Unknown grade<br />")
} }
Loops
While writing a program, you may encounter a situation where you need to
perform an action over and over again.
In such situations, you would need to write loop statements to reduce the
number of lines.
JavaScript supports all the necessary loops to ease down the pressure of
programming.
JavaScript supports
The while Loop
The do...while Loop
The for Loop
The forin Loop
Loops
var count = 0;
document.write("Starting Loop ");
while (count < 10){
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");

var count = 0;
document.write("Starting Loop" + "<br />");
do{
document.write("Current Count : " + count + "<br />");
count++;
}while (count < 5);
document.write ("Loop stopped!");
var aProperty;
var count; document.write("Navigator Object Properties<br /> ");
document.write("Starting Loop" + "<br />"); for (aProperty in navigator)
for(count = 0; count < 10; count++){ {
document.write("Current Count : " + count ); document.write(aProperty);
document.write("<br />"); document.write("<br />");
} }
document.write("Loop stopped!"); document.write
Loop Control
JavaScript provides full control to handle loops and switch
statements.
To handle all such situations, JavaScript provides break and continue
statements.
These statements are used to immediately come out of any loop or to
start the next iteration of any loop respectively.
Loop Control
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");

var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skill rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
Functions
A function is a group of reusable code which can be called anywhere in your program.
This eliminates the need of writing the same code again and again.
It helps programmers in writing modular codes.
Functions allow a programmer to divide a big program into a number of small and manageable
functions.
Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions.
You must have seen functions like alert() and write() in the earlier chapters.
We were using these functions again and again, but they had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well.
A function can be written using one of the below 3 methods supported by JavaScript
A function statement
A function constructor
A function literal
Functions - Function Definition
Before we use a function, we need to define it.
The most common way to define a function in JavaScript is
by using the function keyword,
followed by a unique function name,
a list of parameters (that might be empty),
and a statement block surrounded by curly braces.

function functionname(parameter-list)
{
statements
}
Functions Calling a function, parameters and return value
Calling a Function, and Function Parameters
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
sayHello('Zara', 7); // calling a function
The return Statement
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
secondFunction(); // calling a function
Functions - Default function parameters
Default function parameters allow formal parameters to be initialized with default values if no
value or undefined is passed.
In JavaScript, parameters of functions default to undefined.
However, in some situations it might be useful to set a different default value.
This is where default parameters can help.
This even applies to functions and variables:

function multiply(a, b = 1) { function callSomething(thing = something()) {


return a * b; return thing;
} }

multiply(5, 2); // 10 function something() {


multiply(5, 1); // 5 return 'sth';
multiply(5); // 5 }

callSomething(); //sth
Functions - Arguments object
The arguments object is an Array-like object corresponding to the arguments passed to a function.
The arguments object is a local variable available within all functions.
You can refer to a function's arguments within the function by using the arguments object.
This object contains an entry for each argument passed to the function, the first entry's index starting at 0.
For example, if a function is passed three arguments, you can refer to them as follows:
arguments[0]
arguments[1]
arguments[2]

The arguments can also be set:


arguments[1] = 'new value';

The arguments object is not an Array. It is similar to an Array, but does not have any Array properties
except length. For example, it does not have the pop method. However it can be converted to a real Array:
Functions - Rest parameters
The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
function f(a, b, ...theArgs) {
// ...
}

If the last named argument of a function is prefixed with ..., it becomes an array whose elements from 0
(inclusive) to theArgs.length (exclusive) are supplied by the actual arguments passed to the function.
In the above example, theArgs would collect the third argument of the function (because the first one is
mapped to a, and the second to b) and all the consecutive arguments.
function fun1(...theArgs) {
console.log(theArgs.length);
}

fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3
Functions - Rest parameters vs Arguments object
There are three main differences between rest parameters and the
arguments object:
rest parameters are only the ones that haven't been given a separate name,
while the arguments object contains all arguments passed to the function.
the arguments object is not a real array, while rest parameters are Array
instances, meaning methods like sort, map, forEach or pop can be applied on
it directly.
the arguments object has additional functionality specific to itself (like the
callee property).
Functions Nested functions
JavaScript 1.2 allows function definitions to be nested within other functions as well.
Still there is a restriction that function definitions may not appear within loops or conditionals.
These restrictions on function definitions apply only to function declarations with the function
statement.
Whereas function literals (another feature introduced in JavaScript 1.2) may appear within any
JavaScript expression, which means that they can appear within if and other statements.

function hypotenuse(a, b) {
function square(x) { return x*x; }
return Math.sqrt(square(a) + square(b));
} JavaScript functions implement the concept of closures, which are functions that
function secondFunction(){ are defined inside other functions, and use contextual data from the parent
var result; functions to execute.
result = hypotenuse(1,2);
document.write ( result );
}
secondFunction(); // Calling function
Functions Function() constructor
The function statement is not the only way to define a new function; you can define your function
dynamically using Function() constructor along with the new operator.
Notice that the Function() constructor is not passed any argument that specifies a name for the
function it creates.
The unnamed functions created with the Function() constructor are called anonymous functions.
var variablename = new Function(arg1, arg2,..., argN, "Function Body");
var func = new Function("x", "y", "return x*y;");

function secondFunction(){
var result;
result = func(10,20);
document.write ( result );
}

secondFunction(); //Calling function


Functions Function literals
JavaScript 1.2 introduces the concept of function literals which is
another new way of defining functions.
A function literal is an expression that defines an unnamed function.
var variablename = function(Argument List){
Function Body
};
var func = function(x,y){ return x*y };

function secondFunction(){
var result;
result = func(10,20);
document.write ( result );
}

secondFunction(); // Calling a function


Functions JavaScript Closures
A closure is a function having access to the parent scope, even after the parent function has closed.
https://developer.mozilla.org/en/docs/Web/JavaScript/Closures
Lexical scoping
init() creates a local variable called name and a function called displayName().
The displayName() function is an inner function that is defined inside init() and is only available within the body of
the init() function.
The displayName() function has no local variables of its own.
However, because inner functions have access to the variables of outer functions, displayName() can access the
variable name declared in the parent function, init().
function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
Functions JavaScript Closures
A closure is the combination of a function and the lexical environment within which that function was
declared.
At first glance, it may seem unintuitive that this code still works. But Running this code has exactly the same effect as
the previous example of the init() function in previous slide.
In some programming languages, the local variables within a function exist only for the duration of that function's
execution.
Once makeFunc() has finished executing, you might expect that the name variable would no longer be accessible.
However, because the code still works as expected, this is obviously not the case in JavaScript.
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
Functions Getter and setter methods
The get syntax binds an object property to a function that will be called when that property is looked up.
If you want to remove the getter, you can just delete it: delete obj.latest;

The set syntax binds an object property to a function to be called when there is an attempt to set that
property.
If you want to remove the setter, you can just delete it: delete o.current;

To append a getter to an existing object later at any time, use Object.defineProperty().


var o = {a: 0};
var language = {
Object.defineProperty(o, 'b', { get: function() { return this.a + 1; } });
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
set current(name) {
this.log.push(name);
var obj = { },
log: ['test'], log: []
get latest() { }
if (this.log.length == 0) return undefined;
return this.log[this.log.length - 1]; language.current = 'EN';
} document.write(language.log); // ['EN']
}
document.write(obj.latest); // Will return "test". language.current = 'FA';
document.write(language.log); // ['EN', 'FA']
Functions Arrow functions
Objects
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 in 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 of the object.
Objects
In JavaScript, objects are king. If you understand objects, you understand JavaScript.
In JavaScript, almost "everything" is an object.
Booleans can be objects (if defined with the new keyword)
Numbers can be objects (if defined with the new keyword)
Strings can be objects (if defined with the new keyword)
Dates are always objects
Maths are always objects
Regular expressions are always objects
Arrays are always objects
Functions are always objects
Objects are always objects
All JavaScript values, except primitives, are objects. A primitive value is a value that has no properties or methods.
JavaScript defines 5 types of primitive data types:
string
number
boolean
null
undefined
Object creation
With JavaScript, you can define and create your own objects.
There are different ways to create new objects:
Define and create a single object, using an object literal.
Define and create a single object, with the keyword new.
Define an object constructor, and then create objects of the constructed type.
In ECMAScript 5, an object can also be created with the function
Object.create().
All user-defined objects and built-in objects are descendants of an object called Object.
var proto = {};
var obj = Object.create(proto);
Object.getPrototypeOf(obj) === proto; // true
Object creation Using an object literal
This is the easiest way to create a JavaScript Object.
Using an object literal, you both define and create an object in one statement.
An object literal is a list of name:value pairs (like age:50) inside curly braces {}.

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

Spaces and line breaks are not important. An object definition can span multiple lines:
Example
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Object creation Creating an object using object literal
Objects created using object literals are singletons.
This means when a change is made to the object will reflect to all
other instances of that object.
Object creation Using the JavaScript Keyword new
The following example also creates a new JavaScript object with four
properties:
Example

var person = new Object();

person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

The two examples above do exactly the same. There is no need to use new
Object().
For simplicity, readability and execution speed, use the first one (the object
literal method)
Object creation Using an object constructor
The examples above are limited in many situations. They only create a single object.
Sometimes we like to have an "object type" that can be used to create many objects of one type.
The standard way to create an "object type" is to use an object constructor function:

Example var person = function(first, last, age, eye) {


function person(first, last, age, eye) { this.firstName = first;
this.firstName = first; this.lastName = last;
this.lastName = last; this.age = age;
this.age = age;
this.eyeColor = eye; this.eyeColor = eye;
} function statement } function literal

The above function (person) is an object constructor.


Once you have an object constructor, you can create new objects of the same type:

var myFather = new person("John", "Doe", 50, "blue");


var myMother = new person("Sally", "Rally", 48, "green");
Object creation Using an object constructor
This example demonstrates how to create an object with a function statement.
Here this keyword is used to refer to the object that has been passed to a function.
// Define a function which will work as a method
function addPrice(amount){
this.price = amount;
}

function book(title, author){ A function statement


this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}

var myBook = new book("Perl", "Mohtashim");

myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
Object creation Using an object constructor
This example demonstrates how to create an object with a function literal.
Here this keyword is used to refer to the object that has been passed to a function.

A function literal
Object creation Using an object constructor
Built-in JavaScript Constructors : JavaScript has built-in constructors for native objects:
Example
var x1 = new Object(); // A new Object object
var x2 = new String(); // A new String object
var x3 = new Number(); // A new Number object
var x4 = new Boolean(); // A new Boolean object
var x5 = new Array(); // A new Array object
var x6 = new RegExp(); // A new RegExp object
var x7 = new Function(); // A new Function object
var x8 = new Date(); // A new Date object
There is no reason to create complex objects. Primitive values execute much faster.
And there is no reason to use new Array(). Use array literals instead: []
And there is no reason to use new RegExp(). Use pattern literals instead: /()/
And there is no reason to use new Function(). Use function expressions instead: function () {}.
And there is no reason to use new Object(). Use object literals instead: {}

Example
var x1 = {}; // new object
var x2 = ""; // new primitive string
var x3 = 0; // new primitive number
var x4 = false; // new primitive boolean
var x5 = []; // new array object
var x6 = /()/ // new regexp object
var x7 = function(){}; // new function object
Objects - Properties and Methods
Object properties can be any of the three primitive data types, or any of the abstract
data types, such as another object.
Object properties are usually variables that are used internally in the object's methods,
but can also be globally visible variables that are used throughout the page.

objectName.objectProperty = propertyValue;
Example - var str = document.title;

Object Methods are useful for everything from displaying the contents of the object to
the screen to performing complex mathematical operations on a group of local
properties and parameters.

document.write ("This is test"); //to show how to use the write() method of document object to write content on document
Objects - The this Keyword
In JavaScript, the thing called this, is the object that "owns" the JavaScript code.
The value of this, when used in a function, is the object that "owns" the function.
this is undefined in a function invocation in strict mode
The value of this, when used in a method of an object, is the object itself.
The value of this, is the newly created object in a constructor invocation
The value of this, in an indirect invocation is the value passed as first argument to .call() or .apply().
this is the first argument of .bind() when invoking a bound function
Note that this is not a variable. It is a keyword. You cannot change the value of this.
https://rainsoft.io/gentle-explanation-of-this-in-javascript/#2functioninvocation
Objects - The with Keyword
The with keyword is used as a kind of shorthand for referencing an object's properties or
methods.
The object specified as an argument to with becomes the default object for the duration of the
block that follows.
The properties and methods for the object can be used without naming the object.
The syntax for with object is as follows:

with (object){
properties used without the object name and dot
}
// Define a function which will work as a method
function addPrice(amount){
with(this){
price = amount;
}
}
Objects - JavaScript Object Prototypes
Every JavaScript object has a prototype.
All JavaScript objects inherit their properties and methods from their
prototype.
Objects created with new Date() inherit the Date.prototype.
Objects - Creating a Prototype
The standard way to create an object prototype is to use an object constructor function:

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}

With a constructor function, you can use the new keyword to create new objects from the same prototype:

Example
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
Objects - Adding Properties and Methods to Objects
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

Adding a new property to an existing object is easy:


myFather.nationality = "English";

The property will be added to myFather. Not to myMother. Not to any other person objects.

Adding a new method to an existing object is also easy:


myFather.name = function () {
return this.firstName + " " + this.lastName;
};

The method will be added to myFather. Not to myMother.


Objects - Adding Properties and Methods to prototype
Adding a new property to an existing object is easy.
Adding a new method to an existing object is also easy.
But you cannot add a new property to a prototype the same way as
you add a new property to an existing object, because the prototype
is not an existing object.
To add a new property to a prototype, you must add it to the constructor
function.
To add a new method to a prototype, you must add it to the constructor
function.
Any other mechanism?
Yes The JavaScript Objects prototype property
Objects - Adding Properties and Methods to prototype
Prototyping is a JavaScript language feature that allows attaching functions and properties to the
"blueprint" of a function.
The JavaScript prototype property allows you to add new properties to an existing prototype:
The JavaScript prototype property also allows you to add new methods to an existing prototype.
You can add members to a function's prototype at any time, but this won't affect objects that were already created.
It will affect only any new ones.
Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}

Person.prototype.nationality = "English";

Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
Objects - Private Members
JavaScript doesn't support the notion of private members as C# does, but you can simulate the
functionality by using variables inside the function.
Variables are declared with the var keyword or are received as function parameters.
They aren't accessed using this, and they aren't accessible through function instances, thus acting like private
members.
Variables can, however, be accessed by closure functions
function Table (rows, columns){
// save parameter values to local variables
var _rows = rows;
var _columns = columns;
// return the number of table cells
this.getCellCount = function() { return _rows * _columns; };
}

// create a Table object


var t = new Table(3,5);

// display object field values Your table has undefined rows and undefined columns
document.write("Your table has " + t._rows + " rows" + " and " + t._columns + " columns<br />");

// call object function The table has 15 cells


document.write("The table has " + t.getCellCount() + " cells<br />");
Objects - Inheritance using Closures and Prototypes
There are two significant techniques for implementing the OOP
concept of inheritance with JavaScript code.
The first technique uses closures,
and the other technique makes use of a feature of the language
named prototyping.
Objects - Inheritance Using Closures
Objects - Inheritance Using Prototyping
In closure-based inheritance, the derived class inherits the base class methods and properties by
"loading" them into itself. Here's the code again for your reference:
// class SuperCar
function SuperCar(name)
{
// implement closure inheritance
this.inheritsFrom = Car;
this.inheritsFrom(name);
// SuperCar knows how to fly
this.Fly = Fly;
}

When implementing inheritance through prototyping, we can "load" the base class properties
and methods by adding them to the derived class prototype.
That way, an object of the derived class will have access to the class methods and properties, but
also to the base class methods and properties since they exist in the derived class prototype.
Objects - Inheritance Using Prototyping
Objects - Polymorphism in JavaScript
Polymorphism in JavaScript is now very easy.
One simply makes different constructors for different kinds of child
objects inheriting from the same parent.
JavaScript polymorphism has a feature one does not find in all object-
oriented languages.
One can add and override members even on the fly, after an object has been
created.
An object can acquire or lose properties and behaviours over time.
Objects - Polymorphism using prototype
JavaScript Classes
JavaScript classes introduced in ECMAScript 2015 are primarily syntactical
sugar over JavaScript's existing prototype-based inheritance.
The class syntax is not introducing a new object-oriented inheritance
model to JavaScript.
JavaScript classes provide a much simpler and clearer syntax to create
objects and deal with inheritance.
Classes are in fact "special functions", and just as you can define function
literals and function statements, the class syntax has two components:
class expressions (or class literals)
class declarations (or class statements)
Defining classes - class declaration
One way to define a class is using a class declaration. To declare a class, you use the class keyword with the name of the
class ("Rectangle" here).

class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}

Hoisting
An important difference between function declarations and class declarations is that function declarations are hoisted and
class declarations are not.
You first need to declare your class and then access it, otherwise code like the following will throw a ReferenceError:
var p = new Rectangle(); // ReferenceError
class Rectangle {}
Defining classes - class expression
A class expression is another way to define a class. Class expressions can be named or unnamed.
The name given to a named class expression is local to the class's body.
// unnamed
var Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};

// named
var Rectangle = class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
};

Note: Class expressions also suffer from the same hoisting issues mentioned for Class
declarations.
Defining classes - Constructor method
The constructor method is a special method for creating and initializing an object created with a class.
constructor([arguments]) { ... }

There can only be one special method with the name "constructor" in a class.
A SyntaxError will be thrown, if the class contains more than one occurrence of a constructor method.
A constructor can use the super keyword to call the constructor of a parent class.

If you don't specify a constructor method, a default constructor is used.


For base classes, the default constructor is:
constructor() {}
For derived classes, the default constructor is:
constructor(...args) {
super(...args);
}
Defining classes - Constructor method
class Square extends Polygon { class Polygon {
constructor(length) { constructor() {
this.name = "Polygon";
}
// Here, it calls the parent class' constructor with lengths }
// provided for the Polygon's width and height
super(length, length); class Square extends Polygon {
constructor() {
// Note: In derived classes, super() must be called before you super();
}
// can use 'this'. Leaving this out will cause a reference error.
}
this.name = 'Square';
} class Rectangle {}

get area() { Object.setPrototypeOf(Square.prototype, Rectangle.prototype);


return this.height * this.width;
console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false
}
console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true

set area(value) { let newInstance = new Square();


this.area = value; console.log(newInstance.name); //Polygon
}
} Here the prototype of Square class is changed but still the constructor of the previous base
class Polygon is called when new instance of Square will be created.
Defining classes - Static methods
The static keyword defines a static method for a class.
Static methods are called without instantiating their class and cannot be called
through a class instance.
From another static method
In order to call a static method within another static method of the same class, you can use this
keyword.
From class constructor and other methods
Static methods are not directly accessible using the this keyword from non-static methods.
You need to call them using the class name: CLASSNAME.STATIC_METHOD_NAME()
or by calling the method as a property of the constructor: this.constructor.STATIC_METHOD_NAME().
Defining classes - Calling Static methods
class Point { class StaticMethodCall { class StaticMethodCall {
constructor(x, y) { static staticMethod() { constructor() {
this.x = x; return 'Static method has been called';
console.log(StaticMethodCall.staticMethod());
this.y = y; }
} static anotherStaticMethod() { // 'static method has been called.'
return this.staticMethod() + ' from another static method';
static distance(a, b) { } console.log(this.constructor.staticMethod());
const dx = a.x - b.x; } // 'static method has been called.'
const dy = a.y - b.y; }
StaticMethodCall.staticMethod();
return Math.sqrt(dx*dx + dy*dy); // 'Static method has been called'
} static staticMethod() {
} StaticMethodCall.anotherStaticMethod(); return 'static method has been called.';
// 'Static method has been called from another static method' }
const p1 = new Point(5, 5); }
const p2 = new Point(10, 10);

console.log(Point.distance(p1, p2));
Defining classes - Sub classing with extends
The extends keyword is used in class declarations or class expressions to create a class as a child of another class.
If there is a constructor present in sub-class, it needs to first call super() before using "this".
One may also extend traditional function-based "classes
Note that classes cannot extend regular (non-constructible) objects. If you want to inherit from a regular object, you can
instead use Object.setPrototypeOf():
class Animal { function Animal (name) { var Animal = {
constructor(name) { this.name = name; speak() {
this.name = name; console.log(this.name + ' makes a noise.');
}
} }
};
speak() { Animal.prototype.speak = function () {
console.log(this.name + ' makes a noise.'); console.log(this.name + ' makes a noise.'); class Dog {
} } constructor(name) {
} this.name = name;
}
class Dog extends Animal {
class Dog extends Animal { }
speak() { speak() {
console.log(this.name + ' barks.'); console.log(this.name + ' barks.'); // If you do not do this you will get a TypeError when you invoke speak
} } Object.setPrototypeOf(Dog.prototype, Animal);
} }
var d = new Dog('Mitzie');
var d = new Dog('Mitzie'); d.speak(); // Mitzie makes a noise.
var d = new Dog('Mitzie');
d.speak(); // Mitzie barks.
d.speak(); // Mitzie barks.
Defining classes - Super class calls with super
The super keyword is used to call functions on an object's parent.

class Cat {
constructor(name) {
this.name = name;
}

speak() {
console.log(this.name + ' makes a noise.');
}
}

class Lion extends Cat {


speak() {
super.speak();
console.log(this.name + ' roars.');
}
}

var l = new Lion('Fuzzy');


l.speak();
// Fuzzy makes a noise.
// Fuzzy roars.
Array Object
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
var fruits = new Array( "apple", "orange", "mango" );
var fruits = [ "apple", "orange", "mango" ];
Array Properties
constructor - Returns a reference to the array function that created the object.
arr.constructor is:function Array() { [native code] }
Length - Reflects the number of elements in an array.
array.length
prototype - The prototype property allows you to add properties and methods to an object.
object.prototype.name = value
index - The property represents the zero-based index of the match in the string
input - This property is only present in arrays created by regular expression matches.
Array Methods
concat() Returns a new array comprised of this array joined with other array(s) and/or value(s).

every() Returns true if every element in this array satisfies the provided testing function.

filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true.

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

indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.

join() Joins all elements of an array into a string.

lastIndexOf() Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.

map() Creates a new array with the results of calling a provided function on every element in this array.

pop() Removes the last element from an array and returns that element.

push() Adds one or more elements to the end of an array and returns the new length of the array.

reduce() Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.

reduceRight() Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.

reverse() Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.

shift() Removes the first element from an array and returns that element.

slice() Extracts a section of an array and returns a new array.

some() Returns true if at least one element in this array satisfies the provided testing function.

toSource() Represents the source code of an object

sort() Sorts the elements of an array.

splice() Adds and/or removes elements from an array.

toString() Returns a string representing the array and its elements.

unshift() Adds one or more elements to the front of an array and returns the new length of the array.
Array Methods
var alpha = ["a", "b", "c"]; function printBr(element, index, array) { var arr = new
var numeric = [1, 2, 3]; document.write("<br />[" + index + "] is " + element ); Array("First","Second","Third");
}
var alphaNumeric = alpha.concat(numeric); var str = arr.join();
document.write("alphaNumeric : " + alphaNumeric ); [12, 5, 8, 130, 44].forEach(printBr); document.write("str : " + str );

alphaNumeric : a,b,c,1,2,3 [0] is 12 var str = arr.join(", ");


[1] is 5 document.write("<br />str : " + str );
var passed = [12, 5, 8, 130, 44].every(isBigEnough); [2] is 8
document.write("First Test Value : " + passed ); [3] is 130 var str = arr.join(" + ");
[4] is 44 document.write("<br />str : " + str );
passed = [12, 54, 18, 130, 44].every(isBigEnough);
document.write("Second Test Value : " + passed ); function printBr(element, index, array) { str : First,Second,Third
document.write("<br />[" + index + "] is " + element ); str : First, Second, Third
function isBigEnough(element, index, array) { } str : First + Second + Third
return (element >= 10);
} var index = [12, 5, 8, 130, 44].indexOf(8); var index = [12, 5, 8, 130, 44].lastIndexOf(8);
document.write("index is : " + index ); document.write("index is : " + index );
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
document.write("Filtered Value : " + filtered ); var index = [12, 5, 8, 130, 44].indexOf(13); var index = [12, 5, 8, 130, 44, 5].lastIndexOf(5);
document.write("<br />index is : " + index ); document.write("<br />index is : " + index );
First Test Value : false Second Test Value : true
Filtered Value : 12,130,44 index is : 2 index is : 2
index is : -1 index is : 5
Array Methods
var numbers = [1, 4, 9]; var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
var roots = numbers.map(Math.sqrt); document.write("total is : " + total );
document.write("roots is : " + roots );
total is : 6
roots is : 1,2,3
var total = [0, 1, 2, 3].reduceRight(function(a, b){ return a + b; });
var numbers = [1, 4, 9];
document.write("total is : " + total );
var element = numbers.pop();
document.write("element is : " + element ); total is : 6

var element = numbers.pop(); var arr = [0, 1, 2, 3].reverse();


document.write("<br />element is : " + element ); document.write("Reversed array is : " + arr );

element is : 9 Reversed array is : 3,2,1,0


element is : 4
var element = [105, 1, 2, 3].shift();
var numbers = new Array(1, 4, 9);
document.write("Removed element is : " + element );
var length = numbers.push(10);
document.write("new numbers is : " + numbers ); Removed element is : 105

length = numbers.push(20); var arr = ["orange", "mango", "banana", "sugar", "tea"];


document.write("<br />new numbers is : " + numbers ); document.write("arr.slice( 1, 2) : " + arr.slice( 1, 2) );

new numbers is : 1,4,9,10 arr.slice( 1, 2) : mango


new numbers is : 1,4,9,10,20
Array Methods
function isBigEnough(element, index, array) { var arr = new Array("orange", "mango", "banana", "sugar");
return (element >= 10); var str = arr.toString();
} document.write("Returned string is : " + str );
var retval = [2, 5, 8, 1, 4].some(isBigEnough);
document.write("Returned value is : " + retval ); Returned string is : orange,mango,banana,sugar
var retval = [12, 5, 8, 1, 4].some(isBigEnough);
document.write("<br />Returned value is : " + retval ); var arr = new Array("orange", "mango", "banana", "sugar");
var length = arr.unshift("water");
Returned value is : false document.write("Returned array is : " + arr );
Returned value is : true document.write("<br /> Length of the array is : " + length );

var arr = new Array("orange", "mango", "banana", "sugar"); Returned array is : water,orange,mango,banana,sugar
var sorted = arr.sort(); Length of the array is : 5
document.write("Returned string is : " + sorted );

Returned string is : banana,mango,orange,sugar

var arr = ["orange", "mango", "banana", "sugar", "tea"];


var removed = arr.splice(2, 0, "water");
document.write("After adding 1: " + arr );
document.write("<br />removed is: " + removed);
removed = arr.splice(3, 1);
document.write("<br />After adding 1: " + arr );
document.write("<br />removed is: " + removed);

After adding 1: orange,mango,water,banana,sugar,tea


removed is:
After adding 1: orange,mango,water,sugar,tea
removed is: banana
Number
The Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects
because the browser automatically converts number literals to instances of the number class.
Syntax
The syntax for creating a number object is as follows:
var val = new Number(number);
In the place of number, if you provide any non-number argument, then the argument cannot be converted into a number, it returns NaN (Not-a-Number).

Number Properties
MAX_VALUE The largest possible value a number in JavaScript can have 1.7976931348623157E+308
MIN_VALUE The smallest possible value a number in JavaScript can have 5E-324
NaN Equal to a value that is not a number.
NEGATIVE_INFINITY A value that is less than MIN_VALUE.
POSITIVE_INFINITY A value that is greater than MAX_VALUE
prototype A static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document
constructor Returns the function that created this object's instance. By default this is the Number object.
Number Methods
toExponential() Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation.
toFixed() Formats a number with a specific number of digits to the right of the decimal.
toLocaleString() Returns a string value version of the current number in a format that may vary according to a browser's local settings.
toPrecision() Defines how many total digits (including digits to the left and right of the decimal) to display of a number.
toString() Returns the string representation of the number's value.
valueOf() Returns the number's value.
var num = new Number(15);
document.write("num.toString() is " + num.toString());
document.write("<br />");
Boolean
The Boolean object represents two values, either "true" or "false".
Use the following syntax to create a boolean object.
var val = new Boolean(value);
If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object
has an initial value of false.
Boolean Properties
Constructor - Returns a reference to the Boolean function that created the object.
boolean.constructor()
Prototype - The prototype property allows you to add properties and methods to an object.
object.prototype.name = value
Boolean Methods
toSource() Returns a string containing the source of the Boolean object; you can use this
string to create an equivalent object.
toString() Returns a string of either "true" or "false" depending upon the value of the object.
valueOf() Returns the primitive value of the Boolean object.
Boolean
var bool = new Boolean( );
document.write("bool.constructor() is : " + bool.constructor);
-------------------------------------------------------------------------------------------------------
-
function book(title, publisher)
{
this.title = title;
this.publisher = publisher;
}

var myBook = new book("Perl", "Mohtashim");


book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");

document.write("newBook.toSource() is : "+ newBook.toSource()); ({title:"Perl", publisher:"Mohtashim", price:100})


-------------------------------------------------------------------------------------------------------
-var flag = new Boolean(false);
document.write( "flag.toString is : " + flag.toString() ); flag.toString is : false
-------------------------------------------------------------------------------------------------------
-var flag = new Boolean(false);
document.write( "flag.valueOf is : " + flag.valueOf() ); flag.valueOf is : false
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
constructor Returns a reference to the String function that created the object.
length Returns the length of the string.
prototype The prototype property allows you to add properties and methods to an
object.
String methods
charAt() Returns the character at the specified index.
charCodeAt() Returns a number indicating the Unicode value of the character at the given index.
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
localeCompare() Returns a number indicating whether a reference string comes before or after or is the same as the given string in sorted order.
match() Used to match a regular expression against a string.
replace() Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
search() Executes the search for a match between a regular expression and a specified string.
slice() Extracts a section of a string and returns a new string.
split() Splits a String object into an array of strings by separating the string into substrings.
substr() Returns the characters in a string beginning at the specified location through the specified number of characters.
substring() Returns the characters in a string between two indexes into the string.
toLocaleLowerCase() The characters within a string are converted to lower case while respecting the current locale.
toLocaleUpperCase() The characters within a string are converted to upper case while respecting the current locale.
toLowerCase() Returns the calling string value converted to lower case.
toString() Returns a string representing the specified object.
toUpperCase() Returns the calling string value converted to uppercase.
valueOf() Returns the primitive value of the specified object.
String methods examples
var str = new String( "This is string" ); var str = "Apples are round, and Apples are Juicy.";
document.writeln("str.charAt(0) is:" + str.charAt(0)); document.write(str.toLocaleLowerCase( ));
document.writeln("str.charCodeAt(0) is:" + str.charCodeAt(0));
var str = "Apples are round, and Apples are Juicy.";
var str1 = new String( "This is string one" ); document.write(str.toLocaleUpperCase( ));
var str2 = new String( "This is string two" );
var str3 = str1.concat( str2 ); var str = "Apples are round, and Apples are Juicy.";
document.writeln("Concatenated String :" + str3); document.write(str.toLowerCase( ));

var str1 = new String( "This is string one" ); var str = "Apples are round, and Apples are Juicy.";
var index = str1.indexOf( "string" ); document.write(str.toString( ));
document.writeln("indexOf found String :" + index );
var str = "Apples are round, and Apples are Juicy.";
var str1 = new String( "This is string one and again string" ); document.write(str.toUpperCase( ));
var index = str1.lastIndexOf( "string" );
document.write("lastIndexOf found String :" + index ); var str = new String("Hello world");
document.write(str.valueOf( ));
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
document.write(newstr );

var str = "Apples are round, and apples are juicy.";


var splitted = str.split(" ", 3);
document.write( splitted );

var str = "Apples are round, and apples are juicy.";


document.write("(1,2): " + str.substr(1,2));
String HTML Wrappers
Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML
tag.
anchor() Creates an HTML anchor that is used as a hypertext target.
big() Creates a string to be displayed in a big font as if it were in a <big> tag.
blink() Creates a string to blink as if it were in a <blink> tag.
bold() Creates a string to be displayed as bold as if it were in a <b> tag.
fixed() Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag
fontcolor() Causes a string to be displayed in the specified color as if it were in a <font color="color"> tag.
fontsize() Causes a string to be displayed in the specified font size as if it were in a <font size="size"> tag.
italics() Causes a string to be italic, as if it were in an <i> tag.
link() Creates an HTML hypertext link that requests another URL.
small() Causes a string to be displayed in a small font, as if it were in a <small> tag.
strike() Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.
sub() Causes a string to be displayed as a subscript, as if it were in a <sub> tag
sup() Causes a string to be displayed as a superscript, as if it were in a <sup> tag
String HTML Wrappers example
Date object
The Date object is a datatype built into the JavaScript language. Date
objects are created with the new Date() as shown below.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,
Date Properties
constructor Specifies the function that creates an object's prototype.
prototype The prototype property allows you to add properties and methods
to an object.month,date[,hour,minute,second,millisecond ])
Date methods
Date() Returns today's date and time

getDate() Returns the day of the month for the specified date according to local time.

getDay() Returns the day of the week for the specified date according to local time.

getFullYear() Returns the year of the specified date according to local time.

getHours() Returns the hour in the specified date according to local time.

getMilliseconds() Returns the milliseconds in the specified date according to local time.

getMinutes() Returns the minutes in the specified date according to local time.

getMonth() Returns the month in the specified date according to local time.

getSeconds() Returns the seconds in the specified date according to local time.

getTime() Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.

toLocaleFormat() Converts a date to a string, using a format string.

toLocaleString() Converts a date to a string, using the current locale's conventions.

toLocaleTimeString() Returns the "time" portion of the Date as a string, using the current locale's conventions.

toSource() Returns a string representing the source for an equivalent Date object; you can use this value to create a new object.

toString() Returns a string representing the specified Date object.

toTimeString() Returns the "time" portion of the Date as a humanreadable string.

toUTCString() Converts a date to a string, using the universal time convention.


var dt = Date();document.write("Date and Time : " + dt );
valueOf() Returns the primitive value of a Date object.
Date and Time : Tue Jun 06 2017 20:01:59 GMT+0530 (India Standard Time)
And lot many
Math object
The math object provides you properties and methods for mathematical constants and functions.
Unlike other global objects, Math is not a constructor.
All the properties and methods of Math are static and can be called by using Math as an object
without creating it.
The syntax to call the properties and methods of Math are as follows:
var pi_val = Math.PI;
var sine_val = Math.sin(30);
Math Properties
E Euler's constant and the base of natural logarithms, approximately 2.718.
LN2 Natural logarithm of 2, approximately 0.693.
LN10 Natural logarithm of 10, approximately 2.302.
LOG2E Base 2 logarithm of E, approximately 1.442.
LOG10E Base 10 logarithm of E, approximately 0.434.
PI Ratio of the circumference of a circle to its diameter, approximately 3.14159.
SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
SQRT2 Square root of 2, approximately 1.414.
Math Methods
Math Methods
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
asin() Returns the arcsine (in radians) of a number.
atan() Returns the arctangent (in radians) of a number.
atan2() Returns the arctangent of the quotient of its arguments.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns the cosine of a number.
exp() Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is, base exponent.
random() Returns a pseudo-random number between 0 and 1.
round() Returns the value of a number rounded to the nearest integer.
var value = Math.abs(-1);
sin() Returns the sine of a number.
document.write("First Test Value : " + value );
sqrt() Returns the square root of a number.
tan() Returns the tangent of a number. var value = Math.abs("string");
toSource() Returns the string "Math". document.write("<br />Fourth Test Value : " + value );

var value = Math.ceil(45.95);


document.write("First Test Value : " + value );
Errors and Exception
There are three types of errors in programming:
(a) Syntax Errors,
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.
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.
(b) 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.
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal
execution.
(c) 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.
Exception handling
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:
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.
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
}]
Exception handling
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
try {
document.write ("Value of variable a is : " + a ); Value of variable a is : 100
call();
}
catch ( e ) {
document.write ("<br>"+ "Error: " + e.description ); Error: undefined
}
finally {
document.write ("Finally block will always execute!" ); 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>
Exception handling - The throw Statement
You can use a throw statement to raise your built-in exceptions or your customized exceptions.
Later these exceptions can be captured and you can taken an appropriate action.
function myFunc()
{
var a = 100;
var b = 0;
try{
if ( b == 0 ){
throw( "Divide by zero error." );
}
else{
var c = a / b; Error: Divide by zero error.
}
}
catch ( e ) {
document.write ("Error: " + e );
}
}
Exception handling - The onerror( ) Method
The onerror event handler was the first feature to facilitate error handling in
JavaScript.
The error event is fired on the window object whenever an exception occurs on
the page.
The onerror event handler provides three pieces of information to identify the
exact nature of the error:
Error message: The same message that the browser would display for the given error
URL: The file in which the error occurred
Line number: The line number in the given URL that caused the error
Exception handling - The onerror( ) Method
<html> <html>
<head> <head>
<script type="text/javascript"> <script type="text/javascript">
<!-- <!--
window.onerror = function () { window.onerror = function (msg, url, line) {
document.write ("An error occurred."); document.write ("Message : " + msg );
} document.write ("url : " + url );
//--> document.write ("Line number : " + line );
</script> }
</head> //-->
<body> </script>
<p>Click the following to see the result:</p> </head>
<form> <body>
<input type="button" value="Click Me" onclick="myFunc();" /> <p>Click the following to see the result:</p>
</form> <form>
</body> <input type="button" value="Click Me" onclick="myFunc();" />
</html> </form>
</body>
An error occurred. </html>
Message : ReferenceError: myFunc is not defined
url : https://cg6.tutorialspoint.com/assets/workspace/t2Rtsjya/DgdA576h/index.htm
Line number : 1
References
https://www.w3schools.com/js/default.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript
https://github.com/GoogleChrome/samples
J S
AVA CRIPT

You might also like