Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

UNIT III

JAVASCRIPT
---------------------------------------------
2 MARKS QUESTIONS AND ANSWERS

1. List the primitive types in JavaScript.


Answer: string, number, boolean, null, undefined,

2. List the advantages of javascript.


o Dynamic drop-down menus
o Client-side validation
o Displaying date and time
o Validate user input in an HTML form before sending the data to a server.
o Open and close new windows or frames.
o Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box and
prompt dialog box)

3. What is JavaScript?
JavaScript is a client-side as well as server side scripting language that can be inserted into
HTML pages and is understood by web browsers. JavaScript is also an Object based
Programming language.

4. Which company developed JavaScript?

Netscape is the software company who developed JavaScript.

5. What are undeclared and undefined variables?

Undeclared variables are those that do not exist in a program and are not declared. If the
program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any
value. If the program tries to read the value of an undefined variable, an undefined value is
returned.

6. What is a prompt box?

A prompt box is a box which allows the user to enter input by providing a text box. Label
and box will be provided to enter the text or number.

7. Which symbol is used for comments in Javascript?

// for Single line comments and


/* Multi
Line
Comment
*/

8. Does JavaScript support automatic type conversion?

Yes JavaScript does support automatic type conversion, it is the common way of type
conversion used by JavaScript developers

9. What are all the looping structures in JavaScript?

Following are looping structures in Javascript:

 For
 While
 do-while loops
UNIT III
JAVASCRIPT
---------------------------------------------
10. What would be the result of 3+2+"7"?

Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its
concatenation will be done. So the result would be 57.

11. What is an undefined value in JavaScript?

Undefined value means the

 Variable used in the code doesn't exist


 Variable is not assigned to any value
 Property doesn't exist

12. What are all the types of Pop up boxes available in JavaScript?

 Alert
 Confirm and
 Prompt

13. Which keyword is used to print the text in the screen?

document.write("Welcome") is used to print the text – Welcome in the screen.

14. What are the different types of errors in JavaScript?

There are three types of errors:

 Load time errors: Errors which come up when loading a web page like improper syntax
errors are known as Load time errors and it generates the errors dynamically.
 Run time errors: Errors that come due to misuse of the command inside the HTML
language.
 Logical Errors: These are the errors that occur due to the bad logic performed on a function
which is having different operation.

15. Explain the for-in loop?

The for-in loop is used to loop through the properties of an object.


The syntax for the for-in loop is -
for (variable name in object)
{
statement or block to execute
}
In each repetition, one property from the object is associated to the variable name, and the
loop is continued till all the properties of the object are depleted.

16. Define control statement in javascript.

A compound statement in JavaScript is a sequence of statements delimited by braces. A


control construct is a control statement together with the statement or compound statement
whose execution it controls.

17. How many ways to create the array in javascript.


There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
UNIT III
JAVASCRIPT
---------------------------------------------
18. List the javascript array methods.
Concat(), join(), isArray(), pop(), push() and etc.

19. Define javascript fuction.


A function is a set of statements that take inputs, do some specific computation and produces
output. Basically, a function is a set of statements that performs some tasks or does some
computation and then returns the result to the user.

20. List the advantages of javascript functions.


1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines of
code each time to perform a common task.

21. Define constructor in javascript.


 A JavaScript constructor method is a special type of method which is used to initialize and
create an object. It is called when memory is allocated for an object.
 JavaScript constructors are special methods that create and initialize the properties of newly
created objects.

22. What is regular expression.?


A regular expression is a sequence of characters that forms a search pattern.
Regular Expressions, commonly known as "regex" or "RegExp", are a specially
formatted text strings used to find patterns in text.
A regular expression is a sequence of characters that forms a search pattern.
UNIT III
JAVASCRIPT
---------------------------------------------

Five marks questions and answers.


1. Write differences between Java and JavaScript.
UNIT III
JAVASCRIPT
---------------------------------------------
2. What are the five primitive data types in JavaScript and explain.

JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type

JavaScript is a dynamic type language, means we don't need to specify type of the variable
because it is dynamically used by JavaScript engine. You need to use var here to specify the
data type. It can hold any type of values such as numbers, strings etc. For example:
1. var a=40;//holding number
2. var b="Rahul";//holding string

