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

JS 1

This document provides an overview of JavaScript programming basics, including its features, capabilities, and limitations. It covers topics such as object creation, data types, expressions, and control structures like if statements. Additionally, it explains how to define functions and access object properties, along with examples for better understanding.

Uploaded by

Tanmay Warthe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

JS 1

This document provides an overview of JavaScript programming basics, including its features, capabilities, and limitations. It covers topics such as object creation, data types, expressions, and control structures like if statements. Additionally, it explains how to define functions and access object properties, along with examples for better understanding.

Uploaded by

Tanmay Warthe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

1

Unit 1: Basics of
JavaScript Programming
By: Ms
Lecturer, Government Polytechnic,
Bramhapuri
Things that you can't do by simply 2

using HTML
▪ Build dynamic web pages
▪ Display alert boxes
▪ Write messages to the browser status bar
▪ Control features of the browser
▪ Open new browser windows
▪ Customize reactions to mouse actions and keystrokes
▪ Validate information in forms
▪ Perform calculations
▪ Display messages when the cursor rolls over an object on the
screen
▪ Create interactive forms
▪ Set date and time
▪ Identify browsers and browser plug-ins such as Flash
3

: Things that JavaScript Can’tdo


▪Write files to your hard disk
▪Read files from your hard disk—except for
cookies
▪Close windows other than those the
JavaScript application opened
▪Write server-side applications,
Features of JavaScript 4
1. It is light-weighted as it can be embedded within 5
HTML of website.
2. JavaScript is a case-sensitive language that
means, if it has two members with same name but
different case, then they will be considered
different and also there is a special schema for
declaring variable names.
3. The client edge technology in Java Script allows
the client to have full control over the content which
is being updated in servers.
4. Validation of User‟s Input is most commonly known
as form validation, it allows users to interact with
client through filling forms through web pages.
5. IF and Else Statements are used to perform logical
operations.
6
6. Java Script is built with Interpreter which
allows the user to get the output without the use of
Compiler. That means the input performed by the
user gets rendered directly without the compiling of
codes.
7. It has event based approach to concurrency.
8. Giving the user more control over the browser.
9. It Handling dates and time.
10. It Detecting the user's browser and OS,
11. JavaScript is object based language as it provides
predefined objects.
12. Every statement in javascript must be terminated
with semicolon (;).
Objects 7

▪ A web page contains many objects, some of which


are the same kind of object.
▪ Example: it may contain two images, 5 buttons, 3
forms etc.
▪ Each object must be uniquely identified by a name or
ID that you assign to the object to reference it from
your JavaScript.
▪ Forms, for example, could be named form1 and
form2.
▪ Or you could assign forms names that identify the
purpose of each form, such as StudentDataForm and
DisplayForm, which more clearly identify each form in
your JavaScript.
Objects
Creating Objects in JavaScript
There are 3 ways to create objects.
By object literal
By creating instance of Object directly (using new keyword)
By using an object constructor (using new keyword)

By object literal
The syntax

object ={property1:value1,property2:value2.....propertyN:valueN}
var circle = {x:10, y:20,r :5};
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
Example
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
Object
By creating instance of Object
Javascript provides a special constructor function called
Object() to build the object. The return value of the Object() is
assigned to a variable.
The Syntax
var objectname=new Object();
var emp= new Object();

In the following example, the constructor methods are Object(),


Array(), and Date(). These constructors are built-in JavaScript
functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
Example
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type = "text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
By using an Object constructor

Here this keyword is used to refer to the object that has been
passed to a function.
Here, you need to create function with arguments. Each
argument value can be assigned in the current object by using
this keyword.
The this keyword refers to the current object.
Example
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
function book(title, author)
{ this.title = title;
this.author = author;
} </script>
</head>
<body> <script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
Property 8

▪ A property is a value that is associated with an


object.
▪ Objects can have many values, depending on the
type of object used.

▪ For example: A window has a backgroundcolor, a


width, and height. These are all properties of an
object.

▪ Each kind of object has its own set of properties.


Methods 9

▪ A method is a process performed by an objectwhen


it receives a message.

▪ For example, a Submit button on a form is an object.


Its Submit label and the dimensions of the button are
properties of the button object. If you click the Submit
button, the form is submitted to the server-side
application. In other words, clicking the Submit button
causes the button to process a method.

