0% found this document useful (0 votes)
27 views17 pages

Unit 3

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)
27 views17 pages

Unit 3

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/ 17

Unit -III Javascript

Q1: Discuss in detail about javascript.


Ans: JavaScript is a lightweight, cross-platform, and interpreted scripting
language. JavaScript can be used for Client-side developments as well
as Server-side developments. JavaScript contains a standard library of objects,
like Array, Date, and Math, and a core set of language elements
like operators, control structures, and statements.

Applications of JavaScript:
● Web Development: Adding interactivity and behavior to static sites JavaScript
was invented to do this in 1995. By using AngularJS that can be achieved so
easily.
● Web Applications:When we explore a map in Google Maps then we only need to
click and drag the mouse. All detailed views are just a click away, and this is
possible only because of JavaScript. It uses Application Programming
Interfaces(APIs) that provide extra power to the code.
● Server Applications: With the help of Node.js, JavaScript made its way from
client to server and node.js is the most powerful in the server-side.
● Games: Not only in websites, but JavaScript also helps in creating games for
leisure. The combination of JavaScript and HTML 5 makes JavaScript popular in
game development as well.
● Smartwatches: JavaScript is being used in all possible devices and applications.
It provides a library called PebbleJS which is used in smartwatch applications.
This framework works for applications that require the internet for its
functioning.
● Art: Artists and designers can create whatever they want using JavaScript to
draw on HTML 5 canvas, make the sound more effective also can be
used p5.js library.
● Machine Learning: This JavaScript ml5.js library can be used in web
development by using machine learning.

Limitations of JavaScript:
Performance: JavaScript does not provide the same level of performance as offered
by many traditional languages as a complex program written in JavaScript would be
comparatively slow. But as JavaScript is used to perform simple tasks in a browser,
performance is not considered a big restriction in its use.
Complexity: To master a scripting language, programmers must have a thorough
knowledge of all the programming concepts, core language objects, client and
server-side objects otherwise it would be difficult for them to write advanced scripts
using JavaScript.
Weak error handling and type checking facilities: It is weakly typed language as
there is no need to specify the data type of the variable. So wrong type checking is
not performed by compile.

Advantages of JavaScript
● Speed. Client-side JavaScript is very fast because it can be run immediately within
the client-side browser. Unless outside resources are required, JavaScript is
unhindered by network calls to a backend server.
● Simplicity. JavaScript is relatively simple to learn and implement.
● Popularity. JavaScript is used everywhere on the web.
● Interoperability. JavaScript plays nicely with other languages and can be used in a
huge variety of applications.
● Server Load. Being client-side reduces the demand on the website server.
● Gives the ability to create rich interfaces.

Disadvantages of JavaScript
● Client-Side Security. Because the code executes on the users’ computer, in some
cases it can be exploited for malicious purposes. This is one reason some people
choose to disable Javascript.
● Browser Support. JavaScript is sometimes interpreted differently by different
browsers. This makes it somewhat difficult to write cross-browser code.

Q2: Define Data Type. Explain various Data Types available in Javascript.
Ans: A data type in programming refers to a classification that specifies which
type of value a variable can hold, what operations can be performed on it, and how it
is stored in memory.
Data types are fundamental in programming languages because they help ensure
data integrity, enable efficient memory allocation, and provide clarity about how data
should be used and manipulated.
JavaScript provides different data types to hold different types of values.

1. Primitive Data Types:


● Number: Represents both integer and floating-point numbers.
● String: Represents textual data, enclosed within single ('') or double ("")
quotes.
● Boolean: Represents a logical value, either true or false.
● Undefined: Represents a variable that has been declared but not
assigned a value.
● Null: Represents the intentional absence of any value.
● Symbol: Represents unique identifiers. (Introduced in ECMAScript 6)
2. Object Data Type:

Object: Represents a collection of key-value pairs, where keys are strings (or
symbols) and values can be of any data type. Objects are used for more
complex data structures and can hold functions and other objects.

3. Special Data Types:


● Function: A subtype of object, but is callable. Functions are a core
concept in JavaScript and are used to define reusable blocks of code.
● Array: A special type of object used to store multiple values in a single
variable. Arrays can hold any data type and are indexed starting from
zero.
● Date: Represents dates and times. It allows you to work with dates,
including creating, formatting, and manipulating them.

A. The String Data Type


The string data type is used to represent textual data (i.e. sequences of
characters). Strings are created using single or double quotes surrounding one
or more characters, as shown below:
Example
var a = 'Hi there!'; // using single quotes
var b = "Hi there!"; // using double quotes

