Chapter 4: JavaScript Part 1 – Web Applications Class XI (CBSE 803)
Class 11 · Web Applications
Chapter 4: JavaScript Part 1
JavaScript is a scripting language widely used to add interactivity and dynamic behaviour to web pages. While HTML defines the structure of a webpage and CSS controls its presentation, JavaScript can be used to make a webpage respond to user actions, process information, perform calculations, validate data, and change webpage content.
In this chapter, we will learn the fundamentals of JavaScript, including variables, data types, operators, input and output, conditional statements, and loops.
4.1 Introduction to JavaScript
JavaScript is a high-level scripting language used primarily to add dynamic and interactive behaviour to web pages. JavaScript code can be embedded in an HTML document and executed by a web browser.
A webpage can use JavaScript to perform tasks such as:
- Displaying messages to users
- Accepting input from users
- Performing calculations
- Making decisions based on conditions
- Repeating a set of instructions
- Validating form data
- Changing webpage content dynamically
- Responding to user actions
HTML, CSS and JavaScript
The three technologies commonly work together when developing interactive webpages.
| Technology | Primary Purpose |
|---|---|
| HTML | Defines the structure and content of a webpage. |
| CSS | Controls the appearance and presentation of a webpage. |
| JavaScript | Adds logic, interactivity, and dynamic behaviour. |
4.1.1 History
JavaScript was developed at Netscape in the mid-1990s. It was originally created to provide scripting capabilities within web browsers.
The language was initially associated with the name LiveScript and was later renamed JavaScript. JavaScript became widely adopted as browser-based web development grew.
JavaScript is standardized through the ECMAScript specification. Modern browsers implement JavaScript according to ECMAScript standards while also providing browser-specific features.
JavaScript and Java are different programming languages. Despite the similarity in their names, they have different syntax, purposes, and language designs.
4.1.2 What is JavaScript and How Is It Interpreted?
JavaScript is a scripting language that can be embedded in an HTML document. When a browser loads a webpage containing JavaScript, the browser's JavaScript engine processes and executes the JavaScript instructions.
Modern JavaScript engines use sophisticated techniques, including interpretation and just-in-time compilation, to execute JavaScript efficiently.
Basic Execution Process
- The browser loads an HTML document.
- The browser encounters JavaScript code.
- The JavaScript engine processes the code.
- The instructions are executed.
- The webpage responds according to the JavaScript instructions.
For example, JavaScript can instruct the browser to display a message when a particular condition is satisfied.
<script>
alert("Welcome to JavaScript!");
</script>
4.1.3 Features and Advantages
Features of JavaScript
- It is a scripting language.
- It is commonly used for client-side web programming.
- It can be embedded in HTML documents.
- It supports variables and different data types.
- It provides operators for calculations and comparisons.
- It supports conditional statements.
- It supports loops for repetitive tasks.
- It can respond to user interaction.
- It supports functions for reusable code.
- It is supported by modern web browsers.
Advantages of JavaScript
- Interactivity: It can make webpages interactive.
- Client-side execution: Many operations can be performed in the user's browser.
- Speed: Simple operations can be performed without sending every request to a server.
- Ease of integration: JavaScript works naturally with HTML and CSS.
- Versatility: It can be used for a wide variety of web development tasks.
- Browser support: JavaScript is supported by modern web browsers.
4.2 Prerequisites for Working in JavaScript
Before learning JavaScript, a student should have a basic understanding of HTML and CSS because JavaScript is commonly used along with them to create interactive webpages.
Basic Requirements
- A computer or other suitable computing device
- A modern web browser
- A text editor or code editor
- Basic knowledge of HTML
- Basic understanding of CSS
- Basic programming concepts such as variables and conditions
Simple Development Process
- Create an HTML file.
- Add JavaScript using the appropriate script syntax.
- Save the file with the
.htmlextension. - Open the file in a web browser.
- Observe the output.
- Use the browser's developer tools to identify errors when required.
4.3 Introduction to Script Tag
JavaScript code can be included in an HTML document using the <script> element.
A simple JavaScript block can be written as:
<script>
document.write("Hello World");
</script>
The JavaScript code is placed between the opening
<script> tag and the closing
</script> tag.
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script>
document.write("Welcome to JavaScript");
</script>
</body>
</html>
4.3.1 Rules
The following rules and good practices should be followed while writing basic JavaScript programs:
-
JavaScript statements should be written inside a
<script>element when embedded in HTML. - JavaScript is case-sensitive.
- Variable names should follow JavaScript naming rules.
- Keywords should not be used as variable names.
- Strings should be enclosed in quotation marks.
- Statements may be terminated with a semicolon.
- Proper brackets and quotation marks should be used.
- Meaningful variable names should be preferred.
JavaScript is Case-Sensitive
JavaScript distinguishes between uppercase and lowercase letters. Therefore, the following identifiers are different:
total
Total
TOTAL
A variable created as total cannot be referred to as
Total unless that is a separately declared identifier.
Valid Variable Names
Variable names may contain letters, digits, underscore
(_), and dollar sign ($), but they cannot
begin with a digit.
studentName
marks1
_total
$amount
The following is invalid:
1marks
4.3.2 Common Errors
Beginners may encounter errors because of incorrect syntax, spelling, quotation marks, brackets, or variable names.
1. Missing Quotation Marks
Incorrect:
document.write("Hello);
Correct:
document.write("Hello");
2. Incorrect Capitalization
JavaScript is case-sensitive. For example,
document and Document are not the same.
3. Missing Brackets
Functions and control structures require correctly matched brackets.
if (marks >= 40) {
document.write("Pass");
}
4. Incorrect Variable Name
A variable should be referred to using the same identifier with correct capitalization.
let studentName = "Rahul";
document.write(studentname);
The above code incorrectly uses studentname instead of
studentName.
5. Using a Reserved Keyword
Reserved words and language keywords should not be used as ordinary variable names.
4.4 Input and Output from the Script
JavaScript provides several ways to accept input and display output.
For introductory programs, commonly used methods include
prompt(), alert(), and
document.write().
4.4.1 Using alert()
The alert() function displays a message in a dialog box.
alert("Welcome to the website!");
It is useful when a simple message or notification needs to be shown to the user.
4.4.2 Using prompt()
The prompt() function displays a dialog box that allows
the user to enter a value.
let name = prompt("Enter your name:");
document.write("Hello " + name);
The value returned by prompt() is a string. If the value
is intended to be used in a numerical calculation, it should be
converted to an appropriate numeric type.
let age = Number(prompt("Enter your age:"));
document.write(age + 1);
4.4.3 Using document.write()
The document.write() method can write content to the
webpage.
document.write("Welcome to Code Step Academy");
It can also display values stored in variables.
let marks = 85;
document.write("Marks = " + marks);
document.write() is useful for simple introductory
programs. In modern web development, other DOM-based methods are
generally preferred for updating webpage content after the page
has loaded.
4.4.4 Output Using Console
JavaScript also provides console.log() for displaying
information in the browser's developer console.
let total = 50 + 25;
console.log(total);
Console output is especially useful while testing and debugging JavaScript programs.
Example: Accepting Two Numbers
<script>
let a = Number(prompt("Enter first number:"));
let b = Number(prompt("Enter second number:"));
let sum = a + b;
document.write("Sum = " + sum);
</script>
4.5 Data Types in JavaScript
A data type describes the kind of value stored or represented by a variable.
Some fundamental JavaScript data types include:
| Data Type | Description | Example |
|---|---|---|
| Number | Represents numeric values. | 25, 12.5 |
| String | Represents text. | "Hello" |
| Boolean | Represents true or false. | true, false |
| Undefined | Represents a variable that has not been assigned a value. | undefined |
| Null | Represents an intentional absence of an object value. | null |
4.5.1 Number
The Number type is used for numeric values, including integers and floating-point values.
let age = 16;
let percentage = 87.5;
4.5.2 String
A String represents a sequence of characters. Strings can be written using single quotes or double quotes.
let name = "Amit";
let city = 'Jaipur';
A string can also contain spaces and other characters.
4.5.3 Boolean
A Boolean value can be either
true or false.
let isStudent = true;
let result = false;
Boolean values are commonly used in conditions.
4.5.4 Undefined
A variable declared without assigning a value generally has the value
undefined.
let x;
console.log(x);
4.5.5 Null
null is used to represent an intentional absence of an
object value.
let student = null;
Checking Data Type
The typeof operator can be used to determine the type of
a value.
let age = 16;
console.log(typeof age);
let name = "Riya";
console.log(typeof name);
4.6 Variables in JavaScript
A variable is a named storage location used to hold a value that a program can use.
JavaScript provides var, let, and
const for declaring variables. For modern JavaScript,
let and const are generally preferred.
4.6.1 Declaring a Variable Using var
var marks = 85;
var is an older form of variable declaration and has
function-level scope.
4.6.2 Declaring a Variable Using let
let marks = 85;
A variable declared using let can be reassigned.
let marks = 85;
marks = 90;
4.6.3 Declaring a Constant Using const
A variable declared using const cannot be reassigned
after initialization.
const pi = 3.14159;
Variable Naming Rules
- A variable name should not begin with a digit.
- It may contain letters, digits, underscore, or dollar sign.
- Spaces are not allowed in variable names.
- JavaScript variable names are case-sensitive.
- Reserved keywords should not be used as variable names.
- Meaningful names should be preferred.
Examples
let studentName = "Neha";
let rollNo = 12;
let totalMarks = 450;
Changing Variable Values
let score = 50;
score = 75;
document.write(score);
The final value of score is 75.
Example: Student Marks
let english = 85;
let maths = 92;
let computer = 95;
let total = english + maths + computer;
document.write("Total = " + total);
4.7 Operators in JavaScript
Operators are symbols or keywords used to perform operations on values and variables.
Types of Operators
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Increment and decrement operators
4.7.1 Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations.
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 10 + 5 |
15 |
- |
Subtraction | 10 - 5 |
5 |
* |
Multiplication | 10 * 5 |
50 |
/ |
Division | 10 / 5 |
2 |
% |
Modulus | 10 % 3 |
1 |
** |
Exponentiation | 2 ** 3 |
8 |
4.7.2 Assignment Operators
Assignment operators are used to assign values to variables.
| Operator | Example | Meaning |
|---|---|---|
= |
x = 10 |
Assign 10 to x |
+= |
x += 5 |
x = x + 5 |
-= |
x -= 5 |
x = x - 5 |
*= |
x *= 5 |
x = x * 5 |
/= |
x /= 5 |
x = x / 5 |
4.7.3 Comparison Operators
Comparison operators compare two values and produce a Boolean result.
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to after type conversion where applicable | 5 == "5" |
=== |
Strictly equal in value and type | 5 === 5 |
!= |
Not equal to after type conversion where applicable | 5 != 6 |
!== |
Strictly not equal | 5 !== "5" |
> |
Greater than | 10 > 5 |
< |
Less than | 5 < 10 |
>= |
Greater than or equal to | 10 >= 10 |
<= |
Less than or equal to | 5 <= 10 |
4.7.4 Logical Operators
Logical operators are used to combine or modify conditions.
| Operator | Name | Example |
|---|---|---|
&& |
Logical AND | age >= 18 && citizen == true |
|| |
Logical OR | marks >= 90 || grade == "A" |
! |
Logical NOT | !isPresent |
4.7.5 Increment and Decrement Operators
The increment operator ++ increases a value by one, while
the decrement operator -- decreases a value by one.
let count = 5;
count++;
document.write(count); // 6
count--;
document.write(count); // 5
4.8 Inbuilt Functions in JavaScript
JavaScript provides built-in functions and methods that perform commonly required operations. These reduce the amount of code needed for frequently performed tasks.
4.8.1 Number Conversion
Number()
The Number() function converts a value into a number when
possible.
let age = Number("16");
document.write(age + 2);
parseInt()
parseInt() parses a value and returns an integer when a
valid integer can be obtained.
let x = parseInt("25");
document.write(x);
parseFloat()
parseFloat() parses a value and returns a floating-point
number when appropriate.
let price = parseFloat("125.50");
document.write(price);
4.8.2 String Conversion
String() can be used to convert a value into a string.
let marks = 95;
let result = String(marks);
document.write(result);
4.8.3 Mathematical Functions
JavaScript provides the Math object with mathematical
constants and functions.
| Function / Property | Purpose | Example |
|---|---|---|
Math.round() |
Rounds a number to the nearest integer. | Math.round(4.6) → 5 |
Math.floor() |
Returns the largest integer less than or equal to a number. | Math.floor(4.9) → 4 |
Math.ceil() |
Returns the smallest integer greater than or equal to a number. | Math.ceil(4.1) → 5 |
Math.abs() |
Returns the absolute value. | Math.abs(-10) → 10 |
Math.sqrt() |
Returns the square root. | Math.sqrt(25) → 5 |
Math.pow() |
Returns a number raised to a specified power. | Math.pow(2, 3) → 8 |
Math.max() |
Returns the largest value. | Math.max(10, 20) → 20 |
Math.min() |
Returns the smallest value. | Math.min(10, 20) → 10 |
Math.random() |
Returns a pseudo-random number from 0 inclusive to 1 exclusive. | Math.random() |
4.8.4 String Functions and Properties
JavaScript provides properties and methods for working with strings.
length
The length property returns the number of characters in
a string.
let name = "JavaScript";
document.write(name.length);
toUpperCase()
let name = "javascript";
document.write(name.toUpperCase());
toLowerCase()
let name = "JAVASCRIPT";
document.write(name.toLowerCase());
charAt()
The charAt() method returns the character at a specified
index.
let word = "Computer";
document.write(word.charAt(0));
The output is C.
4.9 Control of Flow Using Conditional Statements
A program normally executes statements in sequence. Sometimes, however, the program needs to make a decision and execute different instructions depending on a condition.
Conditional statements are used to control the flow of execution based on whether a condition is true or false.
Common conditional statements include:
ifif...elseelse ifladderswitch
4.9.1 if Statement
The if statement executes a block of code when its
condition is true.
Syntax
if (condition) {
statements;
}
Example
let marks = 75;
if (marks >= 40) {
document.write("Pass");
}
4.9.2 if...else Statement
The if...else statement provides two alternatives. One
block executes when the condition is true and another executes when
the condition is false.
Syntax
if (condition) {
statements;
} else {
statements;
}
Example
let marks = 35;
if (marks >= 40) {
document.write("Pass");
} else {
document.write("Fail");
}
4.9.3 else if Ladder
An else if ladder is used when there are multiple
conditions to be checked.
Example
let marks = 82;
if (marks >= 90) {
document.write("Grade A+");
} else if (marks >= 80) {
document.write("Grade A");
} else if (marks >= 70) {
document.write("Grade B");
} else if (marks >= 60) {
document.write("Grade C");
} else {
document.write("Needs Improvement");
}
4.9.4 Nested if
An if statement inside another if statement is
called a nested if statement.
Example
let marks = 85;
if (marks >= 40) {
if (marks >= 80) {
document.write("Passed with good performance");
}
}
4.9.5 switch Statement
The switch statement is useful when one expression needs
to be compared against several possible values.
Syntax
switch (expression) {
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
}
Example
let day = 2;
switch (day) {
case 1:
document.write("Monday");
break;
case 2:
document.write("Tuesday");
break;
case 3:
document.write("Wednesday");
break;
default:
document.write("Invalid day");
}
The break statement is generally used to stop execution
from continuing into the next case.
4.10 Control of Flow Using Loops
A loop is used to execute a block of statements repeatedly while a specified condition is satisfied.
Loops are useful when the same operation needs to be performed many times.
Common loops in JavaScript include:
forloopwhileloopdo...whileloop
4.10.1 for Loop
The for loop is commonly used when the number of
repetitions is known or can be controlled using a counter.
Syntax
for (initialization; condition; update) {
statements;
}
Example
for (let i = 1; i <= 5; i++) {
document.write(i + "<br>");
}
The output is:
2
3
4
5
4.10.2 while Loop
A while loop repeatedly executes a block of statements
as long as its condition remains true.
Syntax
while (condition) {
statements;
}
Example
let i = 1;
while (i <= 5) {
document.write(i + "<br>");
i++;
}
The loop continues until i <= 5 becomes false.
4.10.3 do...while Loop
A do...while loop executes its body at least once and
then checks the condition.
Syntax
do {
statements;
} while (condition);
Example
let i = 1;
do {
document.write(i + "<br>");
i++;
} while (i <= 5);
Difference Between while and do...while
| while | do...while |
|---|---|
| Condition is checked before the loop body. | Condition is checked after the loop body. |
| The body may execute zero times. | The body executes at least once. |
| Useful when execution depends on an initial condition. | Useful when the body must execute at least once. |
Example: Displaying Even Numbers
for (let i = 2; i <= 10; i += 2) {
document.write(i + "<br>");
}
Example: Sum of First Five Natural Numbers
let sum = 0;
for (let i = 1; i <= 5; i++) {
sum = sum + i;
}
document.write("Sum = " + sum);
The output is:
Example: Multiplication Table
let n = Number(prompt("Enter a number:"));
for (let i = 1; i <= 10; i++) {
document.write(
n + " × " + i + " = " + (n * i) + "<br>"
);
}
Example: Checking Even or Odd
let n = Number(prompt("Enter a number:"));
if (n % 2 == 0) {
document.write("Even Number");
} else {
document.write("Odd Number");
}
Example: Finding the Greater of Two Numbers
let a = Number(prompt("Enter first number:"));
let b = Number(prompt("Enter second number:"));
if (a > b) {
document.write(a + " is greater");
} else if (b > a) {
document.write(b + " is greater");
} else {
document.write("Both numbers are equal");
}
Example: Calculating Percentage
let english = Number(prompt("Enter English marks:"));
let maths = Number(prompt("Enter Mathematics marks:"));
let computer = Number(prompt("Enter Computer marks:"));
let science = Number(prompt("Enter Science marks:"));
let hindi = Number(prompt("Enter Hindi marks:"));
let total = english + maths + computer + science + hindi;
let percentage = total / 5;
document.write("Total Marks = " + total + "<br>");
document.write("Percentage = " + percentage + "%");
JavaScript Program Development: Basic Pattern
A simple JavaScript program can generally be developed using the following sequence:
For example, to determine whether a student has passed:
- Accept the student's marks.
- Store the marks in a variable.
- Compare the marks with the passing criterion.
- Display the appropriate result.
let marks = Number(prompt("Enter marks:"));
if (marks >= 40) {
document.write("Pass");
} else {
document.write("Fail");
}
Common Mistakes to Avoid
- Remember that JavaScript is case-sensitive.
- Use matching opening and closing brackets.
- Use quotation marks correctly when working with strings.
- Do not begin a variable name with a digit.
- Do not use reserved keywords as variable names.
-
Convert input obtained through
prompt()when a numerical calculation is required. - Make sure loop variables are updated to avoid unintended infinite loops.
-
Use
breakappropriately inswitchstatements. - Check the browser console when debugging JavaScript errors.
Practical Programs for Class XI
The following programs provide useful practice for the JavaScript portion of the practical examination and portfolio/practical file.
Program 1: Display a Message
<script>
document.write("Welcome to JavaScript");
</script>
Program 2: Add Two Numbers
<script>
let a = Number(prompt("Enter first number:"));
let b = Number(prompt("Enter second number:"));
let sum = a + b;
document.write("Sum = " + sum);
</script>
Program 3: Check Positive, Negative or Zero
<script>
let n = Number(prompt("Enter a number:"));
if (n > 0) {
document.write("Positive");
} else if (n < 0) {
document.write("Negative");
} else {
document.write("Zero");
}
</script>
Program 4: Find Factorial
<script>
let n = Number(prompt("Enter a number:"));
let factorial = 1;
for (let i = 1; i <= n; i++) {
factorial = factorial * i;
}
document.write("Factorial = " + factorial);
</script>
Program 5: Display Numbers from 1 to 10
<script>
for (let i = 1; i <= 10; i++) {
document.write(i + "<br>");
}
</script>
Chapter Summary
JavaScript is a scripting language used to add dynamic behaviour and interactivity to webpages. It works together with HTML and CSS in client-side web development.
JavaScript code can be embedded in an HTML document using the
<script> element. JavaScript is case-sensitive and
requires correct syntax, variable names, brackets, and quotation
marks.
JavaScript programs can accept input using methods such as
prompt() and display output using
alert(), document.write(), and
console.log().
Variables store values, while data types describe the nature of those values. Important introductory data types include Number, String, Boolean, Undefined, and Null.
Operators are used for arithmetic calculations, assignment, comparison, logical operations, and increment/decrement operations.
JavaScript provides built-in functionality for common tasks such as numerical calculations, type conversion, and string processing.
Conditional statements such as if,
if...else, else if, and
switch allow a program to make decisions.
Loops such as for, while, and
do...while allow a block of code to be executed
repeatedly.
↓
Variables + Data Types + Operators
↓
Input + Processing
↓
Conditions + Loops
↓
Output
Quick Revision
| Topic | Key Point |
|---|---|
| JavaScript | A scripting language used to add dynamic and interactive behaviour to webpages. |
| HTML | Provides webpage structure. |
| CSS | Controls webpage presentation and styling. |
| <script> | HTML element used to include JavaScript code. |
| prompt() | Accepts input from the user through a dialog box. |
| alert() | Displays a message in a dialog box. |
| document.write() | Writes content to the webpage. |
| Number | Represents numerical values. |
| String | Represents textual data. |
| Boolean | Represents true or false. |
| Variable | Named storage for a value. |
| Operators | Perform calculations, comparisons, assignments, and logical operations. |
| if | Executes code when a condition is true. |
| if...else | Provides two alternative execution paths. |
| switch | Selects an execution path based on a value. |
| for | Repeats a block of code using initialization, condition, and update. |
| while | Repeats code while a condition remains true. |
| do...while | Executes the loop body at least once before checking the condition. |
Important Questions for Revision
- What is JavaScript?
- What is the role of JavaScript in web development?
- Differentiate between HTML, CSS, and JavaScript.
- Briefly describe the history of JavaScript.
- What is ECMAScript?
- How is JavaScript executed by a web browser?
- List the major features of JavaScript.
- Write any four advantages of JavaScript.
- What are the prerequisites for working with JavaScript?
- What is the purpose of the <script> tag?
- Why is JavaScript called case-sensitive?
- List some common errors made while writing JavaScript.
- What is the purpose of the prompt() function?
- What is the use of alert()?
- What is the purpose of document.write()?
- What is the difference between document.write() and console.log()?
- What is a data type?
- Name some basic JavaScript data types.
- What is a variable?
- What is the difference between let and const?
- What are arithmetic operators?
- What is the difference between == and ===?
- What are logical operators?
- What is the purpose of the modulus operator?
- What is the use of Math.round()?
- What is the use of parseInt()?
- What is a conditional statement?
- Differentiate between if and if...else.
- What is an else if ladder?
- What is the purpose of the switch statement?
- What is a loop?
- Differentiate between while and do...while loops.
- When is a for loop useful?
- Write a JavaScript program to find whether a number is even or odd.
- Write a JavaScript program to calculate the sum of first five natural numbers.
Multiple Choice Questions
Q1. JavaScript is primarily used to:
- Structure webpages
- Style webpages only
- Add dynamic and interactive behaviour to webpages
- Create database tables only
Answer: C
Q2. Which HTML tag is used to embed JavaScript code?
- <javascript>
- <script>
- <js>
- <code>
Answer: B
Q3. JavaScript is:
- Case-sensitive
- Case-insensitive
- Only used for databases
- A CSS framework
Answer: A
Q4. Which function accepts input from the user through a dialog box?
- alert()
- prompt()
- write()
- input()
Answer: B
Q5. Which function displays a message in a dialog box?
- prompt()
- alert()
- display()
- message()
Answer: B
Q6. Which data type represents true or false?
- String
- Number
- Boolean
- Undefined
Answer: C
Q7. Which operator returns the remainder after division?
- /
- %
- *
- +
Answer: B
Q8. Which keyword is commonly used to declare a block-scoped variable whose value can be reassigned?
- let
- const
- fixed
- static
Answer: A
Q9. Which operator is used for strict equality comparison?
- =
- ==
- ===
- !=
Answer: C
Q10. Which operator represents logical AND?
- ||
- &&
- !
- %%
Answer: B
Q11. Which function converts a value to a number?
- Number()
- String()
- Boolean()
- Text()
Answer: A
Q12. Which function returns the square root of a number?
- Math.power()
- Math.sqrt()
- Math.root()
- Math.square()
Answer: B
Q13. Which statement is used to execute code when a condition is true?
- if
- loop
- switch only
- repeat
Answer: A
Q14. Which statement is useful for selecting one option from multiple cases?
- if
- switch
- while
- for
Answer: B
Q15. Which loop is guaranteed to execute its body at least once?
- for
- while
- do...while
- if
Answer: C
Q16. Which loop is commonly used when the number of iterations is known?
- for
- while
- switch
- if
Answer: A
Q17. What will be the output?
let x = 10;
let y = 3;
document.write(x % y);
- 1
- 3
- 10
- 0
Answer: A
Q18. What will be the output?
let x = 5;
x++;
document.write(x);
- 4
- 5
- 6
- 7
Answer: C
Q19. What will be the output?
let marks = 75;
if (marks >= 40) {
document.write("Pass");
} else {
document.write("Fail");
}
- Fail
- Pass
- 75
- Error
Answer: B
Q20. What will be the output?
for (let i = 1; i <= 3; i++) {
document.write(i);
}
- 123
- 012
- 1234
- 321
Answer: A