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

Javascript_class12

JavaScript is a lightweight, object-oriented scripting language primarily used for enhancing web pages and applications. It can run on both client-side (in web browsers) and server-side, allowing for dynamic content and user interaction. Key features include support for various data types, operators, control structures, and built-in objects, as well as the ability to define user-defined functions for reusable code.

Uploaded by

s9ck4rymsm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Javascript_class12

JavaScript is a lightweight, object-oriented scripting language primarily used for enhancing web pages and applications. It can run on both client-side (in web browsers) and server-side, allowing for dynamic content and user interaction. Key features include support for various data types, operators, control structures, and built-in objects, as well as the ability to define user-defined functions for reusable code.

Uploaded by

s9ck4rymsm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Web Scripting JavaScript

Q 1 What is javaScript ?
Ans:
1. JavaScript is a cross-platform, object-oriented scripting language.
2. JavaScript is a small, lightweight language. It is not useful as a standalone language, but is
designed for easy embedding in other products and applications, such as web browsers.
3. Inside a host environment, JavaScript can be connected to the objects of its environment to
provide programmatic control over them.

Q.2 What is Difference between client side java script and server side java script?
Ans:
Client-side JavaScript is a type of programming that runs inside your web browser (like
Chrome or Firefox) to make web pages interactive and fun. It works right on your computer
without needing to ask a server for help every time something happens.
For example, client-side extensions allow an application to place elements on an HTML form
and respond to user events such as mouse clicks, form input, and page navigation.

Server-side JavaScript extends the core language by supplying objects relevant to running
JavaScript on a server.

Q.3 What are the uses of Java Script?


Ans:
1. Developing Multimedia Applications: The users can use JavaScript to add multimedia
elements. With JavaScript you can show, hide, change, resize images and create images roll
overs. You can create scrolling text across the status bar, thus making multimedia applications
more interactive.
2. Create Pages Dynamically Based on the user’s choice, the date or other external data,
JavaScript can produce pages that are customized to the user.
3. Interact with the User JavaScript can do some processing of forms and can validate user
input when the user submits the form.

Q.4. Explain the features of JavaScript?


Ans:
Browser Support: All browsers have accepted JavaScript as a scripting language and provide
integrated support for it. For example, to access flash content, you need to install flash plug-in in
your browser. But to use JavaScript, you don't have to use any plug-in at all.
JavaScript can be used on Client Side as well as on Server Side: JavaScript has access to
Document Object Model DOM of the browser. You can change the structure of web pages at
runtime. Thus, JavaScript can be used to add different effects to WebPages. On the other hand,
JavaScript could be used on the server side as well.
Functional Programming Language: In JavaScript, function could be assigned to variables
just like any other data types. A function can accept another function as a parameter and can
also return a function. You can have functions with no name as well. This provides you the
ability to code in functional programming style.
Support for Objects: JavaScript is an object oriented language. However, the way JavaScript
handles objects and inheritance is bit different from conventional object oriented programming
languages like C++/ Java.
Run-time Environment: JavaScript typically relies on a run-time environment (e.g. in a web
browser) to provide objects and methods by which scripts can interact with "the outside world".
Vendor-specific Extensions: JavaScript is officially managed by Mozilla Foundation, and new
language features are added periodically. However, only some JavaScript engines support
these new features.
Object based Features Supported by JavaScript: JavaScript supports various features
related to object based language and JavaScript is sometimes referred to as an object-based
programming language

Q.5 What is script tag?


Ans: The <script> tag alerts a browser that JavaScript code follows. It is typically embedded in
the HTML.
<script language=”javaScript”>
Statements....
</script>

Example:
<script language="text/javascript">
document.write("<h1>Main Title</h1>");
document.write("<p align='right'>Body</p>");
</script>

Q.6. What are variables? How is it declared?


Variables are used to store data that can be referenced and manipulated in a program. A
variable acts as a container or storage location for values like numbers, strings, objects, or
arrays. Once a value is stored in a variable, you can use it throughout your code.
Variables in JavaScript can be defined using the var keyword:

var x; //defines the variable x, although no value is assigned to it by default


