0% found this document useful (0 votes)
50 views

Javascript Complete Notes

Bsc cs

Uploaded by

terencefreefire
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Javascript Complete Notes

Bsc cs

Uploaded by

terencefreefire
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

JavaScript

(Compiled by KUMARESAN.K, Asst. Professor in Computer Science,


Sri. C. Achuthamenon Govt. College, Kuttanellur, Thrissur)
(Source: www.tutorialsteacher.com)

What is JavaScript
JavaScript is a loosely-typed client side scripting language that executes in the
user's browser. JavaScript interact with html elements (DOM elements) in order to
make interactive web user interface.

JavaScript implements ECMAScript standards, which includes core features based


on ECMA-262 specification as well as other features which are not based on
ECMAScript standards.

JavaScript Example
JavaScript can be used in various activities like data validation, display popup
messages, handling different events of DOM elements, modifying style of DOM
elements etc. The following sample form uses JavaScript to validate data and
change color of form.

JavaScript History
In early 1995, Brendan Eich from Netscape, took charge of design and
implementation of a new language for non-java programmers to give access of
newly added Java support in Netscape navigator.
Eich eventually decided that a loosely-typed scripting language suited the
environment and audience, web designers and developers who needed to be able
to tie into page elements (such as forms, or frames, or images) without a
bytecode compiler or knowledge of object-oriented software design. The dynamic
nature of the language led to it being named "LiveScript" but was quickly renamed
to "JavaScript" Know more about JavaScript history.

JavaScript Engine
JavaScript engine in the browser interprets, compiles and executes JavaScript code
which is in a web page. It does memory management, JIT compilation, type
system etc. Each browser includes different JavaScript engines.

Browser JavaScript Engine


Internet Explorer v9.0+ Chakra
Chrome V8
FireFox JagerMonkey
Opera v 14+ V8
Safari JavaScriptCore (Nitro)

Comparison with Server-side Languages


JavaScript is different when compared to server side languages like Java and C#.

The following table lists the differences.

C# Java JavaScript
Strongly-Typed Strongly-Typed Loosely-Typed
Static Static Dynamic
Classical Inheritance Classical Inheritance Prototypal
Classes Classes Functions
Constructors Constructors Functions
Methods Methods Functions

Advantages of JavaScript
1. JavaScript is easy to learn.
2. It executes on client's browser, so eliminates server side processing.
3. It executes on any OS.
4. JavaScript can be used with any type of web page e.g. PHP, ASP.NET, Perl etc.
5. Performance of web page increases due to client side execution.
6. JavaScript code can be minified to decrease loading time from server.
7. Many JavaScript based application frameworks are available in the market to create
Single page web applications e.g. ExtJS, AngularJS, KnockoutJS etc.

Script Tag
Any type of client side script can be written inside <script> tag in html. The script
tag identifies a block of script code in the html page. It also loads a script file with
src attribute.

The JavaScript code can also be embedded in <script> tag as shown below.

Example: <script> tag


<script>

//write JavaScript here..

</script>

Html 4.x requires type attribute in script tag. The type attribute is used to identify
the language of script code embedded within script tag. This is specified as MIME
type e.g. text/javascript, text/ecmascript, text/vbscript etc. So, for the JavaScript
code, specify type="text/javascript" in the script tag in html 4.x page.

Example: Script tag in HTML 4.x:


<script type="text/javascript">

//write JavaScript here..

</script>

Html 5 page does not require type attribute in the <script> tag, because in HTML
5 the default script language is JavaScript

Script File
If you don't want to write JavaScript between script tag in a web page then you
can also write JavaScript code in a separate file with .js extension and include it in
a web page using <script> tag and reference the file via src attribute.

<script src="/PathToScriptFile.js"></script>
The script tag can appear any number of times in the <head> or <body> tag.

Script Tag into <head> Tag


You can include script tag into head tag as shown below.

Example: Script tag into <head> tag


<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JavaScript Demo</title>
<script>
//write JavaScript code here.

</script>
<script src="/PathToScriptFile.js"></<script> @* External JavaScript file *@
</head>
<body>
<h1> JavaScript Tutorials</h1>

<p>This is JavaScript sample.</p>

</body>
</html>

The browser loads all the scripts in head tag before loading and rendering body
html. It is recommended to include scripts before ending body tag if scripts are not
required while window is loading.

Script at the end of <body>


Scripts can also be added at the end of body tag. This way you can be sure that all
the web page resources are loaded and it is safe to interact with DOM.

Example: Script at the end of <body> tag:


<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JavaScript Demo</title>

</head>
<body>
<h1> JavaScript Tutorials</h1>
<p>This is JavaScript sample.</p>

<!--Some HTML here.. -->

<script>
//write JavaScript code here..

</script>
<script src="/PathToScriptFile.js"></<script> @* External JavaScript file *@
</body>
</html>