B. The 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).
Example
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

C. The Boolean Data Type


The Boolean data type can hold only two values: true or false. It is typically
used to store values like yes (true) or no (false), on (true) or off (false), etc. as
demonstrated below:
Example
var isReading = true; // yes, I'm reading
var isSleeping = false; // no, I'm not sleeping
D. The Null Data Type
This is another special data type that can have only one value-the null value.
A null value means that there is no value. It is not equivalent to an empty string
("") or 0, it is simply nothing.
A variable can be explicitly emptied of its current contents by assigning it
the null value.
Example
var a = null;
alert(a); // Output: null

E. The 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. A property key (name) is
always a string, but the value can be any data type, like strings, numbers, booleans,
or complex data types like arrays, function and other objects. You'll learn more about
objects in upcoming chapters.
The following example will show you the simplest way to create an object in
JavaScript.
Example
var emptyObject = {};
var person = {"name": "Clark", "surname": "Kent", "age": "36"};

// For better reading


var car = {
"modal": "BMW X3",
"color": "white",
"doors": 5
}

F. The Array Data Type


An array is a type of object used for storing multiple values in a single variable.
Each value (also called an element) in an array has a numeric position, known
as its index, and it may contain data of any data type-numbers, strings,
booleans, functions, objects, and even other arrays. The array index starts
from 0, so that the first array element is arr[0] not arr[1].
The simplest way to create an array is by specifying the array elements as a
comma-separated list enclosed by square brackets, as shown in the example
below:
Example
var colors = ["Red", "Yellow", "Green", "Orange"];
var cities = ["London", "Paris", "New York"];

alert(colors[0]); // Output: Red


alert(cities[2]); // Output: New York

Q3) What is a conditional Statement ? Explain various conditional


statements in Javascript?
Ans: Conditional statements control behavior in JavaScript and determine whether
or not pieces of code can run. In JavaScript we have the following conditional
statements:

● Use if to specify a block of code to be executed, if a specified condition


is true
● Use else to specify a block of code to be executed, if the same condition
is false
● Use else if to specify a new condition to test, if the first condition is
false
● Use switch to specify many alternative blocks of code to be executed

I. If Statement
The if statement is a fundamental control flow statement in JavaScript, used for
conditional execution of code blocks based on specified conditions. Use
the if statement to specify a block of JavaScript code to be executed if a condition is
true.

Syntax
if (condition) {
// block of code to be executed if the condition is true
}

Example: Make a "Good day" greeting if the hour is less than 18:00:
if (hour < 18) {
greeting = "Good day";
}

The result will be (output):


Good day

II. Else Statement


The else statement in JavaScript is used in conjunction with the if statement to provide
an alternative code block to execute when the condition specified in the if statement
evaluates to false. Use the else statement to specify a block of code to be executed if
the condition is false.

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example: If the hour is less than 18, create a "Good day" greeting, otherwise "Good
evening":
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

The result of greeting will be:

Good day

III. Else if Statement


The else if statement in JavaScript allows you to add additional conditions to check
after the initial if condition. It's used when you have multiple conditions to evaluate,
and you want to execute different blocks of code depending on which condition is
true. Use the else if statement to specify a new condition if the first condition is
false.

Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example: If time is less than 10:00, create a "Good morning" greeting, if not, but time is
less than 20:00, create a "Good day" greeting, otherwise a "Good evening":
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

The result of greeting will be:

Good day

IV. Switch Statement


The switch statement in JavaScript is a control flow statement used to execute one
of multiple blocks of code based on the value of an expression. It provides a concise
way to compare a single value against multiple possible cases and execute different
code blocks depending on the matched case.

This is how it works:

● The switch expression is evaluated once.


● 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.
● If there is no match, the default code block is executed.

Example
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}

The result of day will be:

Sunday

Q4.Explain about Looping statements in Javascripts


Ans:

JavaScript Loops
Loops are handy to run the same code over and over again, each time with a
different value.Loops enable you to repeat a set of instructions multiple times
without having to write them out explicitly for each iteration. This saves time and
reduces redundancy in your code.

In JavaScript we have the following looping statements:

1. while - loops through a block of code while a condition is true


2. do...while - loops through a block of code once, and then repeats the loop while a
condition is true
3. for - run statements a specified number of times

● While Loop

The while loop executes a block of code as long as the specified condition evaluates to
true. It checks the condition before executing the loop body. The while statement will
execute a block of code only when a condition is true.