var y = 2; //defines the variable y and assigns the value of 2 to it

Q.7. How to Save and Run your Program in JavaScript?


Ans:
1. Open any editor like notepad and write the program
2. Save the program in a file with .html extension in a proper folder or subfolder on a drive.
3. Open the saved file using any of the web browser like internet explorer or Mozilla Firefox

Q.8. Explain Operators in javaScript?


Ans: JavaScript operators can be used to perform various operations such as:
Arithmetic Operators
Comparison Operators/Relational Operators
Logical Operators
Assignment Operators
Conditional Operators
Arithmetic Operators
The arithmetic operators are used to perform common arithmetical operations, such as:

Example:
<html>
<head>
<title>JavaScript Arithmetic Operators</title>
</head>
<body>
<script language="JavaScript">
var x = 10;
var y = 4;
document.write("Addition=",x + y);
document.write("<br>");
document.write("Subtraction=",x - y);
document.write("<br>");
document.write("Multiplication=",x * y);
document.write("<br>");
document.write("Division=",x / y);
document.write("<br>");
document.write("Remainder=",x % y);
</script>
</body>
</html>
Example:

<html>
<head>
<title>JavaScript Comparison Operators</title>
</head> <body>
<script language="JavaScript">
var x = 25;
var y = 35;
var z = "25";
document.write(x == z);
document.write("<br>");
document.write(x === z);
document.write("<br>");
document.write(x != y);
document.write("<br>");
document.write(x !== z);
document.write("<br>");
document.write(x < y);
document.write("<br>");
document.write(x > y);
document.write("<br>");
document.write(x <= y);
document.write("<br>");
document.write(x >= y);
</script>
</body>
</html>
Example:
<html>
<head>
<title>JavaScript Logical Operators</title>
</head>
<body>
<script language="JavaScript">
var year = 2018;
if((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0)))
{
document.write(year + " is a leap year.");
}
else
{
document.write(year + " is not a leap year.");
}
</script>
</body>
</html>
Example:
<html >
<head>
<title>JavaScript Assignment Operators</title>
</head>
<body>
<script language="JavaScript">
var x; // Declaring Variable
x = 10;
document.write(x + "<br>");
x = 20;
x += 30;
document.write(x + "<br>");
x = 50;
x -= 20;
document.write(x + "<br>");
x = 5;
x *= 25;
document.write(x + "<br>");
x = 50;
x /= 10;
document.write(x + "<br>");
x = 100;
x %= 15;
document.write(x);
</script>
</body>
</html>

Example:
var age=20;
var allowed = (age > 18) ? "yes" : "no";
Q.9. What are Data Types in JavaScript?
Ans:
A data type is a classification of the type of data that a variable or object can hold. Data type is
an important factor in virtually all computer programming languages, including visual basic, C#,
C/C++ and JavaScript.
Different data types are Numbers, String, Boolean, undefined

Q.10. Give the syntax of number data type.


Syntax: var num=value
Example: var n=100

Q.11. Explain parseInt() of Number datatype in javascript?


We can convert a string to an integer using the built-in parseInt() function. This takes the base
for the conversion as an optional second argument, which you should always provide:
i. parseInt("123", 10)
123
ii. parseInt("010", 10)
10
iii. parseInt("010")
8 //It happens because the parseInt() function decided to treat the string as octal due to the
leading 0.
iv. If you want to convert a binary number to an integer, just change the base:
parseInt("11", 2)
3
v. A special value called NaN (short for "Not a Number") is returned if the string is nonnumeric:
parseInt("hello", 10)
NaN

Q.12. Explain undefined data type in Javascript.


In JavaScript it is possible to declare a variable without assigning a value to it. If we do this, the
variable's type is undefined.
EXample: var a;

Q.13. Explain boolean data type in Javascript.


JavaScript has a boolean type, with possible values true and false (both of which are keywords).
Any given value can be converted to a boolean according to the following rules:
1) false, 0, the empty string (" "), NaN, null, and undefined all become false
2) all other values become true

Example:
boolean(" ")
false

boolean(234)
true

Q.14. Explain Control Structures.