JavaScript Overview
Learn some important characteristics of JavaScript syntax in this section.

Character Set
JavaScript uses the Unicode character set and so allows almost all characters, punctuations, and
symbols.

Case Sensitive
JavaScript is a case sensitive scripting language. It means functions, variables and keywords are
case sensitive. For example, VAR is different from var, John is not equal to john.

String
String is a text in JavaScript. A text content must be enclosed in double or single quotation marks.

Example: string
<script>

"Hello World" //JavaScript string in double quotes

'Hello World' //JavaScript string in single quotes

</script>
Number
JavaScript allows you to work with any kind of numbers like integer, float, hexadecimal etc.
Number must NOT be wrapped in quotation marks.

Integer: 1000

Float: 10.2

Boolean
As in other languages, JavaScript also includes true or false as a boolean value.

Semicolon
JavaScript statements are separated by a semicolon. However, it is not mandatory to end every
statement with a semicolon but it is recommended.

For example, JavaScript considers three different statements for following:

one = 1; two=2; three=3;

White space
JavaScript ignores multiple spaces and tabs.

The following statements are same.

Example: JavaScript ignores whitespaces


var one =1;
var one = 1;
var one = 1;

Comments
A comment is a single or multiple lines, which give some information about the current program.
Comments are not for execution.

Write comment after double slashes // or write multiple lines of comments between/* and */

Example: code comment


var one =1; // this is a single line comment

/* this
is multi line
comment*/
var two = 2;
var three = 3;

Keywords
Keywords are reserved words in JavaScript, which cannot be used as variable names or function
names.

The following table lists some of the keywords used in JavaScript.

Keywords
var function if
else do while
for switch break
continue return try
catch finally debugger
case class this
default false true
in instanceOf typeOf
new null throw
void width delete

Display Popup Message Box


JavaScript provides different built-in functions to display popup messages for different purposes
e.g. to display a simple message or display a message and take user's confirmation on it or display
a popup to take a user's input value.

Alert Box
Use alert() function to display a popup message to the user. This popup will have OK button to
close the popup.

Example: Alert Box


alert("This is alert box!"); // display string message

alert(100); // display number

alert(true); // display boolean

The alert function can display message of any data type e.g. string, number, boolean etc. There is
no need to convert a message to string type.
Confirm Box
Sometimes you need to take the user's confirmation to proceed. For example, you want to take
user's confirmation before saving updated data or deleting existing data. In this scenario, use
JavaScript built-in function confirm(). The confirm() function displays a popup message to the user
with two buttons, OK and Cancel. You can check which button the user has clicked and proceed
accordingly.

The following example demonstrates how to display a confirm box and then checks which button
the user has clicked.

Example: Confirm Box


var userPreference;

if (confirm("Do you want to save changes?") == true) {


userPreference = "Data saved successfully!";
} else {
userPreference = "Save Cancelled!";
}

Prompt Box
Sometimes you may need to take the user's input to do further actions in a web page. For
example, you want to calculate EMI based on users' preferred tenure of loan. For this kind of
scenario, use JavaScript built-in function prompt().

Prompt function takes two string parameters. First parameter is the message to be displayed and
second parameter is the default value which will be in input text when the message is displayed.

Syntax:
prompt([string message], [string defaultValue]);
Example: prompt Box
var tenure = prompt("Please enter preferred tenure in years", "15");

if (tenure != null) {
alert("You have entered " + tenure + " years" );
}

As you can see in the above example, we have specified a message as first parameter and default
value "15" as second parameter. The prompt function returns a user entered value. If user has not
entered anything then it returns null. So it is recommended to check null before proceeding.

Note:
The alert, confirm and prompt functions are global functions. So it can be called using window object
like window.alert(), window.confirm() and window.prompt().
JavaScript Variable
Variable means anything that can vary. JavaScript includes variables which hold
the data value and it can be changed anytime.

JavaScript uses reserved keyword var to declare a variable. A variable must have
a unique name. You can assign a value to a variable using equal to (=) operator
when you declare it or before using it.

Syntax:
var <variable-name>;

var <variable-name> = <value>;


Example: Variable Declaration & Initialization
var one = 1; // variable stores numeric value

var two = 'two'; // variable stores string value

var three; // declared a variable without assigning a value

In the above example, we have declared three variables using var keyword: one,
two and three. We have assigned values to variables one and two at the same
time when we declared it, whereas variable three is declared but does not hold any
value yet, so it's value will be 'undefined'.

Declare Variables in a Single Line


Multiple variables can also be declared in a single line separated by comma.

Example: Multiple Variables in a Single Line


var one = 1, two = 'two', three;

Declare a Variable without var Keyword


JavaScript allows variable declaration without var keyword. You must assign a
value when you declare a variable without var keyword.

Example: Variable without var Keyword