▪ The kinds of methods that are used differ, depending


on the type of object to which they‟re attached.
The Dot Syntax 10

▪ You can think of an object as being associated with certain


kinds of information (properties) and certain kinds of
behaviors (methods).
▪ You access an object‟s properties and methods by using the
dot syntax along with the object name and its property or
method. So, for example, here‟s how you would identify the
background color of a document and the write method for a
document:
document.bgColor
document.write()
▪ Each line has two parts:
▪ The first part is the name of the object, which isdocument.
▪ The second part is either a property (bgColor) or method
(write) of the object.
▪ A dot separates the name of the object from the property
or method.
Variables 11

▪ The word you need to use to declare a variable is var.


▪ The variable name can consist of any letter, digit, and an
underscore, but it cannot begin with a digit.
Data Types in JavaScript 12

Data types basically specify what kind of data can be stored


and manipulated within a program.
▪ String Data Type : Strings are created using single or
double quotes surrounding one or more characters
▪ var a = 'Hi there!'; // using single quotes
▪ var b = "Hi there!"; // using double quotes

▪ Number Data Type : The number data type is used to


represent positive or negative numbers with or without
decimal place, or numbers written using exponential notation
e.g. 1.5e-4 (equivalent to 1.5x10-4).
▪ var a = 25; // integer
▪ var b = 80.5; // floating-point number
▪ var c = 4.25e+6; // exponential notation, same as 4.25e6 or
4250000
▪ var d = 4.25e-6; // exponential notation, same as 0.00000425
Data Types in JavaScript 13

▪ Infinity is the result of dividing a nonzero number by 0


▪ alert(16 / 0); // Output: Infinity alert(-16 / 0); // Output:-Infinity
▪ While NaN represents a special Not-a-Number value.
▪ alert("Some text" / 2); // Output: NaN alert("Some text" / 2 +
10); // Output: NaN alert(Math.sqrt(-1)); // Output: NaN

▪ Boolean Data Type : The Boolean data type can hold only
two values: true or false.
▪ Var x= true;
▪ var a = 2, b = 5, c = 10; alert(b > a) // Output: true

▪ Undefined Data Type : If a variable has been declared, but


has not been assigned a value, has the value undefined.
▪ var a; var b = "Hello World!" alert(a) // Output: undefined
▪ alert(b)
// Output: Hello World!
Data Types in JavaScript 14

▪ Null Data Type : A null value means that there is no value. It is


not equivalent to an empty string ("") or 0, it is simply nothing.
▪ var a = null; alert(a); // Output: null

▪ Object Data Type : The object is a complex data type that


allows you to store collections of data.
▪ An object contains properties, defined as a key-value pair.
▪ var car = { modal: "BMW X3", color: "white", doors: 5 }

▪ Array Data Type : An array is a type of object used for storing


multiple values in single variable. Each value (also called an
element) in an array has a numeric position, known as its index.
▪ The simplest way to create an array is by specifying the array
elements as a comma-separated list enclosed by square brackets
▪ var colors = ["Red", "Yellow", "Green", "Orange"];
▪ var cities = ["London", "Paris", "New York"]; alert(colors[0]); // Output:
Red alert(cities[2]); // Output: New York
Expression 15

▪ A mathematical expression consists of two parts: operands


and operators.
▪ An operand is the value.
▪ An operator is the symbol that tells the browser how to
evaluate the mathematical expression.

▪ For Example,
10 / 5
▪ The division symbol (/) is the operator. The browser
evaluates this mathematical expression by dividing the value
on the right side of the operator to the value on the left side
of the operator
▪ JavaScript uses five types of operators: arithmetic operators,
logical operators, assignment operators, comparison
operators, and conditional operators.
Order of Operations 16

These are the same rules that you use in real


calculations and that you learned back in your high
school math class
1. Calculations must be performed from left to right.
2. Calculations in parentheses are performed first.
When more than one set of parentheses are
included, the expression in the inner parentheses is
performed first.
3. Multiplication and division operations are performed
next. If both operations are in an expression, then
calculations are performed left to right.
4. Addition and subtraction are next. If both operations
are in an expression, calculations are performed left
to right.
Arithmetic operators 17
Logical operators 18
Assignment operators 19
Comparison operators 20
Conditional operators 21
Object and Array Initialisers 22