JavaScript has a similar set of control structures similar to other languages like C\C++ and
Java. Conditional statements are supported by if and else,

Example:
var name = "kittens";
if (name == "puppies")
{
name += "!";
}
else if
(name == "kittens")
{
name += "!!";
}
else
{
name = "!" + name;
}

Q.15. Explain for loop in Java Script.


JavaScript's for loop is the same as that in C\C++ and Java which provides the control
information for the loop on a single line.

for (var i = 0; i < 5; i++)


{
document. write(“Hello”)
// this loop will execute 5 times
}

Q.16. Give the difference between while loop and do-while loop in Javascript.
JavaScript has while loops and do-while loops. While loop is good for basic looping. It is called
as entry controlled loop. The do-while loop is used to ensure that the body of the loop is
executed at least once. It is called as exit controlled loop.

Example of while loop:


var a=10;
while (a<5)
{
document.write(“Hello”);
a++;
}
document.write(“Chinmaya”);

Example of do-while loop:


var a=100;
do
{
document.write(“Hello”);
} while (a==99)

Q.17. Explain switch statement with example.


The switch statement in JavaScript is used to execute one out of multiple blocks of code
based on the value of an expression. It is an alternative to multiple if...else if conditions
when you need to check for many possible values of a single variable.
<html>
<head>
<title>Simple Switch Example</title>
</head>
<body>
<script>
var number = prompt("Enter a number:");

switch(+number) {
case 1:
alert("Number is One!");
break;
case 2:
alert("Number is Two!");
break;
case 3:
alert("Number is Three!");
break;
default:
alert("Number is not 1, 2, or 3!");
}
</script>
</body>
</html>

Q.18. What is Function?


Ans: A function is a group of statements that perform specific tasks and can be kept and
maintained separately from the main program. Functions provide a way to create reusable code
packages which are more portable and easier to debug.

Here are some advantages of using functions:


Functions reduces the repetition of code within a program — Function allows you to extract
commonly used block of code into a single component. Now you can perform the same task by
calling this function wherever you want within your script without having to copy and paste the
same block of code again and again.

Functions makes the code much easier to maintain — Since a function created once can be
used many times, so any changes made inside a function automatically implemented at all the
places without touching the several files.
Functions makes it easier to eliminate the errors — When the program is subdivided into
functions, if any error occurs you know exactly what function causing the error and where to find
it. Therefore, fixing errors becomes much easier.
Example:

<html>
<head>
<title>JavaScript Define and Call a Function</title>
</head>
<body>
<script>
// Defining function
function Hello()
{
document.write("Hello, welcome to this website!");
}
// Calling function
Hello(); // Prints: Hello, welcome to this website!
</script>
</body>
</html>

19. What are Predefined functions?