one = 1;

two = 'two';
Note:
It is Not Recommended to declare a variable without var keyword. It can accidently
overwrite an existing global variable.

Scope of the variables declared without var keyword become global irrespective of
where it is declared. Global variables can be accessed from anywhere in the web
page. Visit Scope for more information.

White Spaces and Line Breaks in JavaScript


JavaScript allows multiple white spaces and line breaks when you declare a
variable with var keyword.

Example: Whitespace and Line Breaks


var
one
=

1,
two
=
"two"

Please note that semicolon is optional.

Loosely-typed Variables
C# or Java has strongly typed variables. It means variable must be declared with
a particular data type, which tells what type of data the variable will hold.

JavaScript variables are loosely-typed which means it does not require a data type
to be declared. You can assign any type of literal values to a variable e.g. string,
integer, float, boolean etc..

Example: Loosely Typed Variables


var one =1; // numeric value

one = 'one'; // string value

one= 1.1; // decimal value

one = true; // Boolean value

one = null; // null value


Points to Remember :

1. Variable stores a single data value that can be changed later.


2. Variables
es can be defined using var keyword. Variables defined without var keyword
become global variables.
3. Variables must be initialized before using.
4. Multiple variables can be defined in a single line. e.g. var one = 1, two = 2, three =
"three";
5. Variables in JavaScript
aScript are loosely
loosely-typed
typed variables. It can store value of any data
type through out it's life time.

Javascript Operators
JavaScript includes operators as in other languages. An operator performs some
operation on single or multiple operands (data value) and produces a result. For
example 1 + 2, where + sign is an operator and 1 is left operand and 2 is right
operand. + operator adds two numeric values and produces a result which is 3 in
this case.

Syntax:
<Left operand> operator <right
right operand
operand>

<Left operand> operator

JavaScript includes following categories of operators.

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators

Arithmetic Operators
Arithmetic operators are used to perform mathematical operations
operatio between
numeric operands.

Operator Description
+ Adds two numeric operands.
- Subtract right operand from left operand
Operator Description
* Multiply two numeric operands.
/ Divide left operand by right operand.
% Modulus operator. Returns remainder of two operands.
++ Increment operator. Increase operand value by one.
-- Decrement operator. Decrease value by one.

The following example demonstrates how arithmetic operators perform different


tasks on operands.

Example: Arithmetic Operator


var x = 5, y = 10, z = 15;

x + y; //returns 15

y - x; //returns 5

x * y; //returns 50

y / x; //returns 2

x % 2; //returns 1

x++; //returns 6

x--; //returns 4

+ operator performs concatenation operation when one of the operands is of string


type.

The following example shows how + operator performs operation on operands of


different data types.

Example: + operator
var a = 5, b = "Hello ", c = "World!", d = 10;

a + b; // "5Hello "

b + c; // "Hello World!"

a + d; // 15
Comparison Operators
JavaScript language includes operators that compare two operands and return
Boolean value true or false.

Operators Description
== Compares the equality of two operands without considering type.
=== Compares equality of two operands with type.
!= Compares inequality of two operands.
> Checks whether left side value is greater than right side value. If yes then returns true otherwise false.
< Checks whether left operand is less than right operand. If yes then returns true otherwise false.
>= Checks whether left operand is greater than or equal to right operand. If yes then returns true otherwise false.
<= Checks whether left operand is less than or equal to right operand. If yes then returns true otherwise false.

The following example demonstrates how comparison operators perform different


tasks.

Example: Comparison Operators


var a = 5, b = 10, c = "5";
var x = a;

a == c; // returns true

a === c; // returns false

a == x; // returns true

a != b; // returns true

a > b; // returns false

a < b; // returns true

a >= b; // returns false

a <= b; // returns true

a >= c; // returns true

a <= c; // returns true


Logical Operators
Logical operators are used to combine two or more conditions. JavaScript includes
following logical operators.

Operator Description
&& && is known as AND operator. It checks whether two operands are non-zero (0, false, undefined, null or "" are
considered as zero), if yes then returns 1 otherwise 0.
|| || is known as OR operator. It checks whether any one of the two operands is non-zero (0, false, undefined,
null or "" is considered as zero).
! ! is known as NOT operator. It reverses the boolean result of the operand (or condition)
Example: Logical Operators
var a = 5, b = 10;

(a != b) && (a < b); // returns true

(a > b) || (a == b); // returns false

(a < b) || (a == b); // returns true

!(a < b); // returns false

!(a > b); // returns true

Assignment Operators
JavaScript includes assignment operators to assign values to variables with less
key strokes.

