Java Script: Variables &scope, Data Types, Control Structures, Array Methods
Java Script: Variables &scope, Data Types, Control Structures, Array Methods
GMRIT/ADM/F-44
Rajam, Andhra Pradesh
REV.: 00
(An Autonomous Institution Affiliated to JNTUGV, AP)
❖ Objective
❖ Apply dynamic effects and validations using JavaScript skills to real-world projects
❖ Demonstrating the ability to build interactive and dynamic web applications
❖ Evocation
❖ Deliverables
Lecture -1:
➢ JAVASCRIPT
❖ JavaScript is the scripting language of the Web.
❖ JavaScript is used in millions of Web pages to add functionality, validate forms,
detect browsers, and much more.
➢ Introduction to JavaScript
❖ JavaScript is used in millions of Web pages to improve the design, validate forms,
detect browsers, create cookies, and much more.
❖ JavaScript is the most popular scripting language on the Internet, and works in all
major browsers, such as Internet Explorer, Mozilla Firefox, and Opera.
➢ What is JavaScript?
❖ JavaScript was designed to add interactivity to HTML pages
❖ JavaScript is a scripting language
❖ A scripting language is a lightweight programming language
❖ JavaScript is usually embedded directly into HTML pages
❖ JavaScript is an interpreted language (means that scripts execute without
preliminary compilation)
❖ Everyone can use JavaScript without purchasing a license
Java and JavaScript are two completely different languages in both concept and
design!
Java (developed by Sun Microsystems) is a powerful and much more complex
programming language - in the same category as C and C++.
function myFunction() {
let x = 1216;
// code here CAN use x
}
// code here can NOT use x
o Local variables have Function Scope:
o They can only be accessed from within the function.
iii.Global Scope
o A variable declared outside a function, becomes GLOBAL.
o Example
let x = 1216;
// code here can use x
function myFunction() {
// code here can also use x
}
o Global variables can be accessed from anywhere in a JavaScript program.
o Variables declared with var, let and const are quite similar when declared
outside a block.
➢ DataTypes
❖ Numbers - are values that can be processed and calculated. You don't enclose them
in quotation marks. The numbers can be either positive or negative.
❖ Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript
uses the string literally; it doesn't process it. You'll use strings for text you want
displayed or values you want passed along.
❖ Boolean (true/false) - lets you evaluate whether a condition meets or does not
meet specified criteria.
❖ Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number,
whereas null is the absence of any value.l
v. Conditional Operator
o JavaScript also contains a conditional operator that assigns a value to a
variable based on some condition.
o Syntax
variablename=(condition)?value1:value2
o Example:
greeting=(visitor=="PRES")?"Dear President ":"Dear ";
- If the variable visitor has the value of "PRES", then the variable greeting
will be assigned the value "Dear President " else it will be assigned
"Dear".
vi. Bitwise Operators
o Bit operators work on 32 bits numbers.
o Any numeric operand in the operation is converted into a 32 bit number.
The result is converted back to a JavaScript number.
Operator Description Example Same as Result Decimal
& AND 5&1 0101 & 0001 0001 1
| OR 5|1 0101 | 0001 0101 5
~ NOT ~5 ~0101 1010 10
➢ Conditional Statements
❖ Very often when you write code, you want to perform different actions for
different decisions. You can use conditional statements in your code to do this.
❖ In JavaScript we have the following conditional statements:
o if statement - use this statement if you want to execute some code only if a
specified condition is true
o if...else statement - use this statement if you want to execute some code if the
condition is true and another code if the condition is false
o if...else if....else statement - use this statement if you want to select one of many
blocks of code to be executed
o switch statement - use this statement if you want to select one of many blocks
of code to be executed
if Statement
o You should use the if statement if you want to execute some code only if a
specified condition is true.
o Syntax
if (condition)
{
code to be executed if condition is true
}
o Example
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>
If...else Statement
o If you want to execute some code if a condition is true and another code if the
condition is not true, use the if....else statement.
o Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Switch Statement
o You should use the switch statement if you want to select one of many blocks of
code to be executed.
o Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}
o This is how it works: First we have a single expression n (most often a variable),
that is evaluated once. The value of the expression is then compared with the
values for each case in the structure. If there is a match, the block of code
associated with that case is executed. Use break to prevent the code from
running into the next case automatically.
o Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>
o Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
o Example
Explanation: The example below defines a loop that starts with i=0. The loop
will continue to run as long as i is less than, or equal to 10. i will increase by 1
each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any
comparing statement.
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Result:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
Lecture-3
➢ Arrays
❖ An array object is used to create a database-like structure within a script. Grouping
data points (array elements) together makes it easier to access and use the data in
a script. There are methods of accessing actual databases (which are beyond the
scope of this series) but here we're talking about small amounts of data.
❖ An array can be viewed like a column of data in a spreadsheet. The name of the
array would be the same as the name of the column. Each piece of data (element) in
the array is referred to by a number (index), just like a row number in a column.
❖ An array is an object. Earlier, I said that an object is a thing, a collection of
properties (array elements, in this case) grouped together.
❖ ArrayMethods:
- concat(): Joins two or more arrays, and returns a copy of the joined arrays
- copyWithin(): Copies array elements within the array, to and from specified
positions
- entries(): Returns a key/value pair Array Iteration Object
- every(): Checks if every element in an array pass a test
- fill(): Fill the elements in an array with a static value
- filter(): Creates a new array with every element in an array that pass a test
- find(): Returns the value of the first element in an array that pass a test
- findIndex(): Returns the index of the first element in an array that pass a test
- forEach(): Calls a function for each array element
- from(): Creates an array from an object
- includes(): Check if an array contains the specified element
- indexOf(): Search the array for an element and returns its position
- isArray(): Checks whether an object is an array
- join(): Joins all elements of an array into a string
- keys(): Returns a Array Iteration Object, containing the keys of the original array
- lastIndexOf(): Search the array for an element, starting at the end, and returns its
position
- map(): Creates a new array with the result of calling a function for each array
element
- pop(): Removes the last element of an array, and returns that element
➢ Functions
❖ A function (also known as a method) is a self-contained piece of code that performs
a particular "function". You can recognise a function by its format - it's a piece of
descriptive text, followed by open and close brackets.A function is a reusable code-
block that will be executed by an event, or when the function is called.
❖ To keep the browser from executing a script when the page loads, you can put your
script into a function.
❖ A function contains code that will be executed by an event or by a call to that
function.
❖ You may call a function from anywhere within the page (or even from other pages if
the function is embedded in an external .js file).
❖ Functions can be defined both in the <head> and in the <body> section of a
document. However, to assure that the function is read/loaded by the browser
before it is called, it could be wise to put it in the <head> section.
❖ Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>
o The returned value from the prod() function is 6, and it will be stored in the
variable called product.
❖ The Lifetime of JavaScript Variables
o When you declare a variable within a function, the variable can only be accessed
within that function. When you exit the function, the variable is destroyed.
These variables are called local variables. You can have local variables with the
same name in different functions, because each is recognized only by the
function in which it is declared.
o If you declare a variable outside a function, all the functions on your page can
access it. The lifetime of these variables starts when they are declared, and ends
when the page is closed.
❖ Generally, the validation process is done at the server-side, which sends that
validation information to the front-end user. This process wastes the execution
time and user time.
❖ JavaScript gives us a way to validate the form's data before sending it to the server-
side. Validation in forms generally performs two functions, which are as follows:
i. Basic validation- It is a process to make sure that all of the mandatory fields
are filled or not.
ii. Data Format validation- As its name implies, it is the process to check that
entered data is correct or not. We have to include appropriate logic for
testing the correctness of data.
❖ Basic Form Validation
o It validates the mandatory input fields of the form, whether the required fields
are filled or not.
o Let us understand the process of basic form validation by using the following
example.
<!DOCTYPE html>
<html>
<head>
<title>Example of Basic form Validation</title>
<script>
function validateBasic() {
var name1 = document.basic.name.value;
var qual1 = document.basic.qual.value;
var phone1 = document.basic.phone.value;
if (name1 == "") {
alert("Name required");
return false;
}
if (qual1 == "") {
alert("Qualification required");
if (phone1 == "") {
alert("Mobile number is required");
return false;
}
}
</script>
</head>
<body>
<center>
<h1>Basic Form Validation</h1>
<form name="basic" action="#" onsubmit="return
validateBasic()">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td>Name: </td>
<td><input type="text" name="name"></td>
<tr>
<tr>
<td> Qualification: </td>
<td><input type="text" name="qual"></td>
</tr>
<tr>
<td>Phone no.:</td>
<td><input type="text" name="phone"></td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
<p id="d1"></p>
</center>
</body>
</html>
❖ String object
o The String object is used to manipulate a stored piece of text.
o Examples of use:
o The following example uses the length property of the String object to find the
length of a string:
var txt="Hello world!";
document.write(txt.length);
The code above will result in the following output:
12
o Window Object: Window Object is object of the browser which is always at top
of the hierarchy. It is like an API that is used to set and access all the properties
and methods of the browser. It is automatically created by the browser.
o Document object: When an HTML document is loaded into a window, it
becomes a document object. The ‘document’ object has various properties that
refer to other objects which allow access to and modification of the content of
the web page. If there is a need to access any element in an HTML page, we
always start with accessing the ‘document’ object. Document object is property
of window object.
o Form Object: It is represented by form tags.
o Link Object: It is represented by link tags.
o Anchor Object: It is represented by a href tags.
o Form Control Elements: Form can have many control elements such as text
fields, buttons, radio buttons, checkboxes, etc.
❖ DOM Methods
o DOM provides various methods that allows users to interact with and
manipulate the document. Some commonly used DOM methods are:
- write(“string”): Writes the given string on the document.
- getElementById(): returns the element having the given id value.
- getElementsByName(): returns all the elements having the given name
value.
Types Description
Window Object Represents the browser window and serves as the main tool for interaction
Model within the Browser Object Model (BOM).
History Object Enables navigation control by keeping track of the user’s browsing history in
Model the Browser Object Model (BOM).
Screen Object Offers information about the user’s screen, like its size, within the Browser
Model Object Model (BOM).
Navigator Object Provides details about the user’s browser and system characteristics within
Model the Browser Object Model (BOM).
Location Object Manages the current web address (URL) and allows changes within the
Model Browser Object Model (BOM).
❖ Window Size
o You can use two properties to find out the dimensions of the browser window,
and both provide the measurements in pixels:
window.innerHeight This gives you the vertical size or height of the browser window in pixels.
This gives you the horizontal size or width of the browser window in
window.innerWidth
pixels.
This method is used to open a new tab or window with the specified URL
window.open()
and name.
This method is used for closing a certain window or tab of the browser that
window.close()
was previously opened by the window.open( ) method.
This method is used in the window to move the window from the left and
window.moveTo()
top coordinates.
window.resizeTo() This method is used to resize a window to the specified width and height
Remember
1. Define Fuctions.
2. List out advantages of JavaScript
Understanding
At the end of this session, the facilitator (Teacher) shall randomly pic-up few students to
summarize the deliverables.