A function is a block of code that will be executed when someone calls it. With functions, you
can give a name to a whole block of code, allowing you to reference it from anywhere in your
program. JavaScript has built-in functions for several predefined operations.
alert("message")
confirm("message")
prompt("message”)

//Program to show the alertbox.


<html>
<head>
<script>
function myFunction()
{
alert("HELLO!");
}
</script>
</head>
<body>
<input type="button" onclick="myFunction()" value="show me the alert box"/>
</body>
</html>

//Program to show the confirm box.


<html>
<head>
<p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var r=confirm("press a button");
if(r==true)
{
x="you pressed OK";
}
else
{
x="you pressed cancel";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>

//Program to show the prompt box.


<html>
<body>
<p><strong>Click the button to demonstrate the prompt box.</strong></p>
<button onclick="myFunction()">try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var person;
person=prompt("please enter your name"," ");
if(person!=null)
{
x=("hello" +person+ "!how are u today?");
}
document.getElementById("demo").innerHTML=x; }

Q.20. What are user defined functions?


A user-defined function in JavaScript is a function that is created by the programmer (the
user) to perform a specific task. Above function myFunction() is an example for user defined
function.

Q.21. What are Built-In Objects in javascript?


Some of the built-in language objects of JavaScript offer more advanced operations such as:
String object – provides for string manipulation
Math object - provides for maths calculations
Array object - provides the collection of similar data types.

Q.22. What are String Objects? Explain the methods used in String function.
Strings in JavaScript are sequences of characters.
Syntax: var name=”Student_name”

The String object provides methods and properties for string manipulation and formatting.
Syntax: stringName.method()

i. To find the length of a string, access its length property:


"hello".length
5 //length of given string “hello”

ii. The strings are represented using objects and they have methods as well:
"hello, world".replace("hello", "goodbye") //by using replace() method
goodbye, world

iii. "hello".toUpperCase() //by using toUpperCase() method


HELLO

//Program to find the length of the array


<html>
<body>
<p>Length of the given string =
<script> var txt="Hello world";
document.write(txt.length);
</script>
</p>
</body>
</html>

//Program to find the position of the first occurrence of a text in a string using indexOf()
<html>
<body>
<p id="demo"><strong>click the button to locate where in the string a specified value
occurs.</strong></p>
<button onclick="myFunction()">try it</button>
<script>
function myFunction()
{
var str="hello! welcome to my world";
var n=str.indexOf("world");
document.getElementById("demo").innerHTML=n;
}
</script>
</body>
</html>

//Program to search for a text in a string and return the text if found using match()
<html>
<body>
<script>
var str="Honesty is the best policy";
document.write(str.match("policy")+"<br>");
document.write(str.match("Police")+"<br>");
document.write(str.match("pollicy")+"<br>");
document.write(str.match("policy")+"<br>");
</script>
</body>
</html>

Output:
Policy
Null
Null
Policy

//Program to replace characters in a string using replace()


<html>
<body>
<p>click the button to replace the characters</p>
<p id="demo">hello prachi</p>
<button onclick="myFunction()">try it</button>
<script>
function myFunction()
{
var str=document.getElementById("demo").innerHTML;
var n=str.replace("hello","good morning");
document.getElementById("demo").innerHTML=n;
}
</script>
</body>
</html>

Q.23. Explain Math Object.


The Math object provides methods for many mathematical calculations like abs(), log(), pow(),
random(), round(), sqrt() etc.
Syntax: Math.method(#)

round() method: The round() method returns a number to the nearest integer.
Syntax: Math.round()
//Program to round off any number using round()
<html>
<body>
<p id="demo">click the button to round the no.to its nearest integer.</p>
<button onclick="myFunction()">try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML=Math.round(8.7896);
}
</script>
</body>
</html>

random(): The random() method returns a random number from 0(inclusive) up to but not
including 1(exclusive).
Syntax: Math.random()

//Program to return a value random number between 0 and 1 using random()


<html>
<body>
<p id="demo">click the button to display a number</p>
<button onclick="myFunction()">try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML=Math.random();
}
</script>
</body>
</html>

max(): The max() method returns the number with the highest value.
Syntax: Math.max(n1,n2,n3……..nx)

//Program to return the number with highest value of two specified numbers using max()
<html>
<body>
<p id="demo">Click the button to return the highest no. between 5 and 10.</p>
<button onclick="myFunction()">try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML=Math.max(5,10);
}
</script>
</body>
</html>

min() The min() method returns the number with the lowest value.
Syntax: Math.min(n1,n2,n3……….nx)

//Program to return the number with the lowest value of two specified number using min().
<html>
<body>
<p id="demo">Click the button to return the lowest no. between 77 and 9.</p>
<button onclick="myFunction()">try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML=Math.min(77,9);
}
</script>
</body>
</html>

Q.24. Explain Array object.


Arrays in JavaScript are actually a special type of object. They work similar to regular objects
but they have one magic property called 'length'. The length of the array (size of the array) is
always one more than the highest index in the array.

<html>
<head>
<title>Creating Arrays in JavaScript</title>
</head>
<body>
<script>
// Creating variables
var colors = ["Red", "Green", "Blue"];
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var cities = ["London", "Paris", "New York"];
var person = ["John", "Wick", 32];

// Printing variable values


document.write(colors + "<br>");
document.write(fruits + "<br>");
document.write(cities + "<br>");
document.write(person + “<br>”);
document. write(colors.length);
</script>
</body>
</html>
Example 2:
var a = new Array();
a[0] = "dog";
a[1] = "cat";
a[2] = "hen";
document.write(a.length)

