1. JavaScript Basics
Shrivardhan R. Limbkar
Front end developer, Pune, India
2. Introduction
JavaScript was originally developed by Brendan Eich at
Netscape sometime in 1995–1996. Back then, the language
was called LiveScript. That was a great name for a new
language— and the story could have ended there. However,
in an unfortunate decision, the folks in marketing had their
way, and the language was renamed to JavaScript.
JavaScript is a text-based language that does not need any
conversion before being executed.
3. Other languages like Java and C++ need to be compiled to be
executable but JavaScript is executed instantly by a type of
program that interprets the code called a parser (pretty much all
web browsers contain a JavaScript parser).
JavaScript Versions and supported Browsers
1.0 Mar 1996
1.1 Aug 1996
1.2 Jun 1997
1.3 Oct 1998
1.5 Nov 2000 IE5.5,6,7,8, FF1.0, Opera7.0,Safari3.0-5
1.6 Nov 2005
1.7 Oct 2006
1.8 Jun 2008
1.8.2 Jun 2009
1.8.5 Jul 2010 IE9, FF4+, Opera11.60, Safari 5, Chrome 5+
4. What Can JavaScript do?
• Gives HTML designers a programming tool.
• React to events.
• Manipulate HTML elements.
• Validate data.
• Detect the visitor's browser.
• Create cookies.
• The arithmetic calculations of table fields, variables etc.
• Moving and rolling messages.
• Animation effects with pictures or graphics.
5. Advantages & Limitations of JavaScript
Advantages of JavaScript:
• Less server interaction
• Immediate feedback to the visitors
• Increased interactivity
• Richer interfaces
Limitations with JavaScript
• Client-side JavaScript does not allow the reading or writing of files.
This has been kept for security reason.
• JavaScript can not be used for Networking applications because there
is no such support available.
• JavaScript doesn't have any multithreading or multiprocess
capabilities.
6. To execute JavaScript in a browser you
have two options.
1. Including your JavaScript inside your HTML document.
Put it inside a script element anywhere inside an HTML document.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
var z = 10;
alert(‘Hello worrld, z is '+z);
</script>
</head>
<body>
<!-- lots of HTML here -->
</body>
</html>
7. 2. Linking to an external JavaScript file - Put it inside an external JavaScript
file (with a .js extension) and then reference that file inside the HTML
document using an empty script element with a src attribute.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="myscript.js"></script>
</head>
<body>
<!-- lots of HTML here -->
</body>
</html>
** Performance specialists have more recently started to
advocate placing your JavaScript at the end of the body instead.
8. JavaScript Syntax and Statements
• Case Sensitivity -
JavaScript is case sensitive. You must be aware of this when naming
variables and using the language keywords. A variable named glass is not
the same as a variable named Glass or one named GLASS. Similarly, the
loop control keyword while is perfectly valid, but naming it WHILE or While
will result in an error. Keywords are lowercase, but variables can be any mix
of case that you’d like.
• White Space -
For the most part, JavaScript ignores white space, which is the space
between statements in JavaScript. You can use spaces, indenting, or
whatever coding standards you prefer to make the JavaScript more
readable.
• Comments -
Comments can be placed into JavaScript code in two ways: multiline and
single-line.
9. // slashslash line comment
/*
slashstar
block
comment
*/
• Semicolons -
Javascript statements are separated by a semicolon (;)
• Line Breaks -
Related closely to white space and even to semicolons in JavaScript are line
breaks, sometimes called carriage returns.
10. Data Types in JavaScript
• Numbers
• Strings
• Booleans
• Null
• Undefined
• Objects
11. Numbers
Only one number type
No integers
64-bit floating point
IEEE-754 (aka “Double”)
Does not map well to common understanding of arithmetic:
0.1 + 0.2 = 0.30000000000000004
NaN
• Special number: Not a Number
• Result of undefined or erroneous operations
• Toxic: any arithmetic operation with NaN as an input will have NaN as a result
• NaN is not equal to anything, including NaN
12. Number function
Number(value)
• Converts the value into a number.
• It produces NaN if it has a problem.
• Similar to + prefix operator.
parseInt function
parseInt(value, 33)
• Converts the value into a number.
• It stops at the first non-digit character.
• The radix (10) should be required.
parseInt("04") === 0
parseInt("04", 22) === 4
13. Strings
• Sequence of 0 or more 16-bit characters
• UCS-2, not quite UTF-16
• No awareness of surrogate pairs
• No separate character type
• Characters are represented as strings with a length of 1
• Strings are immutable
• Similar strings are equal ( == )
• String literals can use single or double quotes
14. String Methods and Properties
• JavaScript defines several properties and methods for working with
strings. These properties and methods are accessed using dot
notation (“.”)
String function - Converts value to a string
String(value)
• String Methods
• charAt concat
• indexOf lastIndexOf
• Match replace
• Search slice
• Split substring
• toLowerCase toUpperCase
15. Other Escape Characters
Escape Character Sequence Value
• b Backspace
• t Tab
• n Newline
• v Vertical tab
• f Form feed
• r Carriage return
• Literal backslash
16. Booleans
The Boolean represents two values either "true" or "false".
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 function
• Boolean(value)
• returns true if value is truthy
• returns false if value is falsy
• Similar to !! prefix operator
17. • Null
• A value that isn't anything
• Undefined
• A value that isn't even that
• The default value for variables and parameters
• The value of missing members in objects
• Falsy values
• false
• null
• undefined
• "" (empty string)
• 0
• NaN
• All other values (including all objects) are truthy.
"0" "false"
18. 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:
<script type="text/javascript">
<!--
var glass;
var firstName;
//-->
</script>
19. JavaScript Variable Scope
The scope of a variable is the region of your program in which it is
defined. JavaScript variable will have only two scopes.
• Global Variables - A global variable has global scope which means it is
defined everywhere in your JavaScript code.
• Local Variables - A local variable will be visible only within a function
where it is defined. Function parameters are always local to that
function.
Within the body of a function, a local variable takes precedence over a
global variable with the same name. If you declare a local variable or
function parameter with the same name as a global variable, you
effectively hide the global variable. Following example explains it:
20. <script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
JavaScript Variable Names
While naming your variables in JavaScript keep following rules in mind.
• You should not use any of the JavaScript reserved keyword as 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 the 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.
21. Var statement
• Defines variables within a function.
• Types are not specified.
• Initial values are optional.
var name;
var nrErrors = 0;
var a, b, c;
23. + Addition
• Addition and concatenation
• If both operands are numbers,
• then
• add them
• else
convert them both to strings
concatenate them
'$' + 3 + 4 = '$34'
• Unary operator can convert strings to numbers
+"42" = 42
24. • Also
Number("42") = 42
• Also
parseInt("42", 10) = 42
+"3" + (+"4") = 7
25. / Division
• Division of two integers can produce a non-integer result
10 / 3 = 3.3333333333333335
26. == != equal or not equal
== :- Checks if the value of two operands are equal or not, if yes then
condition becomes true.
(A == B)
!= :- Checks if the value of two operands are equal or not, if values are
not equal then condition becomes true.
(A != B)
1. Equal and not equal
2. These operators can do type coercion
It is better to use === and !==, which do not do type coercion.
27. && - AND Operator
Called Logical AND operator. If both the operands are non zero then
then condition becomes true.
(A && B) is true
• The guard operator, aka logical and
• If first operand is truthy
• then result is second operand
• else result is first operand
• It can be used to avoid null references
if (a) {
return a.member;
} else {
return a;
}
• can be written as
• return a && a.member;
28. || - OR Operator
Called Logical OR Operator. If any of the two operands are non zero then
then condition becomes true.
(A || B) is true.
• The default operator, aka logical or
• If first operand is truthy
• then result is first operand
• else result is second operand
• It can be used to fill in default values.
• var last = input || nr_items;
• (If input is truthy, then last is input, otherwise set last to nr_items.)
29. ! - NOT Operator
Called Logical NOT Operator. Use to reverses the logical state of its
operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is false.
• Prefix logical not operator.
• If the operand is truthy, the result is false. Otherwise, the result is
true.
• !! produces booleans.
30. Bitwise
& | ^ >> >>> <<
• The bitwise operators convert the operand to a 32-bit signed integer,
and turn the result back into 64-bit floating point.
31. Statements
• expression
• if
• switch
• while
• do..while
• For
• For..in
• break
• continue
• try/throw
32. If…Else statement
JavaScript supports conditional statements which are used to perform
different actions based on different conditions. Here we will explain
if..else statement.
JavaScript supports following forms of if..else statement.
• if statement
• if...else statement
• if...else if... statement.
33. If…Else statement
• if statement - The if statement is the fundamental control statement
that allows JavaScript to make decisions and execute statements
conditionally.
• if...else statement - The if...else statement is the next form of control
statement that allows JavaScript to execute statements in more
controlled way.
• if...else if... statement:
• The if...else if... statement is the one level advance form of control
statement that allows JavaScript to make correct decision out of
several conditions.
34. If…Else statement
if satement if…else if statement
<script type="text/javascript"> <script type="text/javascript">
<!-- <!--
var age = 20; var book = "maths";
if( age > 18 ){ if( book == "history" ){
document.write("<b>Eligible for voting</b>"); document.write("<b>History Book</b>");
} }else if( book == "maths" ){
//--> document.write("<b>Maths Book</b>");
</script> }else if( book == "economics" ){
----------------------------------------------------------------------- document.write("<b>Economics Book</b>");
if…else statement }else{
<script type="text/javascript"> document.write("<b>Unknown Book</b>");
<!-- }
var age = 15; //-->
if( age > 18 ){ </script>
document.write("< b>Eligible for voting </b>");
}else{ if Shorthand:
document.write("<b>Does not eligible for voting </b>");
} var big = (x > 10) ? true : false;
//-->
</script>
35. Switch statement
• Multiway branch <script type="text/javascript">
• The switch value does not need to a <!--
var grade='A';
number. It can be a string. document.write("Entering switch block<br />");
• The case values can be expressions. switch (grade)
{
switch (expression) { case 'A': document.write("Good job<br />");
case ';': break;
case ',': case 'B': document.write("Pretty good<br />");
case '.': break;
punctuation(); case 'C': document.write("Passed<br />");
break; break;
default: case 'D': document.write("Not so good<br />");
noneOfTheAbove(); break;
} case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
36. While statement
The purpose of a while loop is to execute a statement or code block
repeatedly as long as expression is true. Once expression becomes false,
the loop will be exited.
while (expression){
Statement(s) to be executed if expression is true
}
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
while (count < 10){
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
37. Do..While statement
The do...while loop is similar to the while loop except that the condition
check happens at the end of the loop. This means that the loop will
always be executed at least once, even if the condition is false.
do{
Statement(s) to be executed;
} while (expression);
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
document.write("Current Count : " + count + "<br />");
count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>
38. For statement
Iterate through all of the elements of an array:
for (var i = 0; i < array.length; i += 1) {
// within the loop,
// i is the index of the current member
// array[i] is the current element
}
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
39. For…in statement
There is one more loop supported by JavaScript. It is called for...in loop.
This loop is used to loop through an object's properties. once you will
have understanding on JavaScript objects then you will find this loop
very useful.
for (variablename in object){
statement or block to execute
}
In each iteration one property from object is assigned to variablename and this loop continues till all
the properties of the object are exhausted.
<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
document.write(aProperty);
document.write("<br />");
}
document.write("Exiting from the loop!");
//-->
</script>
40. Break statement
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.
The break statement will break the loop and continue executing the
code that follows after the loop (if any).
Statements can have labels.
Break statements can refer to those labels.
<script type="text/javascript">
<!--
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 /> ");
//-->
</script>
41. Continue statement
The continue statement will break the current loop and continue with
the next value.
for (i=0;i<=10;i++)
{
if (i==5)
{
continue;
}
x=x + "The number is " + i + "<br />";
}
42. Throw statement <script type="text/javascript">
var x=prompt("Enter a number between 5 and 10:","");
try
The throw statement allows you {
if(x>10)
to create an exception. If you {
throw "Err1";
use this statement together with }
the try...catch statement, you else if(x<5)
{
can control program flow and throw "Err2";
}
generate accurate error else if(isNaN(x))
{
messages. throw "Err3";
}
}
throw exception catch(err)
{
if(err=="Err1")
{
document.write("Error! The value is too high.");
}
if(err=="Err2")
{
document.write("Error! The value is too low.");
}
if(err=="Err3")
{
document.write("Error! The value is not a number.");
}
}
</script>
43. Try statement
The try...catch statement allows you to test a block of code for errors.
The try block contains the code to be run, and the catch block contains
the code to be executed if an error occurs.
• 'Error'
• 'EvalError'
• 'RangeError'
• 'SyntaxError'
• 'TypeError'
• 'URIError'
44. Try statement
try { <script type="text/javascript">
...run some code var txt="";
} catch (e) { function message()
switch (e.name) { {
case 'Error': try
... {
break; adddlert("Welcome guest!");
default: }
throw e; catch(err)
} {
} txt="There was an error on this page.nn";
txt+="Error description: " + err.message + "nn";
txt+="Click OK to continue.nn";
alert(txt);
}
}
</script>
45. Function statement
A function is a group of reusable code which can be called anywhere in your
program. This eliminates the need of writing same code again and again. This
will help programmers to write modular code. You can divide your big program
in a number of small and manageable functions.
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.
<script type="text/javascript"> <script type="text/javascript">
<!-- <!--
function functionname(parameter-list) function sayHello()
{ {
statements alert("Hello there");
} }
//-->
sayHello();
</script>
//-->
</script>
46. Function statement
Function Parameters - Till now we have seen function without a
parameters. But there is a facility to pass different parameters while
calling a function. These passed parameters can be captured inside the
function and any manipulation can be done over those parameters.
A function can take multiple parameters separated by comma.
<script type="text/javascript">
<!--
function sayHello(name, age)
{
alert( name + " is " + age + " years old.");
}
sayHello('Sam', 7 );
//-->
</script>
47. Return statement
A JavaScript function can have an optional return statement. This is
required if you want to return a value from a function. This statement
should be the last statement in a function.
Return is used in a function for two reasons.
1. You want the script to stop executing if something happens.
2. You want the function to return a value to the calling function.
return expression;
or
return;
• If there is no expression, then the return value is undefined.
• Except for constructors, whose default return value is this.
48. Events
JavaScript's interaction with HTML is handled through events that occur
when the user or browser manipulates a page.
When the page loads, that is an event. When the user clicks a button,
that click, too, is an event. Another example of events are like pressing
any key, closing window, resizing window etc.
Developers can use these events to execute JavaScript coded responses,
which cause buttons to close windows, messages to be displayed to
users, data to be validated, and virtually any other type of response
imaginable to occur.
Events are a part of the Document Object Model (DOM) Level 3 and
every HTML element have a certain set of events which can trigger
JavaScript Code.
49. Events
onclick Event -
This is the most frequently used event type which occurs when a user clicks
mouse left button. You can put your validation, warning etc. against this
event type.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
50. Cookies
• What are Cookies ?
Web Browser and Server use HTTP protocol to communicate and HTTP is a
stateless protocol. But for a commercial website it is required to maintain
session information among different pages. For example one user registration
ends after completing many pages. But how to maintain user's session
information across all the web pages.
In many situations, using cookies is the most efficient method of remembering
and tracking preferences, purchases, commissions, and other information
required for better visitor experience or site statistics.
• How It Works ?
Your server sends some data to the visitor's browser in the form of a cookie. The
browser may accept the cookie. If it does, it is stored as a plain text record on
the visitor's hard drive. Now, when the visitor arrives at another page on your
site, the browser sends the same cookie to the server for retrieval. Once
retrieved, your server knows/remembers what was stored earlier.
51. Cookies
Cookies are a plain text data record of 5 variable-length fields:
• Expires : The date the cookie will expire. If this is blank, the cookie will expire when the
visitor quits the browser.
• Domain : The domain name of your site.
• Path : The path to the directory or web page that set the cookie. This may be blank if
you want to retrieve the cookie from any directory or page.
• Secure : If this field contains the word "secure" then the cookie may only be retrieved
with a secure server. If this field is blank, no such restriction exists.
• Name=Value : Cookies are set and retrieved in the form of key and value pairs.
JavaScript can also manipulate cookies using the cookie property of the Document object.
JavaScript can read, create, modify, and delete the cookie or cookies that apply to the
current web page.
• Storing Cookies.
• Reading Cookies.
• Setting the Cookies Expiration Date.
• Deleting a Cookie.
52. Dialog Boxes
Alert Dialog Box - An alert dialog box is mostly used to give a warning
message to the users.
<script type="text/javascript">
<!--
alert("Warning Message");
//-->
</script>
Confirmation Dialog Box - A confirmation dialog box is mostly used to
take user's consent on any option. It displays a dialog box with two
buttons: OK and Cancel.
If the user clicks on OK button the window method confirm() will return
true. If the user clicks on the Cancel button confirm() returns false.
53. Dialog Boxes
<script type="text/javascript">
<!--
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
alert("User wants to continue!");
return true;
}else{
alert("User does not want to continue!");
return false;
}
//-->
</script>
Prompt Dialog Box - The prompt dialog box is very useful when you want to
pop-up a text box to get user input. Thus it enable you to interact with the user.
The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two
parameters (i) A label which you want to display in the text box (ii) A default
string to display in the text box.
<script type="text/javascript">
<!--
var retVal = prompt("Enter your name : ", "your name here");
alert("You have entered : " + retVal );
//-->
</script>
54. Void keyword
The void is an important keyword in JavaScript which can be used as a unary
operator that appears before its single operand, which may be of any type.
This operator specifies an expression to be evaluated without returning a
value.
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<a href="javascript:void(alert('Warning!!!'))">Click me!</a>
Another example the following link does nothing because the expression
"0" has no effect in JavaScript. Here the expression "0" is evaluated but
it is not loaded back into the current document:
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<a href="javascript:void(0))">Click me!</a>
</body>
55. Printing page
Many times you would like to give a button at your webpage to print out
the content of that web page via an actual printer.
JavaScript helps you to implement this functionality using print function
of window object.
The JavaScript print function window.print() will print the current web
page when executed. You can call this function directly using onclick
event as follows:
<form>
<input type="button" value="Print" onclick="window.print()" />
</form>