▪ They specify property and element values.


▪ Also called as object literals or array literals.
▪ Array Initializer expression is comma separated list of
expression with square bracket.
var a= [1+2, 2+3, 3+4]

▪ The element expressions in an array initializer are evaluated


each time the array initializer is evaluated.

▪ Object Initializer expression is comma separated list of


expression with curly bracket and each sub expression with
property name and a colon.
var a = {p: 5, q: 6, r:7}
Function Definition Expressions 2

▪ A JavaScript function is defined with the help of function


definition expression.
▪ Also known as Function literal.
▪ It consists of keyword „function‟ followed by comma
separated list of parameters in parentheses and a block of
JavaScript code in curly braces.
▪ A function expression can be stored in a variable. Aftera
function expression has been stored in a variable, the
variable can be used as a function:

Var area = function (r) { return 3.14*r*r ; };


Var circle= area(6);

function myFunction(a, b)
{return a * b;}
Property Access Expressions 24

A property access expression evaluates to the value of an object


property or an array element. JavaScript defines two syntaxes for
property access:

expression . identifier
expression [ expression ]

var o = {x:1,y:{z:3}}; // An example object


var a = [o,4,[5,6]]; // An example array that contains the object
o.x // => 1: property x of expression o
o.y.z // => 3: property z of expression o.y
o["x"] // => 1: property x of object o
a[1] // => 4: element at index 1 of expression a
a[2]["1"] // => 6: element at index 1 of expression a[2]
a[0].x // => 1: property x of expression a[0]
Invocation Expressions 25

An invocation expression is JavaScript‟s syntax for calling (or


executing) a function or method. It starts with a function
expression that identifies the function to be called. The function
expression is followed by an open parenthesis, a comma-
separated list of zero or more argument expressions, and a
close parenthesis.

Math.max(x,y,z) // Math.max is the function; x, y and z are the


arguments.
x.sort() // x.sort is the function; there are no arguments.
Selection Statements 26

▪ You can create test conditions in the form of


expressions that evaluates to
either true or false and based on these results you
can perform certain actions.
▪ There are several conditional statements in
JavaScript that you can use to make decisions:

1. The if statement
2. The if...else statement
3. The if...else if....else statement
4. The switch...case statement
If Statement 27

▪ The if statement is used to execute a block of


code only if the specified condition evaluates to
true. This is the simplest JavaScript's
conditional statements and can be written like:

if(condition)
{
// Code to be executed
}
Example
<html>
<body>
<script type = "text/javascript">

var age = 20;


if( age > 18 )
{
document.write("<b>Qualifies for driving</b>");
}
</script>
<p>Set the variable to different value and then try...</p>
</body></html>
If…else Statement 28

▪ The if...else statement allows you to execute one