Output: 3

Example 3:
var a = ["dog", "cat", "hen"];
a[100] = "fox";
document.write(a.length);
document.write(typeof a[90]);

Output:
101
Undefined

The array object is used to store multiple values in a single variable.

//Program to create an array.


<html>
<body>
<script>
var i;
var fruits=new Array();
fruits[0]="apple";
fruits[1]="banana";
fruits[2]="orange";
for(i=0;i<fruits.length;i++)
{
document.write(fruits[i]+"<br>");
}
</script>
</body>
</html>

//Program to join two arrays using concat().


<html>
<body>
<p id="demo">Click the button to join three arrays</p>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction()
{
var fruits=["Apple","Orange"];
var vegetables=["Cucumber","Carrot","Raddish"];
var grains=["Wheat","Maize"];
var mix=fruits.concat(vegetables,grains);
var x=document.getElementById("demo");
x.innerHTML=mix;
}
</script>
</body>
</html>

//Program to remove the last element from the array by using pop()
<html>
<body>
<p id="demo">Click the button to remove the last array element.</p>
<button onclick="myFunction()">Click me</button>
<script>
var name=["John","Mary","Oliver","Alice"];
function myFunction()
{
name.pop();
var x=document.getElementById("demo");
x.innerHTML=name;
}
</script>
</body>
</html>

//Program to add a new element to the array using push().


<html>
<body>
<p id="demo">Click the button to add a new element to the array.</p>
<button onclick="myFunction()">Click me</button>
<script>
var name=["Alice","Henry","John","Leo"];
function myFunction()
{
name.push("Aayush");
var x=document.getElementById("demo");
x.innerHTML=name;
}
</script>
</body>
</html>

//Program to reverse the order of the elements in the array.


<html>
<body>
<p id="demo">Click the button to reverse the order of the element in the array.</p>
<button onclick="myFunction()">Click me</button>
<script>
var alphabet=["z","k","j","h","e"];
function myFunction()
{
alphabet.reverse();
var x=document.getElementById("demo");
x.innerHTML=alphabet;
}
</script>
</body>
</html>

//Program to sort the array.


<html>
<body>
<p id="demo">Click the button to sort the array</p>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction()
{
var fruits=["Banana","Orange","Apple","Mango"];
fruits.sort();
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
</script>
</body>
</html>

Q.25. List out different methods of arrays and strings


Q.25. What are events in javaScript? Explain?
Ans: An event is something that happens when user interact with the web page, such as when
he clicked a link or button, entered text into an input box or textarea, made selection in a select
box, pressed key on the keyboard, moved the mouse pointer, submits a form, etc. In some
cases, the Browser itself can trigger the events, such as the page load and unload events.

Below are some of the most commonly used events:


onLoad - occurs when a page loads in a browser
onUnload - occurs just before the user exits a page
onMouseOver - occurs when you point to an object
onMouseOut - occurs when you point away from an object
onSubmit - occurs when you submit a form
onClick - occurs when an object is clicked

Execution of javascript immediately after a page has been loaded.


<html>
<head>
<script>
function myFunction()
{
confirm("Welcome to the loaded browser");
}
</script>
</head>
<body onload="myFunction()">
<h1>Event handling!</h1>
</body>
</html>

Execute a javascript when a button is clicked.


<html>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="Hello World";
}
</script>
</head>
<body>
<p>Click the button</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>

Additional Programs:
<html>
<head>
<title>JavaScript Code</title>
</head>
<body>
<h1>Age Checker</h1>
<p>Enter your age:</p>
<input type="number" id="ageInput" placeholder="Enter your age" />
<button onclick="checkAge()">Check</button>
<script>
function checkAge()
{
const age = document.getElementById("ageInput").value;
// Conditional statements
if (age < 18) {
document.write("You are a minor.");
} else if (age >= 18 && age < 65) {
document.write("You are an adult.");
} else if (age >= 65) {
document.write("You are a senior citizen.");
} else {
document.write("Please enter a valid age.");
}
}
</script>
</body>
</html>

You might also like