Q 24: What is JavaScript
JavaScript
JavaScript is a popular programming language used to make websites interactive and dynamic.
It works together with HTML and CSS to create modern web pages.
Purpose of JavaScript
JavaScript adds behavior to web pages.
It allows websites to respond to user actions like clicks, typing, and mouse movements.
It makes web pages more interactive and user-friendly.
Q 25: Write some key features/ characteristic?
Features / Characteristics of JavaScript
1. Lightweight: JavaScript is relatively lightweight, meaning it requires less memory and processing power.
2. Event-Driven: JavaScript is designed to handle events (e.g., user actions like clicks and key presses) and respond to them.
3. Browser Compatibility: JavaScript runs in all modern web browsers without needing any special setup or plugins, making it an essential tool for web development.
4. DOM Manipulation: JavaScript can interact with and manipulate the Document Object Model (DOM), allowing developers to dynamically update content, style, and structure of web pages.
5. Object-Oriented: JavaScript supports object-oriented programming (OOP) principles.
Q 26: What aspects of HTML can be changed with JavaScript
Main Aspects of HTML that can be Changed with JavaScript
1. Content:
You can change the text inside an element.
document.getElementById("myElement").textContent = "New Text";
2. Attributes:
You can modify attributes of elements, like src for images, href for links, or custom data attributes.
document.getElementById("myImage").setAttribute("src", "newImage.jpg");
3. Styles:
JavaScript can modify the styling of HTML elements, including properties like color, font size, background and positioning.
document.getElementById("myElement").style.color = "red";
document.getElementById("myElement").classList.add("newClass");
4. Element Properties:
JavaScript can change the properties of form inputs, like text fields, checkboxes, etc.
document.getElementById("myInput").value = "New Value";
5. Events:
JavaScript can add event listener to HTML (e.g., clicks, keypresses) and modify HTML accordingly.
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
6. Form Handling:
JavaScript can prevent or modify how forms are submitted and processed.
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevent form submission
});
Q 27: What aspects of CSS can be changed with JavaScript
Manipulating CSS Properties with JavaScript
1. Inline CSS Styles:
You can use JavaScript to manipulate an element’s inline style properties (e.g., color, font-size, width).
document.getElementById("myElement").style.color = "blue";
document.getElementById("myElement").style.fontSize = "20px";
document.getElementById("myElement").style.width = "100px";
2. Backgrounds:
You can change background color, images, and other background-related properties.
document.getElementById("myElement").style.backgroundColor = "yellow";
document.getElementById("myElement").style.backgroundImage = "url('image.jpg')";
3. Borders and Box Shadows:
You can adjust an element’s borders and apply or change box shadows.
document.getElementById("myElement").style.border = "2px solid red";
document.getElementById("myElement").style.boxShadow = "10px 10px 5px #888";
4. Fonts and Text Styles:
JavaScript can modify font-related properties, like font-family, font-size and text-decoration.
document.getElementById("myElement").style.fontFamily = "Arial";
document.getElementById("myElement").style.fontSize = "18px";
document.getElementById("myElement").style.textDecoration = "underline";
5. Sizing and Spacing:
You can change dimensions (e.g., width, height) or other spacing-related properties like margin and padding.
document.getElementById("myElement").style.width = "300px";
document.getElementById("myElement").style.padding = "10px";
6. Transitions and Animations:
JavaScript can trigger animations by changing CSS properties and can control the timing functions.
document.getElementById("myElement").style.transition = "all 0.5s ease";
document.getElementById("myElement").style.transform = "translateX(100px)";
Q 28: How to embedded JavaScript in HTML?
Embedding JavaScript in HTML
JavaScript code can be embedded in HTML with starting and ending tag of <script> </script> in a webpage.
There is no limitation of where to place the code inside an HTML file.
Q 29: Explain document.write() function in Javascript?
document.write() Function in JavaScript
The document.write() function in JavaScript is used to write HTML or text directly into a document (webpage) while the page is being loaded.
It's one of the simplest methods to add content dynamically to a webpage, but it comes with important considerations and limitations.
Syntax
document.write('content to be written');
Q 30: Display a sentence by using document.write() function?
JavaScript document.write() Example
<html>
<body>
<script language="javascript">
document.write("let’s Meet Javascript");
</script>
</body>
</html>
Q 31: Storing values in TWO variables and display it by using document.write() function
JavaScript Variable Example
<html>
<body>
<script type="text/javascript">
var name = "Ahsan";
var reward;
reward = 5000;
document.write(name, " gets a reward of Rupees ", reward);
</script>
</body>
</html>
Q 32: Define an Event in Javascript and its some common types?
Events in JavaScript
In JavaScript, an event is an action or occurrence that happens in the browser, which the browser or the user can sense and trigger (activate) some task to be done, is called an 'event'.
Events can be triggered by user interactions, such as clicking a button, pressing a key, or moving the mouse, as well as by browser-related actions, such as the page loading or resizing.
Common Types of Events
Mouse Events
click: Triggered when an element is clicked.
dblclick: Triggered when an element is double-clicked.
mousedown: Triggered when a mouse button is pressed down on an element.
mouseup: Triggered when a mouse button is released over an element.
Keyboard Events
keydown: Triggered when a key is pressed down.
keyup: Triggered when a key is released.
keypress: Triggered when a key is pressed down and released.
Window Events
load: Triggered when the entire page, including all dependent resources, has loaded.
resize: Triggered when the browser window is resized.
Touch Events (for mobile devices)
touchstart: Triggered when a touch point is placed on the touch surface.
touchend: Triggered when a touch point is removed from the touch surface.
Q 33: Define Handling Events with example?
Handling Events with JavaScript
To handle events, you typically use event listeners, which are functions that are executed when a specific event occurs.
You can add event listeners to elements using the addEventListener method.
Example: Handling a Click Event
<html>
<head> <title>Button-Click Event</title> </head>
<body>
<button id="myButton">Click me!</button>
<script>
// Select the button element
const button = document.getElementById('myButton');
// Define the event listener function
function handleClick() {
alert('Button was clicked!');
}
// Add the event listener to the button
button.addEventListener('click', handleClick);
</script>
</body>
</html>
In this example, when the button with the ID
myButton is clicked, the
handleClick function is executed, displaying an alert message.
Q 34: What is the function of prompt() in Javascript?
JavaScript prompt() Function
The prompt() function in JavaScript is used to display a dialog box that prompts the user for input.
It is a simple and effective way to collect input from the user.
The function pauses the execution of the script until the user provides the input or cancels the dialog.
Syntax
var userInput = prompt(message);
message (optional): A string that is displayed as the message inside the prompt dialog.
Example
<html>
<body>
<script type="text/javascript">
var ip = prompt("Input a number, please.");
document.write("Input from the user was, number=", ip);
</script>
</body>
</html>
Q 35: What is the function of alert() in Javascript?
alert() Method in JavaScript
The alert() method displays an alert box with a message and an OK button.
It is commonly used to inform the user about the result of their action or for notifications.
In website development, it is the easiest way to allow some event to occur and respond.
It is mostly used to give a warning message to the users.
The alert dialog box takes the focus and forces the user to read the specified message.
Syntax
alert(message);
message: It specifies the text to display in the alert box. It consists of the information that we want to show to the users.
Example 1
alert("Hello, world!");
Example 2: Display Message When Button is Clicked
Here, there is an HTML button used for displaying the alert box. We are using the onclick attribute and call the
msgSure() function where the alert() is defined.
<html>
<head>
<script type="text/javascript">
function msgSure() {
alert("Are You Sure???");
}
</script>
</head>
<body>
Do You Mind, CLICKING on the Button -
<input type="button" onclick="msgSure();" value="Be Sure"/>
</body>
</html>
Q 36: Define Comments and how are used in javascript?
Comments in JavaScript
There are two types of comments in JavaScript: single-line comments and multi-line comments.
1. Single-Line Comments
Single-line comments start with two forward slashes (//). Everything following the // on that line is considered a comment and is ignored by the JavaScript engine.
Example: // This is a single-line comment
2. Multi-Line Comments
Multi-line comments start with /* and end with */. They can span multiple lines, making them useful for longer explanations or for commenting out blocks of code.
Example: /* This is a multi-line comment.
It can span multiple lines. */
Q 37: Explain different Data Types used in JavaScript?
Data Types in JavaScript
There are basically two data types in JavaScript:
1. Primitive Data Types
Primitive data types represent single values. These are predefined by JavaScript. Primitive data types are also known as in-built data types.
There are following five types of primitive data types in JavaScript:
i. String: represents sequence of characters e.g. "hello"
ii. Number: represents numeric values e.g. 100
iii. Boolean: represents boolean value either false or true
iv. Undefined: represents undefined value
v. Null: represents null i.e. no value at all
2. Non-Primitive Data Types
The data types that are derived from primitive data types of the JavaScript language are known as non-primitive data types.
It is also known as derived data types or reference data types.
There are following types of non-primitive data types in JavaScript:
i. Object: Objects can have fields with different values and types inside
ii. Array: It can hold more than one value in a single variable
iii. Date: You can use the JavaScript Date object to manipulate the date.
Q 38: Define variable, write rule for naming variables, how variables are Declaration and initialization (represented) and write Basic Data Types?
Variables in JavaScript
A variable is a temporary container to store information.
A variable is a container (storage area) whose value can be changed during program execution.
The variables are used to represent unknowns.
The basic value that a variable can hold in JavaScript is either a number or set of characters (called string) or a Boolean which is either 'true' or 'false'.
Syntax: var variableName = value;
Variable Naming Rules
Variable names (identifiers) in JavaScript must follow certain rules:
They can contain letters (a-z, A-Z), digits (0-9), underscores (_), and dollar signs ($).
They cannot start with a digit (number).
JavaScript is case-sensitive (reward is different from Reward).
How Variables are Declared in JavaScript?
JavaScript Variables can be declared in 4 ways:
1. Automatically (e.g. x = 5;)
2. var:
- Declares a variable that can be reassigned.
- Scope is function-level (hoisted to the top of the function).
- Can be redeclared.
3. let:
- Declares a variable that can be reassigned.
- Scope is block-level (only exists within curly braces {}).
- Cannot be redeclared.
4. const:
- Declares a constant variable that cannot be reassigned.
- Scope is block-level (not hoisted).
- Cannot be redeclared.
How Variables are Initialized in JavaScript?
The first ever assignment of a value to a variable in the lifespan of program is called 'initialization'.
You can assign a value to a variable using the = operator when you declare it or after the declaration and before accessing it.
Example: Let msg;
msg = "Hello JavaScript";
Note: A good programming practice is to declare and initialize the variable at the same time.
Q 39: What will the output of the following programme?
<html>
<body>
<script type="text/javascript">
var a, b, reward;
reward = 5555;
a = reward % 10;
b = reward / 10;
document.write(a, "-----", b);
</script>
</body>
</html>
Output
5-----555.5
Note: It is important to note that sequence of instructions in programming matters.
Q 40: What will the output of the following programme?
<html>
<body>
<script type="text/javascript">
var a, b, reward;
reward = 5555;
a = reward % 10;
b = reward / 10;
document.write("Value of variable a is ", a);
document.write("<br />");
document.write("Value of variable b is ", b);
</script>
</body>
</html>
Output
Value of variable a is 5
Value of variable b is 555.5
Q 41: Define Operators and explain its typs?
Operators in JavaScript
Operators are symbols or keywords that tell a compiler or interpreter to perform specific mathematical, relational, or logical operations and produce a result.
They are used to manipulate data, variables, and values.
Example: let x = 10 + 5;
1. Arithmetic Operators
These perform basic mathematical operations.
| Operator |
Description |
Operator |
Description |
| + |
Addition |
% |
Modulus (Remainder) |
| - |
Subtraction |
++ |
Increment (Unary) |
| * |
Multiplication |
-- |
Decrement (Unary) |
| / |
Division |
|
|
2. Relational (or Comparison) Operators
These compare two values and return a Boolean result (True or False).
| Operator |
Description |
Operator |
Description |
| == |
Equal to |
< |
Less than |
| != |
Not equal to |
>= |
Greater than or equal to |
| > |
Greater than |
<= |
Less than or equal to |
3. Logical Operators
These combine or modify Boolean expressions and also return a Boolean result.
| Operator |
Description |
| && (AND) |
Logical AND (True if both are True) |
| || (OR) |
Logical OR (True if at least one is True) |
| ! (NOT) |
Logical NOT (Reverses the result) |
4. Assignment Operators
These assign a value to a variable.
| Operator |
Description |
Operator |
Description |
| = |
Simple Assignment |
-= |
Subtract and Assign |
| += |
Add and Assign |
*= |
Multiply and Assign |
Q 42: What is control structure? Explain conditional control structure with examples?
Control Structure in JavaScript
In JavaScript, control structures determine the flow of execution of the code. The three basic types of control structures are sequence, selection, and iteration.
1. Sequence
The sequence control structure is the default mode; instructions are executed one after the other in the order in which they are written.
Syntax:
statement1;
statement2;
statement3;
2. Selection (Conditional Statements)
Selection control structures allow the code to make decisions, based on conditions.
Types/ scenarios of Control Structures in JavaScript: if, if-else, if...else if...else
i. if Statement:
If the condition is true then the block of statements following if will be executed.
If the condition is false then the block of statements following if will be skipped and the control will transfer to the next statement if any exists.
Syntax:
if (condition) {
Block of statements
}
Example:
<html>
<body>
<script type="text/javascript">
var kid_age = 5;
if(kid_age > 3) {
document.write("<b> Admission Granted !!! </b>");
}
</script>
</body>
</html>
Output: Admission Granted !!!
ii. if...else Statement:
If the condition is true then the block of statements following if will be executed and the block of statements following else will be skipped.
If the condition is false then the block of statements following if will be skipped and the block of statements following else will be executed.
Syntax:
if (condition) {
Block of statements
} else {
Block of statements
}
Example:
<html>
<body>
<script type="text/javascript">
var kid_age = 5;
if(kid_age > 6) {
document.write("<b> Admission Granted !!! </b>");
} else {
document.write("<b> Age Requirement is not met !!! </b>");
}
</script>
</body>
</html>
Output: Age Requirement is not met !!!
iii. if...else if...else Statement:
It is used when there is more than two/multiple conditions to be tested.
If none of the conditions is true then the block of statements following else is executed automatically.
Syntax:
if (condition1) {
Block of statements
} else if (condition2) {
Block of statements
} ... else {
Block of statements
}
Example:
<html>
<body>
<script type="text/javascript">
var kid_age = 5;
if(kid_age > 6) {
document.write("<b> Admission in Primary School !!! </b>");
} else if (kid_age > 4) {
document.write("<b> Admission Granted in KG Class !!! </b>");
} else if (kid_age > 3) {
document.write("<b> Admission Granted in Nursery Class !!! </b>");
} else {
document.write("<b> Kid is Underage !!! </b>");
}
</script>
</body>
</html>
Output: Kid is Underage !!!
3. Iteration (Loops)
Execute a block of code repeatedly as long as a specified condition is true. Iteration is another term for looping.
Types of Iteration (Loops): for, while, do...while
i. For loop: Executes a block of code a specific number of times.
Syntax:
for (initialization; condition; increment) {
// code to be executed
}
Q 43: Write a programme in Javascript using for loop to show how index value increases
<html>
<body>
<script type="text/javascript">
var index;
document.write("For-Loop Starts After This .. <br />");
for(index = 0; index<10;index+1){
document.write("Index No:", index,"<br />");
}
document.write("For-Loop Stopped !");
</script>
</body>
</html>
Q 44: How the sequence of instructions affects the result?
Here are some key points on how the sequence of instructions affects the result:
1. Order of operations:
Changing the order of instructions can alter the order of operations, leading to different results.
2. Dependency on previous steps:
Instructions often rely on the results of previous steps. If the sequence is changed, the dependencies may be broken, leading to incorrect results.
3. Error Prevention:
Following the correct sequence helps to prevent mistakes, such as attempting to perform actions before necessary conditions are met.
4. Efficiency:
A well-ordered sequence can improve the speed and resource usage of the task, making it more efficient.
5. Final Output:
Different orders of execution can lead to different results and desired outcomes to incorrect or unexpected ones.
Q 45: Define Nested Loops in Javascript?
A Nested loop:
A Nested loop is a loop statement within another loop statement.
Hence, nested loops in Java are also known as ‘loop inside loop.’
There can be multiple loops inside another loop.
Working of Nested Loop:
In nested loop, initially the outer loop will start and then the inner loop will run and finish. So, the value of the outer loop will increase, and the inner loop will start and finish again. This will keep happening until the outer loop stops.
Syntax:
for ( initialization; condition; increment/decrement ) {
for ( initialization; condition; increment/decrement ) {
// inner for loop body
}
// outer for loop body
}
Q 46: Write a programme in Javascript to print the table from 2-5 using nested loop?
Show Code in Browser
<html>
<body>
<script type="text/javascript">
for(var i = 2; i <= 5; i++) {
document.write("<br /> Table of:", i, "<br />");
for(var j = 1; j <= 10; j++) {
document.write("x", j, " = , ");
}
document.write("<br /><br />");
}
</script>
</body>
</html>
Q 47: Write a programme in Javascript to declare and initialize array in a single line?
Show JavaScript Code in Table
| Code |
Output |
<html>
<head>
<title>Arrays in JavaScript</title>
</head>
<body>
<script type="text/javascript">
var Arr = [4,2,5,1,3];
document.write("Array is:", Arr);
</script>
</body>
</html>
|
Array is: 4,2,5,1,3
|
Q 48: Write a programme in Javascript to show nested loop?
Nested Loops Example
| Code |
Output |
<html>
<body>
<script type="text/javascript">
document.write("About to Enter the loops !!! <br />");
for(var i = 0; i<5; i++)
{
document.write("<br />The Outer Loop:", i, "<br />");
for(var j = 0; j<3; j++)
{
document.write("Inner Loop:", j, " ");
}
}
document.write("<br /><br /><br /> Loops Terminates !!! <br />");
</script>
</body>
</html>
|
About to Enter the Loops !!!
The Outer Loop: 0
Inner Loop: 0 Inner Loop: 1 Inner Loop: 2
The Outer Loop: 1
Inner Loop: 0 Inner Loop: 1 Inner Loop: 2
The Outer Loop: 2
Inner Loop: 0 Inner Loop: 1 Inner Loop: 2
The Outer Loop: 3
Inner Loop: 0 Inner Loop: 1 Inner Loop: 2
The Outer Loop: 4
Inner Loop: 0 Inner Loop: 1 Inner Loop: 2
Loops Terminates !!!
|
Q 49: Define Array?
JavaScript Arrays
In JavaScript, An array is a special variable that is used to store more than one value.
These values, called elements, can be of any type (e.g., numbers, strings, objects, other arrays).
Array elements are accessed using their specific position (index), which starts at 0.
Arrays are denoted by square brackets [] and elements are separated by commas.
Syntax:
let array_name = [element1, element2, ...];
It is a common practice to declare arrays with the let (var and const are also used) keyword.
Example:
let cars = ["Saab", "Volvo", "BMW"];
Creating an Empty Array and Adding Elements:
let cars = [];
cars[0] = "";
cars[1] = "";
cars[2] = "";
Q 50: How to access elements in an array?
Syntax:
ArrayName[index] (e.g. Arr[0] for the first element)
Why we use Arrays?
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
Q 51: Write a programme in Javascript that input via prompt() using for-loop and prints the elements of the array?
<html>
<head>
<title>Arrays in JavaScript</title>
</head>
<body>
<script type=”text/javascript”>
var Arr = [];
for (i=0; i<5; i++)
Arr[i] = prompt (“Input Array element”);
document.write(“Elements of Array using For-Loop are, after declaring a null array”, Arr);
</script>
</body>
<html>
Output:
Elements of Array using For-Loop are, after declaring a null array: 5,3,7,1,9
Q 52: Define Functions and its types?
Function
Function is a block of code that can be executed repeatedly with different inputs.
It is defined once and can be called again and again.
Function can manage a large computer program easily without rewriting the code again.
Types of functions:
1. Built-in Functions: Built-in functions in JavaScript are predefined functions provided by the language that perform common tasks e.g prompt(), alert(), etc. Whenever the function is called, the caller does not necessarily need to know the code behind that function to use it.
2. User Defined Functions: It is defined by the user (developer) to solve a particular problem or perform a specific operation.
Syntax of Function in Javascript?
Syntax:
function functionName (parameters) {
// code to be executed
}
o function keyword indicates that we're defining a function.
o functionName is defined by the user through which it is identified and called. (e.g., calculateArea, validateInput, etc.)
o parameters are the inputs that the function accepts (e.g., x, y, name, etc.).
o The code inside the curly braces {} is the function body, which is executed when the function is called.
Q 53: How function is called (Invoked)?
Calling a Function in JavaScript
In JavaScript, a function is called (or invoked) by using the function name followed by parentheses () containing any required arguments.
Syntax:
functionName(argument1, argument2, ...);
o functionName is the name of the function you want to call.
o argument1, argument2, etc. are the values passed to the function.
Q 54: Write a programme in Javascript that show function with arguments?
Example: Function with Return Value
<html>
<body>
<script type="text/javascript">
function calcBill (bill, amount_rcvd){
document.write("Your Balance is: ");
return(amount_rcvd-bill);
}
var balance = calcBill(2345,5000);
document.write(balance);
</script>
</body>
</html>