block of code if the specified condition is
evaluates to true and another block of code if it
is evaluates to false. It can be written, like this:
if(condition)
{
// Code to be executed if condition is true
}
else
{
// Code to be executed if condition is false
}
Example
<html>
<body>
<script type = "text/javascript">
<!–
var age = 15;
if( age > 18 )
{ document.write("<b>Qualifies for driving</b>");
}
else
{ document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
If…else if...else Statement 29

▪ The if...else if...else a special statement that is used to


combine multiple if...else statements.. It can be written,
like this:
if(condition1)
{
// Code to be executed if condition1 is true
}
else if(condition2)
{
//Code to be executed if the condition1 is false
and condition2 is true
}
else
{
// Code to be executed if both condition1 and
condition2 are false
}
Example
Nested If Statement 30

▪ Embedding If Statement inside another IF Statement called


JavaScript Nested If Statement. It can be written, like this:
if ( test condition 1)
{
//If the test condition 1 is TRUE then these it will check
for test condition 2
if ( test condition 2)
{ //If the test condition 2 is TRUE then these
statements will be executed Test condition 2
True statements; }
else
{ //If the c test condition 2 is FALSE then these
statements will be executed Test condition 2
False statements; }
else
{ //If the test condition 1 is FALSE then these
statements will be executed Test condition 1 False
statements;
}
Switch.. case Statement 31

▪ An if statement can become unwieldy if a series of


decisions have to be made based on a single value.
▪ A switch...case statement tells the browser to compare a
switch value with a series of case values. If the switch
value matches a case value, then the browser executes
statements that are placed beneath the case value. A
switch...case statement has eight parts:
▪ The switch keyword.
▪ A switch value is compared to case values; the switch value
must be placed within parentheses.
▪ The case keyword.
▪ A case value is compared to the switch value; the case value
must be placed between the case keyword and a colon.
▪ Case statements are beneath a case value and are executed if
the
case value matches the switch value.
▪ The break keyword (optional) tells the browser to skip all the
other cases and execute the statement that appears at the
end of the switch...case statement.
▪ The default keyword (optional) contains statements
that are executed if none of the case values match
the switch value.
Example
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
</body>
</html>
32

Syntax
switch (value)
{
case value1:
//Place statements here.
break;
case value2:
//Place statements here.
break;
default:
//Place statements here.
}
Loop Statement 33

▪ A loop is used to execute one or more statements


repeatedly, without your having to duplicate those
statements in your JavaScript.
▪ You can use four types of loops in a JavaScript:
1. for loop
2. for in loop
3. While loop
4. do...while loop.
for Loop 34

▪ The for loop tells the browser to execute statements


within the for loop until a condition statement returns
false.
▪ Here‟s the structure of the for loop:
for ( initializer; conditional expression ; post loop
statements)
{
//Place statements here.
}
▪ The initializer holds the number of times the
browser executed statements within the loop.
▪ The conditional expression sets the condition when
the browser should stop executing statements with the
loop.
▪ The post loop statements increase or decrease
the value of the initializer
Example
<html>
<body>
<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>
<p>Set the variable to different value and then try...</p>
</body>
</html>
for in Loop DNB, GP Ambad
35

▪ The for in loop is a special kind of for loop that is


used whenever you don‟t know the number of
times that the browser should loop. This happens
when you want to retrieve all the properties of an
object, but you don‟t know how many properties
are associated with the object.
▪ The for in loop tells the browser to execute
statements within the code block for each item on
a list.
for(list)
{
//Place statements here.
}
Example
<html>
<body>
<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>
<p>Set the variable to different object and then try...</p>
</body>
</html>
While Loop 36

▪ A while loop evaluates the condition inside the


parenthesis ().
▪ If the condition evaluates to true, the code inside
the while loop is executed.
▪ The condition is evaluated again.
▪ This process continues until the condition is false.
▪ When the condition evaluates to false, the loop
stops.

while (condition)
{
// body of loop
}
Example
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
Do While Loop 37

▪ The body of the loop is executed at first. Then


the condition is evaluated.
▪ If the condition evaluates to true, the body of the
loop inside the do statement is executed again.
▪ The condition is evaluated once again.
▪ If the condition evaluates to true, the body of the
loop inside the do statement is executed again.
▪ This process continues until
the condition evaluates to false.
Then the loop stops.

do
{ // body of loop
} while(condition)
Example
<html>
<body>
<script type = "text/javascript">
<!–
var count = 0;
document.write("Starting Loop" + "<br />");
do
{ document.write("Current Count : " + count + "<br />");
count++;
}
while (count < 5);
document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Loop Control Statements
The break Statement
The break statement, which was briefly introduced with
the switch statement, is used to exit a loop early, breaking out
of the enclosing curly braces.
Flow Chart
The flow chart of a break statement would look as follows −
Example
<html>
<body>
<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>
<p>Set the variable to different value and then try...</p>
</body> </html>
Loop Control Statements
The continue Statement
The continue statement tells the interpreter to immediately
start the next iteration of the loop and skip the remaining code
block. When a continue statement is encountered, the
program flow moves to the loop check expression immediately
and if the condition remains true, then it starts the next
iteration, otherwise the control comes out of the loop.
Example
<html>
<body>
<script type = "text/javascript">
<!–
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{ x = x + 1;
if (x == 5) { continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Property Getters and Setters 38

▪ In JavaScript, there are two kinds of object


properties:
1. Data properties
2. Accessor propertie
▪ Data Property
student= {name: “divya”}
▪ Accessor Property
In JavaScript, accessor properties are methods that
get or set the value of an object. For that, we use
these two keywords:
1. get - to define a getter method to get the property
value
2. set - to define a setter method to set the property
value

You might also like