JavaScript primitive data types

There are five types of primitive data types in JavaScript. They are as follows:
Data Description
Type

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

Number:
A number data type can be an integer, a floating point value, an exponential value, a
‘NaN’ or a ‘Infinity’.
1 var a=250; // integer value
2 var b=25.5; // a number containing a decimal
3 var c = 10e4 // an exponential value which evaluates to 10*10000;

String:

The string data type in JavaScript can be any group of characters enclosed by a single or
double-quotes or by backticks.

1 var str1 = “This is a string1”;


2 var str2= ‘This is a string2’;
3 var str3 = `This is a string3`;

Boolean:

The boolean data type has only two values, true and false. It is mostly used to check a logical
condition. Thus Booleans are logical data types which can be used for comparison of two
variables or to check a condition. The true and false implies a ‘yes’ for ‘true’ and a ‘no’ for
‘false in some places when we check a condition or the existence of a variable or a value.

When we check the data type of ‘true’ or ‘false’ using typeof operator, it returns a boolean.
1 typeof(true) // returns boolean
2 typeof(false) // returns Boolean
example of comparison statement:
1 var a =5;
2 var b=6;
UNIT III
JAVASCRIPT
---------------------------------------------
3 a==b // returns false

3. Explain the syntax of JavaScript.

 JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
 We can place the <script> tags, containing your JavaScript, anywhere within your web
page, but it is normally recommended that you should keep it within the <head> tags.
 The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.
 <script ...>
 JavaScript code
 </script>
The script tag takes two important attributes −
 Language − This attribute specifies what scripting language you are using. Typically, its
value will be javascript. Although recent versions of HTML (and XHTML, its successor)
have phased out the use of this attribute.
 Type − This attribute is what is now recommended to indicate the scripting language in
use and its value should be set to "text/javascript".
So our JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>

Example

Let us take a sample example to print out "Hello World". We added an optional HTML
comment that surrounds our JavaScript code. This is to save our code from a browser that does
not support JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in
JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as
a piece of JavaScript code. Next, we call a function document.write which writes a string into
our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
This code will produce the following result −
Hello World!
UNIT III
JAVASCRIPT
---------------------------------------------
4. Explain all types of Pop up boxes available in JavaScript?

There are 3 types of pop-up boxes:


1. Alert
2. Confirm
3. Prompt

1. alert Box:
The alert method opens a dialog window and displays its parameter in that window.
It also displays an OK button.
The string parameter of alert is not XHTML code; it is plain text. Therefore, the string
parameter of alert may include \n but never should include <br />.

alert(“The sum is:” + sum + “\n”);

2. confirm Box
The confirm method opens a dialog window in which the method displays its string parameter,
along with two buttons: OK and Cancel.
confirm returns a Boolean value that indicates the user’s button input: true for OK and
false for Cancel. This method is often used to offer the user the choice of continuing some
process.
var question = confirm(“Do you want to continue this download?”);

After the user presses one of the buttons in the confirm dialog window, the script can test
the variable, question, and react accordingly.

3. prompt Box:

The prompt method creates a dialog window that contains a text box used to collect a string of
input from the user, which prompt returns as its value.
UNIT III
JAVASCRIPT
---------------------------------------------
5. What is an array in javascript? And explain its types to create an arrays.
 An array is a special variable, which can hold more than one value at a time.
 JavaScript arrays are used to store multiple values in a single variable

There are 3 ways to construct array in JavaScript


1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1) JavaScript array literal


UNIT III
JAVASCRIPT
---------------------------------------------
6. Write JavaScript program to sort the array

7. Explain the types of errors in JavaScript.


An error is an action which is inaccurate or incorrect. There are three types of error in
programming which are discusses below :
 Syntax error
 Logical error
 Runtime error
Syntax error: According to computer science, a syntax error is an error in the syntax of a
sequence of characters or tokens that is intended to be written in a particular programming
language or it is also the compile-time error if the syntax is not correct then it will give an error
message.
Example:
<script type="text/javascript">
// Here the semicolon after the printing statement
// is missing and it is a syntax error
window.print( )
</script>