Assignment
operators Description
= Assigns right operand value to left operand.
+= Sums up left and right operand values and assign the result to the left
operand.
-= Subtract right operand value from left operand value and assign the result to
the left operand.
*= Multiply left and right operand values and assign the result to the left
operand.
/= Divide left operand value by right operand value and assign the result to the
left operand.
%= Get the modulus of left operand divide by right operand and assign resulted
modulus to the left operand.
Example: Assignment operators
var x = 5, y = 10, z = 15;
x = y; //x would be 10

x += 1; //x would be 6

x -= 1; //x would be 4

x *= 5; //x would be 25

x /= 5; //x would be 1

x %= 2; //x would be 1

Ternary Operator
JavaScript includes special operator called ternary operator :? that assigns a value
to a variable based on some condition. This is like short form of if
if--else condition.

Syntax:
<condition> ? <value1> : <value2>;

Ternary operator
ator starts with conditional expression followed by ? operator. Second
part ( after ? and before : operator) will be executed if condition turns out to be
true. If condition becomes false then third part (after :) will be executed.

Example: Ternary operato


operator
var a = 10, b = 5;

var c = a > b? a : b; // value of c would be 10


var d = a > b? b : a; // value of d would be 5

Points to Remember :

1. JavaScript includes operators that perform some operation on single or multiple


operands (data value) and produce a result.
2. JavaScript includes various categories of operators: Arithmetic operators,
Comparison operators, Logical operators, Assignment op
operators,
erators, Conditional operators.
3. Ternary operator ?: is a conditional operator.

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.

JavaScript includes primitive and non-primitive data types as per latest ECMAScript
5.1.

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.

Example: Loosely-typed JavaScript


var myVar = 100;
myVar = true;
myVar = null;
myVar = undefined;
myVar = "Steve";

alert(myVar); // 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


var str1 = "Hello World";

var str2 = 'Hello World';

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

Example: String as array


var str = 'Hello World';

str[0] // H
str[1] // e
str[2] // l
str[3] // l
str[4] // o

str.length // 11

Since, string is character index, it can be accessed using for loop and for-of loop.

Example: Iterate String


var str = 'Hello World';

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


console.log(str[i]);

for(var ch of str)
console.log(ch);

Concatenation
A string is immutable in JavaScript, it can be concatenated using plus (+) operator
in JavaScript.

Example: String concatenation


var str = 'Hello ' + "World " + 'from ' + 'TutorialsTeacher ';
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.

Example: Quotes in string


var str1 = "This is 'simple' string";

var str2 = 'This is "simple" string';

If you want to include same quotes in a string value as surrounding quotes then
use backward slash (\) before quotation mark inside string value.

Example: Quotes in string


var str1 = "This is \"simple\" string";

var str2 = 'This is \'simple\' string';

String object
Above, we assigned a string literal to a variable. JavaScript allows you to create a
String object using the new keyword, as shown below.

Example: String object


var str1 = new String();
str1 = 'Hello World';

// or

var str2 = new String('Hello World');

In the above example, JavaScript returns String object instead of primitive string
type. It is recommended to use primitive string instead of String object.

Caution:

