1-Overview of JS
1-Overview of JS
• Features of JavaScript
• Using JS in an HTML document
Attributes
JS in the HEAD element
JS in the BODY element
JS in the External file
• Exploring Programming Fundamental of
JS
Lexical Structure
Variables
Operators
Control flow statements
Popup boxes
Lexical Structure
Character set
Case sensitivity
White spaces and line breaks
Optional semicolons
Comments
Literals
Identifies
Reserved words
Variables
Exploring Operators
Arithmetic Operators
1
Assignment Operators
Comparison Operators
Logical Operators
Conditional Operator
Exploring Control Flow Statements
Selection statements
Loops
Jump statements
Exploring Popup Boxes
The alert box
The confirm box
The prompt box
2
JavaScript is a client and server side object-based scripting language
that is used to make interactive web pages. A scripting is a light-weight
programming language with the less complexity.
JavaScript is interpreted language, which implies that scripts written in
JavaScript are processed line by line these scripted are interpreted by
JavaScript interpreter which is a built-in component of web browser.
Exploring the features of java script
Imperative and structured-implies that JavaScript supports all the
syntaxes of the structured programming language c, such as if
statement, loops and the switch statement.
Dynamic text- implies that JavaScript supports dynamic typing. This
means that the type of variable is defined according to the value
stored in it.
Functional- implies that JavaScript does not support classes. Instead
of using classes, objects are create from the constructor functions.
Prototype based- implies that JavaScript is a prototype based
scripting language. This means it uses prototypes instead of classes for
inheritance.
Platform independent- implies that JavaScript supports platform
independency or probability. This means you can write the script once
and run it at anywhere at any time.
Using JavaScript in HTML Document
The script element either contains scripting statements or a reference to an
external script file. The script element contains five attributes: async, type,
charset, defer ans src.
Attributes of script element:
3
charset charset The character encoding
used in the script
defer true Specifies whether the
false browser can continue
passing the webpage or
not
src URL Specifies the uniform
resource locator of a
file that contains script
4
EX:
<head>
<script src=URL of external file>
</script>
</head>
Exploring Programming Fundamentals of JavaScript
JavaScript helps you to create webpages and embed JavaScript statements
directly in an html document. The programming fundamentals of JavaScript
include:
✓ Lexical structure
✓ Variables
✓ Operators
✓ Control flow statements
✓ Popup boxes
Symbols Names
\t Represents a tab
\f A formfeed also called white spaces
\b backspace
\n A new line
5
\r A carriage return character,used to
start a new line text
\” A double quote
\’ A single quote
\\ A backslash
6
Understanding comments
Comments refer to the text or code in a program that is ignored at the time
of executing the program. It also defines two different types of comments;
Single-line comment: starts with // and ends with end of line
Multiple-line comment: starts with /* and ends with */
Understanding Literals
It is a data value that represents a fixed value ina program.It supports
following type of literals:
✓ Numeric
✓ Floating-point
✓ Boolean
✓ String
✓ Array
✓ Regular expression
✓ Object
Numeric literal: 89, 569//decimal base 10
021, 065//octal base 8
Floating point: 4.89080
-123.56734
Boolean: var b=true;
var c=false;
if(b=true)
{
//some code
}
String: “anu”
“push”
“haal”
“1258”
Array: var emp=[“anu”,”push”,”haal”];
7
Regular expression: var myregexp=/abc/;
Object literal: var games={cricket: 11, chess:2, carom:4};
Understanding Identifiers
ECMAScript defines some rules and guidelines for identifiers, which are as
follows:
✓ They must start with a letter, dollar sign($),or underscore(_)
✓ Cannot start with a number
✓ Contains only combination of letters, dollar sign, underscore, numbers
after first character
✓ Can be of any length
✓ They are case sensitive
✓ Cannot contain reserved words or keywords.
EX: sum
_abc
One_two
Understanding reserved words
Understanding variables
In Javascript, data can be temporarily stored in variables, which are the
named locations in the memory.
Syntax: var variable_name;
var var1,var2,var3; //can also declare multiple variables
8
Understanding Operators
9
10
Exploring control flow statements: These are divided into following
categories:
● Selection statements
● Loops
● Jump statements
Understanding selection statements-These statements use a condition
to select or determine the statements that are to be executed. These
statements help you to make decisions and change the flow of execution of
the statements. There are three selection statements:
● If
● If…else
● switch
if statement:
This is one of the most basic and simple one used when you want to execute
a group of one or more script statements only when a particular condition is
met.
Syntax: if(condition)
{
Statement
}
If…else statement:
The statement allows you to execute a set of statements only when a
particular condition is true.
Syntax: if(condition)
{
Statement1
}
else
{
Statement2
}
11
switch statement:
It is used to select a particular group of statements to be executed among
several other groups of statements.
Syntax: switch(expr)
{
case val1:statement1
break;
case val2:statement2
break;
default:statement_default
break;
}
Understanding Loops-Loops and iteration statements allows you to
execute a particular group of statements repeatedly. The no of times a
group of statements is executed depends on a particular condition that is a
Boolean expression. If Boolean expr is true, statements are executed until
the condition becomes false. there are three loops namely
● while loop
● do…while loop
● for loop
while loop:
You can use this loop when you want to check the condition at the start of
the loop
Syntax: while(condition)
{
Statement
}
do…while loop:
If the condition becomes false in the very first iteration, statements specified
in while loop is never executed.
Syntax: do { Statement } while(condition);
12
for loop:
Allows you to execute a group of statements for a predetermined no of
times. The condition for the loop is placed at the beginning of the loop.
Syntax: for(initialization_statement;condition;updation_statement)
{
Statement
}
Understanding Jump statement:
These statements allow you to jump over or skip certain statements in a
script and execute some other statement. The two jump statements are:
● break
● continue
break statement: allows you to break statement to prevent the execution
of the subsequent case statements. This also you to break or exit a loop.
continue statement: Similar to break, the continue statement is used to
stop the execution of a loop. However, continue doesnot exit the loop.
Exploring pop up boxes:
A pop-up is a window that displays a message along with an ok button. It
may also contain a cancel button. In addition, it can prompt users to enter
some text. Javascript supports three types of pop-up boxes:
● Alert box
● Confirm boc
● Prompt box
Alert box:It is generally used to display an alert message while executing
the JavaScript code. In addition, it is used to display error messages after
you validate a form. It contains ok button, where the user has to click
continue with execution of the code.
Confirm box: It is an advanced form of alert box, used to display a
message as well as return a true or false value and a dialogue box with two
buttons, ok and cancel. When you click ok, confirm box returns true value
and when you click cancel button, confirm box returns false value.
Prompt box:It is used to input a value from a user. It contains a text box
and ok and cancel buttons. The user has to click either ok or cancel button
to continue the execution of the code after entering an input value.
13
Incorporating JavaScript in the Head Element:
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>Adding script in head element</TITLE>
<H1>adding script</H1>
<SCRIPT type=”text/javascript”>
document.write(“welcome to java script<BR/>”);
document.write(“we used java script”);
</SCRIPT>
</HEAD>
</HTML>
14
document.write(“welcome to java script<br/>”);
document.write(“we used java script”);
</script>
</body>
</html>
15
}
document.write(count);
16
For multiple variables:
<!DOCTYPE HTML>
<html>
<head>
<title>Assigning values to multiple variables</title>
</head>
<body>
<h1>Using multiple variable</h1>
<script type=”text/javascript”>
Var countBooks=50, minBookPrice=150, maxBookPrice=3000, bookName;
countBooks=2000;
minBookPrice=500;
maxBookPrice= minBookPrice;
document.write(“countBooks=”+countBooks+”<br/>”);
document.write(“maxBookPrice=”+ maxBookPrice +”<br/>”);
document.write(“bookName =”+ bookName);
</script>
</body>
</html>
17
Using Operators:
<!DOCTYPE HTML>
<html>
<head>
<title>Using operators</title>
</head>
<body>
<h1>Using operators</h1>
<script type=”text/javascript”>
Var math=95,English=80,science=90,avg/marks;
avgMarks=math+English+science/3;
document.write(“average marks=”+avgMarks);
avgMarks=math+English+science/3;
document.write(“average marks=”+avgMarks);
</script>
</body>
</html>
18
Using if statement:
<!DOCTYPE HTML>
<html>
<head>
<title>Using if statement</title>
</head>
<body>
<h1>Using if statement</h1>
<script type=”text/javascript”>
Var no=45;
If((no%2)!=0)
{
document.write(no+”is an odd number”);
}
document.write(“<br/>Thank you”);
</script>
</body>
</html>
19
Using the if…else statement:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
var greeting;
var time = new Date().getHours();
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
}
</script>
</body>
</html>
20
Fig 9:Displaying output for NestedifelseStatement.html
Using switch statement:
<!DOCTYPE html>
<html>
<body>
<p>Write Banana, Orange or Apple in the input field and click the
button.</p>
<p>The switch statement will execute a block of code based on your
input.</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text;
var fruits = document.getElementById("myInput").value;
switch(fruits) {
case "Banana":
text = "Banana is good!";
break;
case "Orange":
text = "I am not a fan of orange.";
break;
21
case "Apple":
text = "How you like them apples?";
break;
default:
text = "I have never heard of that fruit...";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
22
function myFunction() {
var text = "";
var i = 0;
while (i < 5) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
23
<p id="demo"></p>
<script>
var text = ""
var i = 0;
do {
text += "<br>The number is " + i;
i++;
}while (i < 10);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
24
<h2>JavaScript Loops</h2>
<p id="demo"></p>
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
25
<p>A loop with a break.</p>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
26
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
27
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
28
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
<script>
function myFunction() {
var txt;
var person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you today?"; }
29
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
30