As the syntax is not correct of the JavaScript it will affect only the thread that is under this
JavaScript and the rest of the code in other threads gets executed as nothing in them depends on
the code containing the error.
Logical error: It is the most difficult error to be traced as it is the error on the logical part of the
coding or logical error is a bug in a program that causes it to operate incorrectly and terminate
abnormally (or crash).

Runtime Error: A runtime error is an error that occurs during the running of the program, also
known as the exceptions. In the example that is given below the syntax is correct, but at runtime,
it is trying to call a method that does not exist.
Example:
<script type="text/javascript">
// An runtime error here
window.printme();
</script>
As in runtime error, there are exceptions and this exception is correct by the help of the
try and catch method
UNIT III
JAVASCRIPT
---------------------------------------------
Ten Marks Questions and answers
1. Explain functions JavaScript in detail with an example.
Defn :

A function is a set of statements that take inputs, do some specific computation and
produces output. Basically, a function is a set of statements that performs some tasks or does
some computation and then returns the result to the user.

JavaScript functions are used to perform operations. We can call JavaScript function
many times to reuse the code.

Advantage of JavaScript function


There are mainly two advantages of JavaScript functions.

 Code reusability: We can call a function several times so it save coding.


 Less coding: It makes our program compact. We don’t need to write many lines of code
each time to perform a common task.

How to Create a Function in JavaScript


 Use the keyword function followed by the name of the function.
 After the function name, open and close parentheses.
 After parenthesis, open and close curly braces.
 Within curly braces, write your lines of code.

JavaScript Function Syntax:


The syntax of declaring function is given below.
function functionName(Parameter1, Parameter2, ..)
{
// Function body
}
To create a function in JavaScript, we have to first use the keyword function, separated
by name of function and parameters within parenthesis. The part of function inside the curly
braces {}is the body of the function.

Function Definition
Before, using a user-defined function in JavaScript we have to create one. We can use the
above syntax to create a function in JavaScript. Function definition is sometimes also termed as
function declaration or function statement.
Below are the rules for creating a function in JavaScript:
 Every function should begin with the keyword function followed by,
 A user defined function name which should be unique,
 A list of parameters enclosed within parenthesis and separated by commas,
 A list of statement composing the body of the function enclosed within curly braces { }.
Example:
function calcAddition(number1, number2)
{
return number1 + number2;
}
In the above example, we have created a function named calcAddition, this function
accepts two numbers as parameters and returns the addition of these two numbers

Function Parameters
 Parameters are additional information passed to a function. For example, in the above
example, the task of the function calcAddition is to calculate addition of two numbers. These
two numbers on which we want to perform the addition operation are passed to this function
as parameters.
UNIT III
JAVASCRIPT
---------------------------------------------
 The parameters are passed to the function within parentheses after the function name and
separated by commas. A function in JavaScript can have any number of parameters and also
at the same time a function in JavaScript cannot have a single parameter.

Calling Functions:
After defining a function, the next step is to call them to make use of the function. We can call a
function by using the function name separated by the value of parameters enclosed between
parenthesis and a semicolon at the end. Below syntax shows how to call functions in JavaScript:

functionName( Value1, Value2, ..);

Below is a sample program that illustrate working of functions in JavaScript:

<script type = "text/javascript"> OUTPUT:


// Function definition Hello Admin welcome to Javascript
function welcomeMsg(name) Functions…
{
document.write("Hello "+ name + "
welcome to Javascript Functions…");
}
// creating a variable
Var nameVal = "Admin";

// calling the function


welcomeMsg(nameVal);
</script>
UNIT III
JAVASCRIPT
---------------------------------------------
2. Explain the pattern matching in JavaScript.
What Is a Regular Expression?
 A regular expression is a sequence of characters that forms a search pattern.
 When you search for data in a text, you can use this search pattern to describe what you
are searching for.
 A regular expression can be a single character, or a more complicated pattern.
 Regular expressions can be used to perform all types of text search and text
replace operations.

Syntax

/pattern/modifiers;

Example
var patt = /w3schools/i;

Example explained:
 /w3schools/i is a regular expression.
 w3schools is a pattern (to be used in a search).
 i is a modifier (modifies the search to be case-insensitive).

Using String Methods


In JavaScript, regular expressions are often used with the two string
methods: search() and replace().
The search() method uses an expression to search for a match, and returns the position of the
match.
The replace() method returns a modified string where the pattern is replaced.
UNIT III
JAVASCRIPT
---------------------------------------------

Anchors: string start ^ and end $


 The caret ^ and dollar $ characters have special meaning in a regexp. They are called
“anchors”.
 The caret ^ matches at the beginning of the text, and the dollar $ – at the end.
 For instance, let’s test if the text starts with Mary:
<!DOCTYPE html> OUTPUT:
<script>
str1 = "Mary had a little lamb"; true
alert( /^Mary/.test(str1) ); // true
</script>

Similar to this, we can test if the string ends with snow using snow$:

<!DOCTYPE html> OUTPUT:


<script>
str1 = "it's fleece was white as snow"; true
alert( /snow$/.test(str1) ); // true
</script>

PATTERN MODIFIERS
 The modifiers are specified as letters just after the right delimiter of the pattern.
 The i modifier makes the letters in the pattern match either uppercase or lowercase letters
in the string.
 For example, the pattern /Apple/i matches ‘APPLE’, ‘apple’, ‘APPle’, and any other
combination of uppercase and lowercase spellings of the word “apple.”
 The x modifier allows white space to appear in the pattern.

Regular Expression Modifiers :


Modifiers can be used to perform multiline searches:
Examples:
EXPRESSIONS DESCRIPTION
[abc] Find any of the character inside the brackets
[0-9] Find any of the digits between the brackets 0 to 9
(x | y) Find any of the alternatives between x or y separated with |

Regular Expression Patterns :


Metacharacters are characters with a special meaning:
UNIT III
JAVASCRIPT
---------------------------------------------
Examples:
METACHARACTER DESCRIPTION
\d Used to find a digit
\s Used to find a whitespace character
\b Used to find a match at beginning or at the end of a word

Quantifiers define quantities:


Examples:
QUANTIFIER DESCRIPTION
n+ Used to match any string that contains at least one n
Used to match any string that ccontains zero or more
n* occurrences of n
Used to matches any string that contains zero or one
n? occurrences of n

OTHER PATTERN-MATCHING METHODS OF String

 In JavaScript, regular expressions are often used with the two string.
methods: search() and replace().
 The search( ) method uses an expression to search for a match, and returns the position
of the match.
The replace( ) method returns a modified string where the pattern is replaced.
 Using String search() With a Regular Expression :
Use a regular expression to do a case-insensitive search for “WelcomeToBCA” in a
string:
UNIT III
JAVASCRIPT
---------------------------------------------
3. Explain Errors in JavaScript.
ERRORS IN SCRIPTS:
 The JavaScript interpreter is capable of detecting various errors in scripts.
 Debugging a script is a bit different from debugging a program in a more typical
programming language, mostly because errors that are detected by the JavaScript
interpreter are found while the browser is attempting to display a document.
 In some cases, a script error causes the browser not to display the document and does not
produce an error message.

Without a diagnostic message, you must simply examine the code to find the problem

Notice the syntax in the while statements. The browser display of what happens when an
attempt is made to debugdemo.js
Internet Explorer

Mozilla Firefox
UNIT III
JAVASCRIPT
---------------------------------------------
Some Important Programs for exams so read from
your journal

Lab 4)
Create a HTML form containing Textboxes to enter name of
student, roll number, course, and grade obtained. When
the form runs in the Browser fill the textboxes with
data. Write JavaScript code that verifies that all
textboxes has been filled. If a textboxes has been left
empty, popup an alert indicating which textbox has been
left empty.

Lab 5)
Develop and demonstrate a XHTML file that includes
JavaScript script for receiving a number n as input and
outputting first n Fibonacci numbers.

Lab 6)
Write a JavaScript code to compute the sum of n natural
numbers.

Lab 7)
Create a HTML form containing textbox to enter text.
Write a JavaScript code block, which checks the contents
entered in a form’s Text element. If the text entered is
in the lower case, convert to upper case. Make use of
function to Uppercase().

You might also like