0 ratings0% found this document useful (0 votes) 32 views27 pagesUnit I - Basics of JavaScript Programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Basies of JavaScript Programming
Unit-1
Basics of JavaScript Programming
Q. What is JavaScript?
a) JavaScript is an object-based scripting language.
b) JavaScript makes a web page more interactive.
©) Itallows you to implement dynamic features on web pages.
4) JavaScript can update and change both HTML and CSS.
e) JavaScript can calculate, manipulate and validate data.
1.1 Features of JavaScrip
Q. List features of Java script.
Answer:
1) JavaScript is an object-based scripting language.
2). Giving the user more control over the browser.
3) It Handling dates and time.
4) Itdetecting the user's browser and OS.
5) Itis light weighted.
6) Client-Side Technology.
7) JavaScript is a scripting language and it is not java
8) JavaScript is interpreter based scripting language.
9) JavaScript is case sensitive
10) JavaScript is object based language as it provides predefined objects.
11) Every statement in JavaScript must be terminated with semicolon,
12) Most of the JavaScript contro! statements syntax is same as syntax of control statements in
C language.
13)An important part of JavaScript is the ability to create new fun
Declare a function in JavaScript using function keyword.
ions within scripts.
Q. Explain features of Java script.
1) Client-Side Technology: JavaScript is a client-side technology. It is mainly used for
giving client-side validation. It is an object-based scripting language.
2) Greater Control: It gives the user more control over the browser.
Example — You can change the background color of the page as well as text on the
browser's status bar. Here, the back button is implemented with JavaScript. Click it and
you will return to the page from which you have arrived.
3) Detecting the User’s Browser and OS: The feature to detect the user's browser and
OS enables your script to perform platform-dependent operations.
4) Browser support: To access flash content, you need to install a flash plugin in your
browser. But to use JavaScript, you don't have to use any plugin at all. This is because all
browsers have accepted JavaScript as a scripting language for them and provide
integrated support for it. All you need to do is to handle some of the tasks that are
9423034909 1Basies of JavaScript Programming
dependent on the DOM (Document Object Model) of different browsers properly.
5) Performing Simple Calculation on the Client side: Using a JavaScript calculator,
we perform simple calculations on the client side.
6) Validating The User’s Input: In the JavaScript calculator, try to type some lette ad
of numeric input, you will get an error: Invalid input character. Note that JavaScript
helps the browser perform output validation without wasting the user’s time by the web
server access.
If the user makes a mistake in the input, the user will get an error message immediately. If
the input information is validated only on the server, then the user would have to wait for
the server's response.
7) Handling Date and time: The Date object is a built-in object in JavaScript that stores
the date and time. It provides a number of built-in methods for formatting and managing
that data.
1.2 Object Name, Property, method, Dot Syntax, Main event:
Object Name:
1) JavaScript is an object based scripting language.
2) It allows us to define our own objects and make our own variable types.
3) It also offers a set of predefined objects.
4) The tables, forms, buttons, images, or links on our web page are examples of objects.
5) The values associated with objects are properties and the actions that can perform on
objects are methods or behavior.
6) Property associated to an object can be accessed as follows:
Example for object and property using dot (.)
Syntax: ObjectName.PropertyName
Example: documentaitle;
In the above example “document” is an object name accessing property of document
“title” with “.” (Dot syntax)
Property:
1) Properties are the values associated with a JavaScript object.
2). A JavaScript object is a collection of properties.
3) Properties can usually be changed, added, and deleted, but some are read only.
4) List of Some of the common properties of the document object are:
a) Title - returns/ sets the title of the current document.
) Forms - retums a list of the FORM elements within the current document.
) Images - returns a list of the images in the current document
4) URL- returns a string containing the URL of the current document
€) Location - to load another URL in the current document window.
Syntax: ObjectName.PropertyName
Example: document.title;
In the above example “document” is an obj
“(Dot syntax)
name accessing property of document “title” with
9423034909 2Basies of JavaScript Programming
Dot Syntax:
1) For accessing properties and methods of an object we can use dot (.) operator.
Syntax:
‘ObjectName.PropertyName
or
ObjectName.MethodName
Example:
document.itle;
or
document.write);
In the above example “document” is an object name accessing property “title” and method
“write” with “ .” dot operator.
Method:
1) Method is a function or a process associated with each object,
2) JavaScript methods are actions that can be performed on objects.
3) List of some methods and its purposes:
a) open() - Opens a document for writing
b) write) - Writes string/data to a document
©) writeln() - Writes string/data followed by a newline character to a document
4) close() - Closes a document stream for writing.
‘Syntax: ObjectName.MethodName
Example: document.write();
My Page Titles/title>
s/html>
Output: The title of this HTML document is: My Page Title
‘Main Event:
1) JavaScripts interaction with HTML is handled through events that occur when the user
or the browser manipulates a page.
2) When the page loads, it is called an event.
3) When the user clicks a button, that click too is an event.
4) Other examples include events like pressing any key, closing a window, resizing a
low, ete.
9423034909 3Basies of JavaScript Programming
1.3 Values and Variables:
Variables:
1) A variable is an identifier that can store values.
2) A JavaScript variable can hold a value of any data type.
3) These values can be changed during the execution of the script.
4) Once a value is stored in a variable it can be accessed using the variable name.
5) Variable declaration is not compulsory, though it is a good practice to use variable
declaration
6) Generally keyword var is used to declare a variable.
7) 4 Ways to Declare a JavaScript Variable:
© Using var
Using const
* Using nothing
8) Always declare JavaScript variables with var, let, or const.
is used in all JavaScript code from 1995 to 2015.
10) The let and const keywords were added to JavaScript in 2015.
11) If you want your code to run in older browser, you must use var.
12) If you think the value of the variable can’t change, use const.
Syntax:
var variable_name;
var variable_name = value;
let variable_name;
const variable_name;
9) The var keywor
Example:
var x =5;
let
const pi=3.14;
x=5;
Values:
In JavaScript, there are six primitive data types:
Boolean, Number, String, Null, Object, and Function
1) Boolean
* A Boolean represents only one of two values: true, or false.
2) Number:
+ There is only one type of Number in JavaScript.
* Numbers can be written with or without a decimal point
Example:
9423034909 4Basics of JavaScript Programming,
var a=5;
var b=2.5;
3) String:
‘© Strings are used for storing text.
‘* String is collection of characters.
‘© Strings must be inside of either double or single quotes.
‘In JavaScript, Strings contains numbers also.
Example:
var str="JavaScript”s
Null has one value: null,
* Ibis explicitly nothing
Example:
var nothing = null;
5) Object:
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.
Example:
Form object is an object upon which some components such as button, checkbox etc. can
be placed and used,
6) Function:
‘© The function is a callable object that executes a block of code.
# Since functions” are objects, so it is possible to assign them to variables, as shown in the
example below:
Example:
var message = function()
{
return "Hello World!’
}
Keywords:
abstract arguments await boolean break
byte case catch char
const continue | debugger default delete
do double else enum eval
export extends false final
9423034909 5Basies of JavaScript Programming
float for function goto if
implements | import in instanceof int
interface let long native new
null package private protected public
return short static super switch
throw this throws transient true
uy typeof var void volatile
yield
1.4 Operators and Expressions:
Operators:
Following types of operators in JavaScript:
1) Arithmetic Operators
2) Comparison (Relational) Operators
3) Bitwise Operators
4) Logical Operators
5) Assignment Operators
6) Special Operators
1) Arithmetic Operators:
Arithmetic operators are used to perform arithmetic operations on the operands, The
following operators are known as JavaScript arithmetic operators.
Operator | Description Example
+ Addition a=10, b=20; c= a+b; c=30
- Subtraction a=50, b=20;
* Muttiplication a0,
1 Division 100, b=20; c= a/b;
[ Modulus en
% (Remainder) a=10,b=2; c= a % b; c=0
+ Increment var a=10; a+; Now a= II
- Decrement
94230349092) Comparison (Relational) Operators
‘The JavaScript comparison operator compares the two operands. The comparison operators
are as follows:
Basies of JavaScript Programming
Operator | Description Example
== | fsequalto a=10,
Identical (equal and of same | 10= = =20; false
type)
1= | Notequal to 10!=20; true
Not Identical
20!= =20; false
> Greater than 20>10; true
>= Greater than or equal to 20>=10; true
< Less than 20610; false
Less than or equal to
20<=10; false
3) Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:
Operator | Description Example
& Bitwise AND
Bivwise OR
=10 | 20= =33) = 1
7 Bitwise XOR 20 * 20= =33) = 0
- Bitwise NOT (-10)=-11
<< Bitwise Left Shift (10<<2) = 40
> Bitwise Right Shift (0>>2) =2
>>> | Bitwise Right Shift with Zero (10>>52) =2
eeBasies of JavaScript Programming
4) Logical Operators
The following operators are known as JavaScript logical operators. Logical operators are
used to determine the logic between variables or values.
Operator Description Example
(10= =20 && 20= =33) = false
al AND OR
(20==20 && 33==33) = true
&& Los
(10= =20 |] 2
I Logical OR OR
(10==10 [2
! Logical Not 1(10==20) = true
5) Assignment Operators
Operator | Description Example
= Assign a=10, b=20; c= a+b;
+ ‘Add and assign a=10; a+=20; Now a= 30
= Subtract and assign 2220; a-=10; Now a= 10
* Multiply and assign a=10; a*=20; Now a= 200
i Divide and assign 10; a/=2; Now a= 5
Modulus and assign a=10; a%=2; Now a=0
©) Special Operators
The following operators are known as JavaScript special operators.
Operator Description
(2) | Conditional Operator returns value based on the condition, Its like if-else
: Comma Operator allows multiple expressions to be evaluated as single statement,
delete | Delete Operator deletes a property from the object.
9423034909 8Basies of JavaScript Programming
in In Operator checks if object has the given property
instanceof | checks if the object is an instance of given type
new creates an instance (object)
typeof | Checks the type of object.
void It discards the expression's return value.
yield | Checks what is returned in a generator by the generators iterator.
Expressions:
1) An expression is a unit of code that a JavaScript interpreter can parse and compute to
produce a value.
2) There are simple expressions like literal values and complexes which are built from
simpler ones usually using operators.
Primary Expressions:
1) Primary expressions refer to stand alone expressions such as literal values, certain keywords
and variable values.
2) The simplest expressions, known as primary expressions, are those that stand alone,
3) They do not include any simpler expressions.
Example:
1.23. // A number literal
“hello” A string literal
Ipattern/ // A regular expression literal
Object and Array initializers:
Object initializers:
1) Object initializers are expressions whose value is a newly created object.
2). These initializer expressions are sometimes called “object literals’
3) Unlike true literals, however, they are not primary expressions, because they include a number
of sub expressions that specify property and element values,
Syntax:
var object_name =
Exampl
var p= { x: 2.3, y:-1.2 }; // An object with 2 properties
var q= (5 1/ An empty object with no properties
property:valuel, property:value2,...., property:valueN };
Array initializer
1) An array initializer is a comma-separated list of expressions contained within square
9423034909 9Basies of JavaScript Programming
brackets.
2) The value of an array initializer is a newly created array,
Example:
Syntax:
‘const array_name
var array_name
Example:
var arr = [1, 2,
var array_name
item1, item2, .., element];
ew Array(elementl. element2, ...., elementN);
jew Array("CSS", "AJP", "STE");
Function definition expressio
1) A JavaScript function can also be defined using an expression,
2) A function expression can be stored in a variable:
var x = funetion (a, b)
{
return a * b
}
3) After a function expression has been stored in a variable, the variable can be used as a
function,
Example:
var sum = function (x, y)
(
return x + y;
1
var z= sum (3,4); M7
Property access expressions:
1) A property access expression evaluates to the value of an object property or an array
element.
2) JavaScript defines two syntaxes for property access:
expression.identifier
expression [expression]
3). The first style of property access is an expression followed by a period and an identifier.
4) The expression specifies the object, and the identifier specifies the name of the desired
property,
5) The second style of property access follows the first expression (the object or array)
with another expression in square brackets.
Example:
var obj = {x:1, y:2}; obj.x // 1
objf'y]/2
var arr = (2, 3];
arr(1] 73
9423034909 10Basies of JavaScript Programming
Invocation expressions:
1) An invocation expression is JavaScript’s syntax for calling (or executing) a function or
method
2) It starts with a function expression that identifies the function to be called,
3) The function expression is followed by an open parenthesis, a comma-separated list of
zero or more argument expressions, and a close parenthe
Example:
funl (arg);
display);
1.5 If Statement, if...else, if...else if, nested if statement:
If statement:
* It evaluates the content only if the expression is true, The syntax of JavaScript if
statement is given below.
Syntax:
if(expression)
{
Heontent to be evaluated
}
Flowchart of JavaScript If statement:
True
False
Body of it
Example:
Example of if Statement
9423034909 1asics of JavaScript Programming
Output:
a is equal to 20
Nested if statement:
«A nnested if is the target of another if or else.
* Nested if statements mean an if statement inside an if statement.
Syntax:
if condition!
{
// Executes when condition! is true
if condition2
{
/ Executes when condition? is true
}
}
9423034909 4Basies of JavaScript Programming
17 using if statement
if(v1==50) {
1/if condition is true then
JI check the following
if(v2==60)
{
/1f condition is true
// then display the following
document.write("Value of v1 is 50 and v2 is 60");
}
}
1.6 Switch Statement:
1) The JavaScript switch statement is used to execute one code from multiple expressions.
2) It is just like if..else..if statement, but it ig more convenient than if..else..f because it can
be used with numbers, characters etc.
3) Working of switch case statement:
a) The switch expression is evaluated once.
bb). The value of the expression is compared with the values of each case.
©) If there is a match, the associated block of code is executed.
d) If there isno match, the default code block is executed.
Syntax:
switch(expression)
(
case valuel:
Mode to be executed; break;
case value2:
JIcode to be executed; break;
default:
Hcode to be executed if above values are not matched;
}
9423034909 15Basies of JavaScript Programming
Example of switch case Statements/TITLE>
Output:
€ > @ O File| CyZambareds/css%.. @ x Ol A ¢
1 to 5 numbers printing using for loop:
aboRe
JavaScript while loop:
1) The JavaScript while loop iterates the elements for an infinite number of times.
9423034909 72) It should be used if the number of iterations
Basies of JavaScript Programming
is not known.
3) The syntax of the while loop is given below.
Syntar
Exampl
while (condition)
{
code to be executed
Output:
Example of while loops/TITLE>
€ > S O Fie| c/zambarepaycss%.. 1 t OO FX:
JavaScript do while loop:
1) The JavaScript do-while loop iterates the elements for an infinite number of times like a
while loop.
2) But, code is executed at least once whether the condition is true or false.
9423034909
18,Basics of JavaScript Programming,
3) The syntax of do while loop is given below.
Syntax:
do
{
IIcode to be executed
}
while (condition);
Example:
Example of do while loops/TITLE>
Output:
@ Example of do while loop
€ > © O File | C/ZambareDB/css%.. tr Tl FA
JavaScript for in loo}
1). The JavaScript for in loop is used to iterate the properties of an object.
Syntax:
for(variable in object)
{
Hcode to be executed
9423034909 19Basics of JavaScript Programming,
}
OR
for (key in object) {
1/ code block to be executed
}
Example:
Example of for in loops/TITLE>
Output:
a
€ > © O File | CyZambareD#/Css%.. 12 vx Oh AX
for in loop example:
Dattatray
Zambare
33
Continue statement:
1) The continue statement breaks one iteration (in the loop) if a specified condition occurs,
and continues with the next iteration in the loop.
Example:
Example of continue statement
9423034909 20Basies of JavaScript Programming
var text =
document.write("A loop which will skip the step where i=3
"
for (let
i <= 10; +4)
continue;
}
text += "The number is "+i + "
";
}
document.write(text);
Output:
@ Example cf continue statement x
€ > S O File| cyzambarevaycss%a0rr.. 1 Oh FA
A loop which will skip the step where i=
The number is 0
The number is 1
The number is 2
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
1.8 Querying and setting properties and deleting properties:
Property Attributes:
1) All properties have a name.
9423034909
2Basies of JavaScript Programming
2) In addition they also have a value.
3). The value is one of the property's attributes.
Adding New Properties:
1) You can add new properties to an existing object by simply giving it a value.
2) Assume that the person object already exists - you can then give it new properties:
Example:
person.nationality = "Indian";
Deleting Properties:
1) The delete keyword deletes a property from an object:
Example
var person=
firstName:"Dattatray",
lastName:"Zambare"
age:33,
eyeColor:"black"
delete person.age;
or
delete personf"age"];
2) The delete keyword deletes both the value of the property and the property itself. After
deletion, the property cannot be used before it is added back again.
3) The delete operator is designed to be used on object properties. It has no effect on variables or
functions.
4) The delete operator should not be used on predefined JavaScript object properties. It can crash
your application.
Q. Write a Java script to create person object with properties firstname, lastname, age,
eyecolor, delete eyecolor property and display remaining properties of person object.
Answer:
24Basies of JavaScript Programming
Output:
a
€ > GO Fie| C/ZambareDeycss%20rr.. 2? tr | Th FA
Car color:blue Car Make: Toyota
Car colored Car Make: Audi
OR.
Q. Explain setter and getter properties in JavaScript with the help of suitable example.
Property getters and sette
1. The accessor properties. They are essentially functions that work on getting and setting a value.
2. Accessor properties are represented by “getter” and “setter” methods. In an object literal they are
denoted by get and set.
get: It is used to define a getter method to get the property value.
set: It is used to define a setter method to set / change the property value
let obj
get propName()
{
1! getter, the code executed on getting obj.propName
}
set propName(value)
{
setter, the code executed on setting obj.propName = value
}
K
3. An object property is a name, a value and a set of attributes. The value may be replaced by one or
two methods, known as setter and a getter.
Example of getter and Setter:
property getters and setters
1) Itdisplays the confirm dialog box. Ithas message with ok and eancel buttons.
2) Returns Boolean indicating which button was pressed
Synta
Example :
alert():
low.confirm("sometext");
"delete record” onclick="msg()"/>
It displays the alert dialog box. It has message with ok button.
Syntax:
window.alert("some alert text");
Example :
9423034909