Be careful while working with String object because comparison of string objects
using == operator compares String objects and not the values. Consider the
following example.
Example: String object comparison
var str1 = new String('Hello
'Hello World'
World');
var str2 = new String('Hello
'Hello World'
World');
var str3 = 'Hello World';
var str4 = str1;

str1 == str2; // false - because str1 and str2 are two different objects
str1 == str3; // true
str1 === str4; // true

typeof(str1); // object
typeof(str3); //string

Learn about JavaScript string properties and methods in the next section.

Points to Remember :

1. JavaScript string must be enclosed in double or single quot


quotes
es (" " or ' ').
2. String can be assigned to a variable using = operator.
3. Multiple strings can be concatenated using + operator.
4. A string can be treated as character array.
5. Use back slash (\)) to include quotation marks inside string.
6. String objects can be created
eated using new keyword. e.g. var str = new String();
7. String methods are used to perform different task on strings.

JavaScript String Methods & Properties


JavaScript string (primitive or String object) includes default properties and methods which you
can use for different purposes.

String Properties
Property Description
length Returns the length of the string.

String Methods
Method Description
charAt(position) Returns the character at the specified position (in Number).
charCodeAt(position) Returns a number indicating the Unicode value of the character at the given
position (in Number).
Method Description
concat([string,,]) Joins specified string literal values (specify multiple strings separated by
comma) and returns a new string.
indexOf(SearchString, Position) Returns the index of first occurrence of specified String starting from specified
number index. Returns -1 if not found.
lastIndexOf(SearchString, Returns the last occurrence index of specified SearchString, starting from
Position) specified position. Returns -1 if not found.
localeCompare(string,position) Compares two strings in the current locale.
match(RegExp) Search a string for a match using specified regular expression. Returns a
matching array.
replace(searchValue, Search specified string value and replace with specified replace Value string and
replaceValue) return new string. Regular expression can also be used as searchValue.
search(RegExp) Search for a match based on specified regular expression.
slice(startNumber, endNumber) Extracts a section of a string based on specified starting and ending index and
returns a new string.
split(separatorString, Splits a String into an array of strings by separating the string into substrings
limitNumber) based on specified separator. Regular expression can also be used as separator.
substr(start, length) Returns the characters in a string from specified starting position through the
specified number of characters (length).
substring(start, end) Returns the characters in a string between start and end indexes.
toLocaleLowerCase() Converts a string to lower case according to current locale.
toLocaleUpperCase() Converts a sting to upper case according to current locale.
toLowerCase() Returns lower case string value.
toString() Returns the value of String object.
toUpperCase() Returns upper case string value.
valueOf() Returns the primitive value of the specified string object.

String Methods for Html


The following string methods convert the string as a HTML wrapper element.

Method Description
anchor() Creates an HTML anchor <a>element around string value.
big() Wraps string in <big> element.
blink() Wraps a string in <blink> tag.
bold() Wraps string in <b> tag to make it bold in HTML.
fixed() Wraps a string in <tt> tag.
fontcolor() Wraps a string in a <font color="color"> tag.
fontsize() Wraps a string in a <font size="size"> tag.
italics() Wraps a string in <i> tag.
link() Wraps a string in <a>tag where href attribute value is set to specified string.
small() Wraps a string in a <small>tag.
strike() Wraps a string in a <strike> tag.
sub() Wraps a string in a <sub>tag
sup() Wraps a string in a <sup>tag
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.

Example: Number in JavaScript


var int = 100;
var float = 100.5;
var hex = 0xfff;
var exponential = 2.56e3;
var octal = 030;

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.

Example: Number Object Comparison


var num1 = new Number(100);
var num2 = new Number(100);

var num3 = 100;

num1 == num2; // false - because num1 and num2 are two different objects
num1 == num3; // true
num1 === num3;//false

typeof(num1); // object
typeof(num3); //number

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
ing 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_INFINITY Returns negative infinity ((-Infinity)
NaN Represents a value that is not a number.
POSITIVE_INFINITY Represents positive infinity (Infinity).
Example: Number properties
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
);

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

Method Description
toExponential(fractionDigits) Returns exponential value as a string.

Example:
var num = 100; Num.toExponential(2); // returns '1.00e+2'
toFixed(fractionDigits) Returns string of decima
decimall value of a number based on specified fractionDigits.

Example:
var num = 100; Num.toFixed(2); // returns '100.00'
toLocaleString() Returns a number as a string value according to a browser's locale settings.

Example:
var num = 100; Num.toLocaleString()
Num.toLocaleString(); // returns '100'
toPrecision(precisionNumber) Returns number as a string with specified total digits.

Example:
var num = 100; Num.toPrecision(4); // returns '100.0'
toString() Returns the string representation of the number value.

Example:
var num = 100; Num.toString(); // returns '100'
valueOf() Returns the value of Number object.

Example: var num = new Number(100); Num.valueOf(); // returns '100'

Points to Remember :
1. JavaScript Number can store various numeric values like integer, float, hexadecimal,
hexade
decimal, exponential and octal values.
2. Number object can be created using new keyword. e.g. var num = new Number(100);
3. Number type includes default properties - MAX_VALUE, MIN_VALUE,
NEGATIVE_INFINITY, NaN and POSITIVE_INFINITY.
4. Number methods are used
sed to perform different tasks on numbers.

JavaScript Array
We have learned that a variable can hold only one value, for example var i = 1,
we can assign only one literal value to i. We cannot assign multiple literal values to
a variable i. To overcome this
is problem, JavaScript provides an array.

An array is a special type of variable, which can store multiple values using special
syntax. Every value is associated with numeric index starting with 0. The following
figure illustrates how an array stores value
values.

JavaScript Array

Array Initialization
An array in JavaScript can be defined and initialized in two ways, array literal and
Array constructor syntax.

Array Literal
Array literal syntax is simple. It takes a list of values separated by a comma and
enclosed in square brackets.

Syntax:
var <array-name>
name> = [element0, element1, element2,... elementN];

The following example shows how to define and initialize an array using array
literal syntax.

Example: Declare and Initialize JS Array


var stringArray = ["one", "two", "three"];

var numericArray = [1, 2, 3, 4];

var decimalArray = [1.1, 1.2, 1.3];

var booleanArray = [true, false, false, true];

var mixedArray = [1, "two", "three", 4];

JavaScript array can store multiple element of different data types. It is not
required to store value of same data type in an array.

Array Constructor
You can initialize an array with Array constructor syntax using new keyword.

The Array constructor has following three forms.

Syntax:
var arrayName = new Array();

var arrayName = new Array(Number length);

var arrayName = new Array(element1, element2, element3,... elementN);

As you can see in the above syntax, an array can be initialized


using new keyword, in the same way as an object.

The following example shows how to define an array using Array constructor
syntax.

Example: Array Constructor Syntax


var stringArray = new Array();
stringArray[0] = "one";
stringArray[1] = "two";
stringArray[2] = "three";
stringArray[3] = "four";

var numericArray = new Array(3);


numericArray[0] = 1;
numericArray[1] = 2;
numericArray[2] = 3;

var mixedArray = new Array(1, "two", 3, "four");


Please note that array can only have numeric index (key). Index cannot be of
string or any other data type. The following syntax is incorrect.
Example: Incorrect Array Index
var stringArray = new Array();

stringArray["one"] = "one";
stringArray["two"] = "two";
stringArray["three"] = "three";
stringArray["four"] = "four";

Accessing Array Elements


An array elements (values) can be accessed using index (key). Specify an index in
square bracket with array name to access the element at particular index. Please
note that index of an array starts from zero in JavaScript.

Example: Access Array Elements


var stringArray = new Array("one", "two", "three", "four");

stringArray[0]; // returns "one"


stringArray[1]; // returns "two"
stringArray[2]; // returns "three"
stringArray[3]; // returns "four"

var numericArray = [1, 2, 3, 4];


numericArray[0]; // returns 1
numericArray[1]; // returns 2
numericArray[2]; // returns 3
numericArray[3]; // returns 4

Array Properties
Array includes "length" property which returns number of elements in the array.

Use for loop to access all the elements of an array using length property.

Example: Access Array using for Loop


var stringArray = new Array("one", "two", "three", "four");

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


{
stringArray[i];
}
Points to Remember :

1. An array is a special type of variable that stores multiple values using a special
syntax.
2. An array can be created using array literal or Array constructor syntax.
3. Array literal syntax: var stringArray = ["one", "two", "three"];
4. Array constructor syntax:var
var numericArray = new Array(3);
5. A single array can store values of different data types.
6. An array elements (values) can be accessed using zero based index (key). e.g.
array[0].
7. An array index must be numeric.
8. Array includes length property and various methods to operate on array objects.

Array Methods Reference


The following table lists all the Array methods.

Method Description
concat() Returns new array by combining values of an array that is specified as parameter with existing array values.
every() Returns true or false if every element in the specified array satisfies a condition specified in the callback
function. Returns false even if single element does not sa satisfy the condition.
filter() Returns a new array with all the elements that satisfy a condition specified in the callback function.
forEach() Executes a callback function for each elements of an array.
indexOf() Returns the index of the first occurrenc
occurrence of the specified element in the array, or -1 1 if it is not found.
join() Returns string of all the elements separated by the specified separator
lastIndexOf() Returns the index of the last occurrence of the specified element in the array, or -1 1 if it is not 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 at the end of an array and retu returns
rns the new length of the array.
reduce() Pass two elements simultaneously in the callback function (till it reaches the last element) and returns a single
value.
reduceRight() Pass two elements simultaneously in the callback function from right right-to-left (till it reaches the last element)
and returns a single value.
reverse() Reverses the elements of an array. Element at last index will be first and element at 0 index will be last.
shift() Removes the first element from an array and returns that element.
slice() Returns a new array with specified start to end elements.
some() Returns true if at least one element in this array satisfies the condition in the callback function.
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.
Method Description
unshift() Adds one or more elements to the front of an array and returns the new length of the array.

JavaScript - Date
JavaScript provides Date object to work with date & time including days, months,
years, hours, minutes, seconds and milliseconds.

The following example shows how to display current date and time using Date
object in JavaScript.

Example: Current Local Date


Date(); //current date

//or

var currentDate = new Date(); //current date

As you can see in the above example, we can display current date and time either
by calling Date as function or creating an object with new keyword.

In order to work with date other than current date and time, we must create a
date object by specifying different parameters in the Date constructor.

Syntax:
var dt = new Date();

var dt = new Date(milliseconds);

var dt = new Date('date string');

var dt = new Date(year, month[, date, hour, minute, second, millisecond]);

As per the above syntax, the following parameters can be specified in Date
constructor.

 No Parameter: Date object will be set to current date & time if no parameter is
specified in the constructor.
 Milliseconds: Milliseconds can be specified as numeric parameter. The date object
will calculate date & time by adding specified numeric milliseconds from mid night of
1/1/1970
 Date string: String parameter will be treated as a date and will be parsed using
Date.parse method.
Overload of Date constructor includes following seven numeric parameters.

 year: Numeric value to represent year of a date.


 month: Numeric value to represent month of a date. Starts with 0 for January till 11
for December
 date: Numeric value to represent day of a date (optional).
 hour: Numeric value to represent hour of a day (optional).
 minute: Numeric value to represent minute of a time segment (optional).
 second: Numeric value to represent second of a time segment (optional).
 millisecond: Numeric value to represent millisecond of a time segment(optional).
Specify numeric milliseconds in the constructor to get the date and time elapsed from
1/1/1970.

In the following example, date object is created by passing milliseconds in Date


constructor. So date will be calculated based on milliseconds elapsed from
1/1/1970.

Example: Create Date by Specifying Milliseconds


var date1 = new Date(0); // Thu Jan 01 1970 05:30:00

var date2 = new Date(1000); // Thu Jan 01 1970 05:30:01

var date3 = new Date(5000); // Thu Jan 01 1970 05:30:05

Specify any valid date as a string to create new date object for the specified date.
The following example shows various formats of date string which you can specify
in a Date constructor.

Example: Create Date by Specifying Date String


var date1 = new Date("3 march 2015");

var date2 = new Date("3 February, 2015");

var date3 = new Date("3rd February, 2015"); // invalid date

var date4 = new Date("2015 3 February");

var date5 = new Date("3 2015 February ");

var date6 = new Date("February 3 2015");

var date7 = new Date("February 2015 3");

var date8 = new Date("2 3 2015");

var date9 = new Date("3 march 2015 20:21:44");


You can use any valid separator in date string to differentiate date segments.

Example: Create Date using Different Date Separator


var date1 = new Date("February 2015-3");

var date2 = new Date("February-2015-3");

var date3 = new Date("February-2015-3");

var date4 = new Date("February,2015-3");

var date5 = new Date("February,2015,3");

var date6 = new Date("February*2015,3");

var date7 = new Date("February$2015$3");

var date8 = new Date("3-2-2015"); // MM-dd-YYYY

var date9 = new Date("3/2/2015"); // MM-dd-YYYY

Specify seven numeric values to create a date object with specified year, month
and optionally date, hours, minutes, seconds and milliseconds.

Example: Date
var dt = new Date(2014, 2, 3, 10, 30, 50, 800); // Mon Feb 03 2014 10:30:50

Date Methods
The JavaScript Date object includes various methods to operate on it. Use different
methods to get different segments of date like day, year, month, hour, seconds or
milliseconds in either local time or UTC time.

Example: Date Methods


var date = new Date('4-1-2015');

date.getDay();// returns 3

date.getYear();// returns 115, no of years after 1900

date.getFullYear();// returns 2015

date.getMonth();// returns 3, starting 0 with jan


date.getUTCDate();// returns 31

Visit Date Methods Reference to know about all the date methods.

Date Formats
JavaScript supports ISO 8601 date format by default - YYYY-MM-DDTHH:mm:ss.sssZ

Example: ISO Date Format


var dt = new Date('2015-02-10T10:12:50.5000z');

Convert Date Format


Use different Date methods to convert a date from one format to another format
e.g. to Universal Time, GMT or local time format.

For example, use ToUTCString(), ToGMTString(), ToLocalDateString(),


ToTimeString() methods to convert date into respective formats.

Example: Date Conversion in Different Formats


var date = new Date('2015-02-10T10:12:50.5000z');

date; 'Default format:'

date.toDateString();'Tue Feb 10 2015'

date.toLocaleDateString();'2/10/2015'

date.toGMTString(); 'GMT format'

date.toISOString(); '2015-02-10T10:12:50.500Z'

date.toLocaleString();'Local date Format '

date.toLocaleTimeString(); 'Locale time format '

date.toString('YYYY-MM-dd'); 'Tue Feb 10 2015 15:42:50'

date.toTimeString(); '15:42:50'

date.toUTCString(); 'UTC format '


To get date string in formats other than the ones listed above, you need to
manually form the date string using different Date methods. The following example
converts date string to DD-MM
MM-YYYY format.

Example: Get Date Segments


var date = new Date('4-1-2015'
2015'); // M-D-YYYY

var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();

var dateString = (d <= 9 ? '0' + d : d) + '-' + (m <= 9 ? '0' + m : m) + '-' + y;

Note:
Use third party JavaScript Date library like datejs.com or momentjs.com,
momentjs.com if you want to
work with Dates extensively.

Parse Date
Use Date.parse() method to convert valid date string into milliseconds since
midnight of 1/1/1970.

Example: Date.parse()
Date.parse("5/2/2015"); // 1430505000000

var date = new Date(Date.parse(


Date(Date.parse("5/2/2015")); // Sat May 02 2015 00:00:00

Compare Dates
Use comparison operators to compare two date objects.

Example: Date Comparison


var date1 = new Date('4-1-2015'
2015');
var date2 = new Date('4-2-2015'
2015');

if (date1 > date2)


alert(date1 + ' is greater than ' + date2);
else (date1 < date2 )
alert(date1 + ' is less than ' + date2);

Points to Remember :

1. Get current date using Date() or new Date().


2. Date object can be created using new keyword. e.g. var date = new Date();
3. Date can be created by specifying milliseconds, date string or year and month in
Date constructor.
4. Date can be created by specifying date string in different formats using different
separators.
5. Date methods are used to perform different tasks on date objects

JavaScript Function
JavaScript provides functions similar to most of the scripting and programming languages.

In JavaScript, a function allows you to define a block of code, give it a name and then execute it as
many times as you want.

A JavaScript function can be defined using function keyword.

Syntax:
//defining a function
function <function-name>()
{
// code to be executed
};

//calling a function
<function-name>();

The following example shows how to define and call a function in JavaScript.

Example: Define and Call a Function


function ShowMessage() {
alert("Hello World!");
}

ShowMessage();

In the above example, we have defined a function named ShowMessage that displays a popup
message "Hello World!". This function can be execute using () operator e.g. ShowMessage().

Function Parameters
A function can have one or more parameters, which will be supplied by the calling code and can be
used inside a function. JavaScript is a dynamic type scripting language, so a function parameter
can have value of any data type.

Example: Function Parameters


function ShowMessage(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}

ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);

You can pass less or more arguments while calling a function. If you pass less arguments then rest
of the parameters will be undefined. If you pass more arguments then additional arguments will be
ignored.

Example: Function Parameters


function ShowMessage(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}

ShowMessage("Steve", "Jobs", "Mr."); // display Hello Steve Jobs


ShowMessage("Bill"); // display Hello Bill undefined
ShowMessage(); // display Hello undefined undefined

The Arguments Object


All the functions in JavaScript can use arguments object by default. An arguments object includes
value of each parameter.

The arguments object is an array like object. You can access its values using index similar to array.
However, it does not support array methods.

Example: Arguments Object


function ShowMessage(firstName, lastName) {
alert("Hello " + arguments[0] + " " + arguments[1]);
}

ShowMessage("Steve", "Jobs");

ShowMessage("Bill", "Gates");
ShowMessage(100, 200);

An arguments object is still valid even if function does not include any parameters.

Example: Arguments Object


function ShowMessage() {
alert("Hello " + arguments[0] + " " + arguments[1]);
}
ShowMessage("Steve", "Jobs"); // display Hello Steve Jobs

An arguments object can be iterated using for loop.

Example: Iterate all Arguments


function ShowMessage() {

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


alert(arguments[i]);
}
}

ShowMessage("Steve", "Jobs");

Return Value
A function can return zero or one value using return keyword.

Example: Return value From a Function


function Sum(val1, val2) {
return val1 + val2;
};

var result = Sum(10,20); // returns 30

function Multiply(val1, val2) {


console.log( val1 * val2);
};

result = Multiply(10,20); // undefined

In the above example, a function named Sum adds val1 & val2 and return it. So the calling code
can get the return value and assign it to a variable. The second function Multiply does not return
any value, so result variable will be undefined.

A function can return another function in JavaScript.

Example: Function Returning a Function


function multiple(x) {

function fn(y)
{
return x * y;
}

return fn;
}
var triple = multiple(3);
triple(2); // returns 6
triple(3); // returns 9

Function Expression
JavaScript allows us to assign a function to a variable and then use that variable as a function. It is
called function expression.

Example: Function Expression


var add = function sum(val1, val2) {
return val1 + val2;
};

var result1 = add(10,20);


var result2 = sum(10,20); // not valid

Anonymous Function

Anonymous function is useful in pass


passing
ing callback function, creating closure or Immediately invoked function
expression.

JavaScript allows us to define a function without any name. This unnamed function is called
anonymous function. Anonymous function must be assigned to a variable.

Example: Anonymous Function


var showMessage = function (){
alert("Hello World!");
};

showMessage();

var sayHello = function (firstName) {


alert("Hello " + firstName);
};

showMessage();

sayHello("Bill");

Nested Functions
In JavaScript, a function can have one or more inner functions. These nested functions are in the
scope of outer function. Inner function can access variables and parame
parameters
ters of outer function.
However, outer function cannot access variables defined inside inner functions.
Example: Nested Functions
function ShowMessage(firstName)
{
function SayHello() {
alert("Hello " + firstName);
}

return SayHello();
}

ShowMessage("Steve");

Points to Remember :

1. JavaScript a function allows you to define a block of code, give it a name and then execute
exe it
as many times as you want.
2. A function can be defined using function keyword and can be executed using () operator.
3. A function can include one or more parameters. It is optional to specify function parameter
values while executing it.
4. JavaScript is a loosely-typed
typed language. A function parameter can hold value of any data type.
5. You can specify less or more arguments while calling function.
6. All the functions can access arguments object by default instead of parameter names.
7. A function can return a literal
ral value or another function.
8. A function can be assigned to a variable with different name.
9. JavaScript allows you to create anonymous functions that must be assigned to a variable.

You might also like