M1 FS Ia1
M1 FS Ia1
Ans:
JavaScript
console.log(data);
Java
System.out.println("Hello, Java!");
}
}
Security
• JavaScript: Less secure, vulnerable to XSS and injection attacks as it runs in browsers.
• Java: More secure, runs in JVM with built-in security features like bytecode
verification.
Performance
• Java: Faster, compiled into bytecode and supports multithreading for better
performance.
JavaScript is mainly used for web interactivity, while Java is used for general-purpose
programming, including mobile and backend applications.
2. Explain the difference between var, let, and const in JavaScript with examples.
Ans:
Example:
var x = 10;
if (true) {
var x = 20; // Re-declaration allowed
console.log(x); // Output: 20
}
console.log(x); // Output: 20 (Var is not block-scoped)
Hoisting Example:
console.log(x); // Output: undefined
var x = 5;
Example:
let y = 10;
if (true) {
let y = 20; // Creates a new variable inside this block
console.log(y); // Output: 20
}
console.log(y); // Output: 10 (Different from `var`)
Re-declaration Error
let a = 5;
let a = 10; // Error: 'a' has already been declared
Example:
const z = 30;
console.log(z); // Output: 30
Reassignment Error
const z = 30;
z = 40; // Error: Assignment to constant variable
Must be initialized
3. Discuss different data types in JavaScript? List and explain any four.
1. Number
2. String
3. Boolean
4. Object
let person = {
name: "Alice",
age: 30,
isStudent: false
};
An array in JavaScript is a data structure used to store multiple values in a single variable.
Arrays can hold different data types, such as numbers, strings, objects, and even other arrays.
This is the most common and preferred way to create an array in JavaScript.
• The elements are enclosed within square brackets [] and separated by commas.
• JavaScript arrays are zero-indexed, meaning the first element is at index 0, the
second at 1, and so on.
Example:
console.log(emptyArray); // Output: []
console.log(mixedArray);
Conclusion
JavaScript arrays are flexible and easy to use. They can be created using square brackets []
(preferred) or the Array constructor. Arrays can hold different data types and support
various operations to manipulate data efficiently.
Ans:
Difference Between for Loop and while Loop in JavaScript
Both for and while loops are used to execute a block of code repeatedly, but they differ in
syntax and usage.
Example:
console.log(i); // Output: 1, 2, 3, 4, 5
Example:
let i = 1;
while (i <= 5) {
console.log(i); // Output: 1, 2, 3, 4, 5
i++;
Key Differences
Ans:
function factorial(n) {
let result = 1;
result *= i;
return result;
Using Recursion
function factorialRecursive(n) {
7.Explain how JavaScript objects are created. Illustrate with an example using object
properties and methods.
The most common and simplest way to create an object is by using curly braces {}.
let person = {
name: "John",
age: 25,
city: "New York",
greet: function() {
return "Hello, my name is " + this.name + ".";
}
};
• This method is less common and not preferred over object literals.
A constructor function allows you to create multiple objects with similar properties.
• The new keyword creates a new object based on the Person constructor.
4. Using Object.create()
let prototypePerson = {
greet: function() {
return "Hello, my name is " + this.name + ".";
}
};
• This method is useful when you want to inherit properties from another object.
Conclusion
JavaScript objects can be created in multiple ways, but the object literal method ({}) is the
most commonly used due to its simplicity and readability. Objects help in structuring data
efficiently using properties (variables) and methods (functions).
8. Describe the different types of string methods available in JavaScript with examples.
Ans:
JavaScript provides various built-in string methods to manipulate and process text. These
methods allow performing operations like searching, modifying, splitting, and formatting
strings.
1. Finding the Length of a String
console.log(str.length); // Output: 13
2. Changing Case
• slice(start, end): Extracts part of a string from start index to end index (excluding
end).
• substring(start, end): Similar to slice(), but does not accept negative values.
• substr(start, length): Extracts a substring starting from start and takes length
characters.
5. Searching in a String
console.log(phrase.indexOf("JavaScript")); // Output: 9
console.log(phrase.lastIndexOf("is")); // Output: 18
6. Removing Whitespaces
7. Splitting a String
8. Concatenating Strings
Conclusion
JavaScript provides various string methods to manipulate and process text efficiently.
These methods help with searching, modifying, extracting, formatting, and splitting
strings based on different needs.
Ans:
Control flow statements like if-else and switch-case allow JavaScript to execute different
blocks of code based on conditions.
1. If-Else Statement
The if-else statement executes a block of code if a condition is true and another block if the
condition is false.
Syntax
if (condition) {
// Code executes if condition is true
} else {
// Code executes if condition is false
}
Example
let age = 18;
Output:
You are eligible to vote.
Else-If Ladder
Output:
Grade: B
2. Switch-Case Statement
The switch statement is used when there are multiple possible values for a variable, and
different actions need to be taken based on those values.
Syntax
switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
default:
// Code to execute if none of the cases match
}
Example
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the workweek.");
break;
case "Friday":
console.log("Weekend is near!");
break;
case "Sunday":
console.log("It's a holiday.");
break;
default:
console.log("It's a regular day.");
}
Output:
Start of the workweek.
The break statement stops further execution once a case is matched. The default case runs
if none of the cases match the given value.
The switch-case statement is best when checking a single variable against multiple fixed
values. It directly jumps to the matched case, making it more efficient for such scenarios.
Use if-else when checking conditions with relational or logical operators. Use switch-
case when checking a variable against multiple fixed values.
10. Write a JavaScript program to find the largest number in an array using a loop.
Ans:
Program
function findLargestNumber(arr) {
if (arr.length === 0) {
return "Array is empty";
}
return largest;
}
11. Write a script that Logs "Hello, World!" to the console. Create a script that calculates
the sum of two numbers and displays the result in an alert box.
Ans:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LAB 1</title>
<link rel="icon" href="data:,">
</head>
<body>
<h1>WELCOME TO SEE HELLO WORLD IN CONSOLE</h1>
<div id="result"></div>
<script>
console.log("HELLO WORLD");
</script>
</body>
</html>
12. Create an array of 5 cities and perform the following operations: Log the total number
of cities. Add a new city at the end. Remove the first city. Find and log the index of a
specific city.
Ans:
13. Read a string from the user, Find its length. Extract the word "JavaScript" using
substring() or slice(). Replace one word with another word and log the new string.
Ans:
if(startInd!= -1){
let extractedWord=string.slice(startInd, startInd+10);
console.log("Extracted word:", extractedWord);
}
else{
console.log("The word 'JavaScript' was not found in the string.");
}
14. Write a function isPalindrome(str) that checks if a given string is a palindrome (reads
the same backward).
Ans:
function isPalindrome(word) {
let reversed = word.split("").reverse().join("");
console.log("Reversed String:", reversed);
15. Write a JavaScript program to declare variables of different data types (string,
number, boolean, array, and object) and display their values using console.log()
Ans:
JavaScript supports various data types, including string, number, boolean, array, and object.
The following program demonstrates how to declare these data types and print their values
using console.log().
Program
// String
let name = "John Doe";
console.log("String:", name);
// Number
let age = 25;
console.log("Number:", age);
// Boolean
let isStudent = true;
console.log("Boolean:", isStudent);
// Array
let colors = ["Red", "Blue", "Green"];
console.log("Array:", colors);
// Object
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
isStudent: true
};
console.log("Object:", person);
Explanation
• A string variable is declared and assigned a name.
• A number variable is assigned an integer value.
• A boolean variable stores a true/false value.
• An array is declared to hold multiple values.
• An object is created to store multiple properties of a person.
• The console.log() function is used to display each variable's value.
Output
String: John Doe
Number: 25
Boolean: true
Array: [ 'Red', 'Blue', 'Green' ]
Object: { firstName: 'John', lastName: 'Doe', age: 25, isStudent: true }
16. Write a JavaScript program to create an array of five numbers. Find and print the
largest and smallest numbers from the array.
Ans:
function findLargestAndSmallest(arr) {
if (arr.length === 0) {
return "Array is empty";
}
17. Write a JavaScript function that takes a string as input and: • Converts it to uppercase
• Reverses the string • Counts the number of vowels in the string
Ans:
function processString(input) {
if (typeof input !== "string" || input.length === 0) {
return "Invalid input";
}
// Convert to uppercase
let upperCaseStr = input.toUpperCase();
// Count vowels
let vowelCount = 0;
let vowels = "aeiouAEIOU";
console.log("Uppercase:", upperCaseStr);
console.log("Reversed:", reversedStr);
console.log("Number of vowels:", vowelCount);
}
// Example usage
processString("hello world");
18. Write a JavaScript function to generate and print the first n Fibonacci numbers using a
loop. The function should take n as input.
Ans:
This function takes n as input and generates the first n Fibonacci numbers using a loop.
Program
function generateFibonacci(n) {
if (n <= 0) {
console.log("Please enter a positive integer");
return;
}
// Example usage
generateFibonacci(10);
Explanation
Output
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
19. Write a JavaScript function that takes an array of numbers as input and returns the
sum of all elements.
Ans:
This function takes an array of numbers as input and returns the sum of all elements.
Program
function sumArray(arr) {
if (!Array.isArray(arr) || arr.length === 0) {
return "Invalid input";
}
let sum = 0;
return sum;
}
// Example usage
let numbers = [10, 20, 30, 40, 50];
console.log("Sum of array elements:", sumArray(numbers));
Explanation
Output
Sum of array elements: 150