while (condition)
{
code to be executed
}

Example:
<html>
<body>
<script type="text/javascript">
i=0
while (i<=5)
{
document.write("<b>The number is " + i + "</b>")
document.write("<br>")
i++
}
</script>
<p>Explanation:
<p>The for loop sets <b>i</b> equal to 0.
<p>As long as <b>i</b> is less than or equal to 5, the loop will continue to run.
<p><b>i</b> will increase by 1 each time the loop runs.
</body>
</html>

● Do...while

Similar to the while loop, but it checks the condition after executing the block of code.
This means the block of code will always execute at least once.The do...while statement
will execute a block of code once, and then it will repeat the loop while a condition is
true.

do
{
code to be executed
}
while (condition)

Example:
<html>
<body>
<script type="text/javascript">
i=0
do
{
document.write("<b>The number is " + i + "</b>")
document.write("<br>")
i++
}
while (i<=5)
</script>
<p>Explanation:
<p>The for loop sets <b>i</b> equal to 0.
<p>As long as <b>i</b> is less than or equal to 5, the loop will continue to run.
<p><b>i</b> will increase by 1 each time the loop runs.
</body>
</html>

● For Loop

The for loop is one of the most common looping structures. It consists of three parts:
initialization, condition, and iteration. The for statement will execute a block of code a
specified number of times.
for (initialization; condition; increment)
{
code to be executed
}

Example:
<html>
<body>
<script type="text/javascript">
for (i=0; i<=5; i++)
{
document.write("<b>The number is " + i + "</b>")
document.write("<br>")
}
</script>
<p>Explanation:
<p>The for loop sets <b>i</b> equal to 0.
<p>As long as <b>i</b> is less than or equal to 5, the loop will continue to run.
<p><b>i</b> will increase by 1 each time the loop runs.
</body>
</html>

Q5. List various objects provided by Java Script


Ans:
Objects, in JavaScript, is it’s most important data-type and forms the building blocks
for modern JavaScript. These objects are quite different from JavaScript’s primitive
data-types(Number, String, Boolean, null, undefined and symbol) in the sense that
while these primitive data-types all store a single value each (depending on their
types).
1. The Number Object
The Number object represents numerical data, either integers or floating-point
numbers. The browser automatically converts number literals to instances of the
number class.
Syntax: The syntax for creating a number object is as follows −
var sub = new Number(number);

2. The Boolean Object


The Boolean object 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.
Syntax:
var sub = new Boolean(value);
3. The Strings Object
The String object lets you work with a series of characters. There are string methods
and properties associated with the String object. These methods and properties are
accessible via string literals or instances of the String object. JavaScript provides
numerous methods for working with strings.
Some common methods include charAt(), charCodeAt(), indexOf(), concat(), slice(),
substring(), toUpperCase(), toLowerCase(), trim(), and replace().

Syntax
var sub = new String(string);

4. The Arrays Object


The Array object lets you store multiple values in a single variable. It stores a
fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
Syntax
var fruits = new Array( "apple", "orange", "mango" );

5. The Date Object


The Date object is a datatype built into the JavaScript language. Date objects are
created with the new Date( ). Once a Date object is created, a number of methods
allow you to get and set the year, month, day, hour, minute, second, and millisecond
fields of the object, using either local time or UTC (universal, or GMT) time.
Syntax
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

6.The Math Object


The math object provides you properties and methods for mathematical
constants and functions. Unlike other global objects, Math is not a constructor. All
the properties and methods of Math are static and can be called by using Math as
an object without creating it.
The Math object also provides numerous mathematical methods for performing
common operations. Some of these methods include
● Math.abs() (returns the absolute value of a number),
● Math.round() (rounds a number to the nearest integer),
● Math.floor() (returns the largest integer less than or equal to a given number),
● Math.ceil() (returns the smallest integer greater than or equal to a given
number),
● Math.min() (returns the smallest of zero or more numbers),
● Math.max() (returns the largest of zero or more numbers),
● Math.random() (returns a pseudo-random number between 0 and 1),
● Math.pow() (returns the base to the exponent power),
● Math.sqrt() (returns the square root of a number),
● Math.sin() (returns the sine of a number),
● Math.cos() (returns the cosine of a number),
● Math.tan() (returns the tangent of a number), and many more.
Thus, you refer to the constant pi as Math.PI and you call the sine function
as Math.sin(x), where x is the method's argument.
Syntax
var pi_val = Math.PI;
var sine_val = Math.sin(30);

Q6 Discuss in brief about string objects.


