Professional Documents
Culture Documents
Table of Contents
1 Prerequisite: ................................................................................................................................. 6
2 What is JavaScript? ...................................................................................................................... 6
3 Main uses of JavaScript? .............................................................................................................. 6
4 Where to code?............................................................................................................................ 6
4.1 JavaScript in head section ..................................................................................................... 7
4.2 JavaScript in body section ..................................................................................................... 7
4.3 External JavaScript ................................................................................................................ 7
5 Try out this ................................................................................................................................... 8
6 JavaScript Basics ........................................................................................................................... 8
6.1 Javascript statements ........................................................................................................... 8
6.2 Events .................................................................................................................................. 10
7 Comments .................................................................................................................................. 10
8 Variables and types .................................................................................................................... 11
8.1 Declarations ........................................................................................................................ 11
8.2 Declaring Variables ............................................................................................................. 11
8.3 Variable Scope .................................................................................................................... 11
8.4 Variable Hoisting ................................................................................................................. 12
8.5 Constants ............................................................................................................................ 13
8.6 Data types. .......................................................................................................................... 13
1 Prerequisite:
Before starting with JavaScript, you must have good knowledge of HyperText Markup
Language(HTML).
2 What is JavaScript?
JavaScript is an object-oriented scripting language. It is small and lightweight. JavaScript is a
cross-platform language. JavaScript contains a standard library of objects, such as Array, Date,
and Math, and a core set of language elements such as operators, control structures, and
statements.
4 Where to code?
The script tag is used for adding javascript to your HTML document.
JavaScript code can be placed in the head or body section or we can even create an external
javascript file with (.js) extension.
<head>
<script>
...JavaScript code...
<script>
</head>
greet("World");
</script>
</body>
</html>
6 JavaScript Basics
Most of javascript syntax are similar to java.
JavaScript is case-sensitive and uses the Unicode character set.
A javascript code consist of statements which end with semicolon(;).
In this example, the button have been assigned the function sayHello(). When the button is
clicked, the function sayHello() fetches the element with id = demo and copies the text Valar
Dohaeris inside that element(.innerHTML copies the text inside that <p> tag). This is a basic
application of JavaScript. I have explained every part of it in the later part of this module so
dont worry, youll get the hang of it !
6.2 Events
There are a list of events which you can use in JavaScript.
Event
Description
onclick
onchange
onmouseover
onmouseout
onkeydown
onload
7 Comments
Comments in javascript are same as that of java.
// One line comment
/*
Multi-line comment
*/
if (true) {
var x = 5;
}
alert('x= ' + x);
if (true) {
let y = 5;
}
alert('y= ' + y);
8.5 Constants
These are read only variables.
Value of a constant cannot be changed using assignment. It cannot be re-declared.
It has to be initialized to a value
Constant with the same name of a function or variable cannot be declared in the same
scope.
Syntax: const pi = 3.14;
9 Strings
A string is zero or more characters enclosed in double (") or single (') quotation marks.
var firstname = "Vijay";
var middlename = "Dinanath";
var lastname = "Chauhan";
Special characters:
\n
New line
\t
Tab
\b
Backspace
Single quote
Double quote
\\
Backslash
10 Array
An array is a list of zero or more expressions, each of which represents an array element,
enclosed in square brackets [].
var chocolates = ["Toffee", "Candy", "Lollipop"];
This array has three elements, chocolate[0] is Toffee, chocolate[1] is Candy and
chocolate[2] is Lollipop.
11 Object
An object is a list of zero or more pairs of property names and associated values of an object,
enclosed in curly braces {}.
A mobile is an object with properties such as name, model, color. This example given below
shows one such object with these properties.
The properties can also contain functions. These are called object methods.
Here the name property has value google, model property has value nexus-5x, color
property has value white and getinfo property contains the function which gives an alert
when it is called.
var mobile = { name: "google ",
model: "nexus-5x ",
color: "white ",
getinfo: function() {
alert(mobile.name + mobile.model +
mobile.color)}
};
mobile.getinfo();
while (i < 5) {
i++;
}
Example:
var result;
var marks = 80;
if ( marks > 90 ) {
result = "Excellent";
} else if ( marks > 70 ) {
result = "Very Good";
} else if ( marks > 50 ) {
result = "Good";
} else {
result = "Need practice";
}
alert("Result= " + result);
statements_def
break;
The optional break statement associated with each case clause ensures that the
program breaks out of switch once the matched statement is executed and continues
execution of the statements following the switch.
If the break statement is omitted, the program continues to execute all the statements
in the case clause following the matching case clause.
Example
var fruit = "Bananas";
switch (fruit) {
case "Oranges":
alert("Oranges are Orange.");
break;
case "Apples":
alert("Apples are Red.");
break;
case "Bananas":
alert("Bananas are Yellow.");
break;
case "Guavas":
alert("Guavas are Green.");
break;
case "Blueberries":
alert("Blueberries are Blue.");
break;
default:
alert("Sorry, "+fruit+" was new for us!");
}
try...catch statements
The try...catch statement groups a block of statements to try, and specifies one or more
responses exception that may get thrown.
If an exception is thrown, the try...catch statement catches it.
You will understand exception handling more properly from the following example.
var subjects = ["Physics", "Chemistry",
"Maths"];
var x = 0;
if ( subjects[x] ) {
alert("Subject "+x+" is
"+subject[x]);
}
var subjects = ["Physics", "Chemistry",
"Maths"];
var x = 0;
try{
if ( subjects[x] ) {
alert("Subject "+x+" is
"+subject[x]);
}
}
catch(e) {
alert("Subject code was incorrect.");
}
Example
var i;
var x = 0;
for (i = 0; i < 5; i++) {
x = x + 5;
}
alert(x);
Example
var i = 0;
var hi = "Hi";
var ok = "Ok";
while(i<5) {
ok = ok.concat(" ", hi);
i++;
}
alert(ok);
Example
var i = 0;
var hi = "Hi";
var ok = "Ok";
do {
ok = ok.concat(" ", hi);
i++;
} while(i<5);
alert(ok);
Example
14 Functions
Functions are one of the fundamental building blocks in JavaScript. A function is a set of
statements that performs a task.
15 Operators
JavaScript consist of the following operators
Assignment operators
Comparison operators
Arithmetic operators
Bitwise operators
Logical operators
String operators
Conditional operator
Unary operator
Relational operator
Shorthand operator
Meaning
Assignment
x = y
x = y
Addition assignment
x += y
x = x + y
Subtraction assignment
x -= y
x = x - y
Multiplication assignment
x *= y
x = x * y
Division assignment
x /= y
x = x / y
Remainder assignment
x %= y
x = x % y
x &= y
x = x & y
Bitwise OR assignment
x |= y
x = x | y
considering their type, the === and !== operators are used. These operators do not
attempt to convert the operands into compatible types before comparing.
Comparison operands are given below
Operator
Description
==
Equal value
!=
===
!==
>
Greater than
>=
<
Less than
<=
Description
Addition
Subtraction
Multiplication
Division
Modulus (Remainder)
++
Increment
--
Decrement
Description
Example
Evaluation
&
AND
3 & 5
OR
3 | 5
XOR
3 ^ 5
NOR
~3
~0011
= 1100 (12)
Description
Example
&&
Logical AND
a == 5 && b == 7
||
Logical OR
a == 5 || b == 7
Logical NOT
!( a == 5 )
If the condition is true the first value is assigned and if the condition is false the second value is
assigned.
Example
var class = ( age >= 18 ) ? "You can drive" : "No driving license!" ;
Returns "number"
typeof x;
var y = "Hello";
Returns "string"
typeof y;
Example
var tdate = new Date(1995, 12, 17);
of date object.
// statements to execute
}
16 Numbers
There is only one type for numbers in javascript. They can be written with or without decimal.
Here x = 31500000
var x = 315e-5
Here x = 0.00315
Here bin1 = 3
Here bin2 = 19
Here hex1 = 10
Here bin2 = 63
16.1.4 NaN
NaN stands for Not a Number.
NaN is a JavaScript reserved word indicating that a value is not a number.
Trying to do arithmetic with a non-numeric string will result in NaN.
However if the string contains numeric value, the result will be numeric.
var x = 5 / "Hi";
Here x = NaN
var x = 20 / "5";
Here x = 4
Description
Number.MAX_VALUE
Number.MIN_VALUE
Number.NaN
Number.NEGATIVE_INFINITY
Number.POSITIVE_INFINITY
Example
var x = Number.MAX_VALUE;
alert(x);
Description
Number.parseInt()
Number.parseFloat()
x = Number.parseInt(x);
alert(x);
// 6
Number.isInteger()
Example
x = Number.parseFloat(x);
alert(x);
// 6.5
var x = 6;
x = Number.isInteger(x);
alert(x);
// true
Number.isNaN()
var x = parseInt("hi");
x = Number.isNaN(x);
alert(x);
// true
toString()
var x = 6;
x = x.toString();
alert(x);
// 6
toExponential()
var x = 6;
x = x.toExponential();
// 6e+0
notation.
toFixed()
var x = 6.555555;
x = x.toFixed(4);
alert(x);
notation.
toPrecision()
alert(x);
// 6.5556
var x = 6.555555;
x = x.toPrecision(4);
alert(x);
// 6.556
Description
abs(x)
floor(x)
ceil(x)
pow(x,y)
log(x), log10(x)
Logarithmic functions.
min(a,b,.,n), max(a,b,.,n)
round(x)
sqrt(x)
random()
17 Dates
There is no date data type in JavaScript but it consist of date object. You can use date object
and its methods to work with dates.
Description
setDate()
setFullYear()
setMonth()
setHours()
setMinutes(), setSeconds()
setTime()
Set time.
Description
getDate()
getFullYear()
getMonth()
getHours()
getMinutes(), setSeconds()
getTime()
Get time.
Examples
setDate()
getDate()
tdy.setDate(15);
alert(tdy.getDate());
setFullYear()
getFullYear()
tdy.setFullYear(1992);
alert(tdy.getFullYear());
setHours()
getHours()
tdy.setHours(13);
alert(tdy.getHours());
18 Regular expressions
A regular expression is a sequence of characters that forms a pattern.
These patterns are used with methods of RegExp and String.
There are two ways of creating regular expression.
var re = /ax+by/;
var re = new RegExp("ax+by");
Regular expressions make search much more powerful. There are some more modifiers which
can be used.
18.2 Modifiers
Modifier
Description
18.3 Patterns
18.3.1 Brackets
Finds a range of characters
Expression
Description
[mno]
[a-e]
(1|3)
18.3.2 Quantifiers
Quantifiers
Description
a+
a*
a?
18.3.3 Metacharacters
Metacharacter
Description
\d
\s
\b
Thats it guys. If you have understood this module, you can easily code in JavaScript. Ill keep
updating the document to make it more better and easy to understand.