The String object lets you work with a series of characters; it wraps Javascript's
string primitive data type with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects,
you can call any of the helper methods of the String object on a string primitive.
Syntax
var val = new String(string);
The String parameter is a series of characters that has been properly encoded.

String Properties
Here is a list of the properties of String objects and their description.

Sr.No. Property & Description

constructor
Returns a reference to the String function that created the object.

length
Returns the length of the string.

prototype
The prototype property allows us to add properties and methods to an
object.

String Methods
Here is a list of the methods available in String objects along with their description.

Sr.No. Method & Description

charAt()
Returns the character at the specified index.

concat()
Combines the text of two strings and returns a new string.

indexOf()
Returns the index within the calling String object of the first occurrence
of the specified value, or -1 if not found.

lastIndexOf()
Returns the index within the calling String object of the last occurrence
of the specified value, or -1 if not found.

match()
Used to match a regular expression against a string.

replace()
Used to find a match between a regular expression and a string, and to
replace the matched substring with a new substring.

search()
Executes the search for a match between a regular expression and a
specified string.

split()
Splits a String object into an array of strings by separating the string
into substrings.

substr()
Returns the characters in a string beginning at the specified location
through the specified number of characters.

toLowerCase()
Returns the calling string value converted to lower case.

toUpperCase()
Returns the calling string value converted to uppercase.

Q7 . List various Date and Math Objects.


The Date object is a datatype built into the JavaScript language. Date objects are
created with the new Date( ). Once a Date object is created, a number of methods
allow you to get and set the year, month, day, hour, minute, second, and millisecond
fields of the object, using either local time or UTC (universal, or GMT) time.
Syntax
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

Date Properties
Here is a list of the properties of the Date object along with their description.

Sr.No. Property & Description

constructor
Specifies the function that creates an object's prototype.

prototype
The prototype property allows you to add properties and methods
to an object

length The length property returns the number of arguments expected by


the Date object constructor.

constructo The constructor property returns a reference to the constructor


r function that created the date object.

Date Methods
Here is a list of the methods used with Date and their description.

Sr.No. Method & Description

Date()
Returns today's date and time

getDate()
Returns the day of the month for the specified date according to
local time.
getDay()
Returns the day of the week for the specified date according to
local time.

getFullYear()
Returns the year of the specified date according to local time.

getHours()
Returns the hour in the specified date according to local time.

getMilliseconds()
Returns the milliseconds in the specified date according to local
time.

getMinutes()
Returns the minutes in the specified date according to local
time.

getMonth()
Returns the month in the specified date according to local time.

getSeconds()
Returns the seconds in the specified date according to local
time.

getTime()
Returns the numeric value of the specified date as the number
of milliseconds since January 1, 1970, 00:00:00 UTC.

getYear()
Deprecated - Returns the year in the specified date according to
local time. Use getFullYear instead.

setDate()
Sets the day of the month for a specified date according to
local time.

THE MATH OBJECT


The math object provides properties and methods for mathematical constants and
functions. Unlike other global objects, Math is not a constructor. All the properties
and methods of Math are static and can be called by using Math as an object
without creating it.
Syntax
var pi_val = Math.PI;
var sine_val = Math.sin(30);
Math Properties
Here is a list of all the properties of Math and their description.

Sr.No. Property & Description

LN10
Natural logarithm of 10, approximately 2.302.

LOG10E
Base 10 logarithm of E, approximately 0.434.

PI
Ratio of the circumference of a circle to its diameter, approximately 3.14159.

SQRT2
Square root of 2, approximately 1.414.

Math Methods
Here is a list of the methods associated with Math object and their description

Sr.No. Method & Description

abs()
Returns the absolute value of a number.

ceil()
Returns the smallest integer greater than or equal to a number.

cos()
Returns the cosine of a number.

exp()
Returns EN, where N is the argument, and E is Euler's constant, the
base of the natural logarithm.

floor()
Returns the largest integer less than or equal to a number.

log()
Returns the natural logarithm (base E) of a number.

max()
Returns the largest of zero or more numbers.
min()
Returns the smallest of zero or more numbers.

pow()
Returns base to the exponent power, that is, base exponent.

random()
Returns a pseudo-random number between 0 and 1.

round()
Returns the value of a number rounded to the nearest integer.

sin()
Returns the sine of a number.

sqrt()
Returns the square root of a number.

tan()
Returns the tangent of a number.

Q8. What is a statement? Explain the various types of


statements in java Script?
Ans: Write about both Conditional and Looping statements

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy