fs
fs
2. Explain the difference between var, let, and const in JavaScript with examples.
n JavaScript, var, let, and const are used for declaring variables, but they have
different behaviors in terms of scope, hoisting, and reassignment. Let’s break them
down:
1. var
• Function-scoped: var is limited to the function in which it is declared.
• Hoisting: Variables declared with var are hoisted to the top of their scope but not
initialized.
• Re-declaration: Allowed.
• Reassignment: Allowed.
Example:
javascript
CopyEdit
function testVar() {
if (true) {
var x = 10; // x is declared inside block but accessible outside
}
console.log(x); // 10 (no block scope)
}
testVar();
2. let
• Block-scoped: let is limited to the block ({}) in which it is declared.
• Hoisting: Variables declared with let are hoisted but not initialized (Temporal Dead
Zone until initialized).
• Re-declaration: Not allowed in the same scope.
• Reassignment: Allowed.
Example:
javascript
CopyEdit
function testLet() {
if (true) {
let y = 20; // y is block-scoped
console.log(y); // 20
}
// console.log(y); // ReferenceError: y is not defined
}
testLet();
3. const
• Block-scoped: Like let, const is limited to the block in which it is declared.
• Hoisting: Same as let (hoisted but not initialized).
• Re-declaration: Not allowed.
• Reassignment: Not allowed (but mutable objects declared with const can be
modified).
Example:
javascript
CopyEdit
const z = 30;
console.log(z); // 30
3. Discuss different data types in JavaScript? List and explain any four.
In JavaScript, data types define the kind of data that variables can hold. JavaScript
has primitive and non-primitive (reference) data types.
Four Important Data Types in JavaScript
1. Number
o The Number type represents both integer and floating-point values.
o Example:
js
CopyEdit
let age = 25; // Integer
let price = 99.99; // Float
o Special values: Infinity, -Infinity, and NaN (Not-a-Number).
2. String
o The String type is used to represent text. Strings are enclosed in single ('),
double (") or backticks (`).
o Example:
js
CopyEdit
let name = "John Doe";
let greeting = `Hello, ${name}!`; // Template literal
3. Boolean
o The Boolean type represents logical values: true or false.
o Example:
js
CopyEdit
let isAdult = true;
let isStudent = false;
4. Object
o An Object is a collection of key-value pairs. It can store multiple values of
different data types.
o Example:
js
CopyEdit
let person = {
name: "Alice",
age: 30,
isEmployed: true
};
These data types help in efficient memory management and proper handling of
variables in JavaScript programs.
In JavaScript, you can create an array using one of the following methods:
javascript
CopyEdit
javascript
CopyEdit
javascript
CopyEdit
cars[0] = "Toyota";
cars[1] = "Honda";
The preferred way is using square brackets [] as it is more concise and readable.
Feature for
Loop while Loop
Used when the number of iterations is Used when the number of iterations is
Usage
known beforehand. not known in advance.
Has a predefined initialization, Only has a condition; initialization and
Structure condition, and increment/decrement in increment/decrement are done
a single line. separately.
Readability More compact and structured. More flexible but can be less readable.
Running loops based on conditions
Iterating over arrays or a known range
Best For that depend on user input or dynamic
of values.
values.
Both loops are used for iteration, but for loops are preferred when the number of iterations is
known, while while loops are used when the loop runs based on a condition.
function factorial(n) {
let fact = 1;
fact *= i;
return fact;
if (!isNaN(num)) {
} else {
7. Explain how JavaScript objects are created. Illustrate with an example using object
properties and methods.
javascript
CopyEdit
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
};
javascript
CopyEdit
person.firstName = "Jane";
person.lastName = "Smith";
person.age = 25;
person.fullName = function() {
};
This method is useful when creating multiple objects of the same type.
javascript
CopyEdit
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.fullName = function() {
};
javascript
CopyEdit
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
fullName() {
5. Using Object.create()
javascript
CopyEdit
let prototypePerson = {
fullName: function() {
};
person3.firstName = "Emma";
person3.lastName = "Wilson";
8. Describe the different types of string methods available in JavaScript with examples.
JavaScript provides various string methods to manipulate and work with strings. Here are
some commonly used string methods:
1. length (Property)
js
CopyEdit
console.log(text.length); // Output: 13
js
CopyEdit
3. charAt(index)
js
CopyEdit
js
CopyEdit
console.log(message.indexOf("Hello")); // Output: 0
console.log(message.lastIndexOf("Hello")); // Output: 14
5. slice(start, end)
js
CopyEdit
6. substring(start, end)
js
CopyEdit
7. replace(oldValue, newValue)
js
CopyEdit
8. split(separator)
js
CopyEdit
9. trim()
js
CopyEdit
let text = " Hello World! ";
10. concat()
JavaScript provides if-else and switch-case statements to control the flow of execution based
on conditions.
1. if-else Statement
Syntax:
js
CopyEdit
if (condition) {
} else {
Example:
js
CopyEdit
let age = 18;
} else {
if-else if Example:
js
CopyEdit
console.log("Grade: A");
console.log("Grade: B");
} else {
console.log("Grade: C");
2. switch-case Statement
The switch statement is used when there are multiple possible conditions for a variable.
Syntax:
js
CopyEdit
switch (expression) {
case value1:
break;
case value2:
break;
default:
Example:
js
CopyEdit
switch (day) {
case "Monday":
break;
case "Friday":
console.log("Weekend is coming!");
break;
case "Sunday":
console.log("It's a holiday!");
break;
default:
10. Write a JavaScript program to find the largest number in an array using a loop
function findLargestNumber(arr) {
if (arr.length === 0) {
return "Array is empty";
}
// Example usage
let numbers = [10, 45, 78, 23, 89, 56];
console.log("The largest number is:", findLargestNumber(numbers));
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.
Lab
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.
Lab
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.
14.Write a function isPalindrome(str) that checks if a given string is a palindrome (reads the
same backward).
Lab
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()
// 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 fruits = ["Apple", "Banana", "Cherry"];
console.log("Array:", fruits);
// Object
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
isStudent: true
};
console.log("Object:", person);
16. Write a JavaScript program to create an array of five numbers. Find and print the largest
and smallest numbers from the array.
// Create an array with five numbers
let numbers = [25, 10, 45, 5, 30];
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
function processString(input) {
// Convert to uppercase
let upperCaseStr = input.toUpperCase();
return {
uppercase: upperCaseStr,
reversed: reversedStr,
vowelCount: vowelCount
};
}
// Example usage:
let result = processString("hello world");
console.log(result);
// Output: { uppercase: 'HELLO WORLD', reversed: 'DLROW OLLEH', vowelCount: 3 }
18. Write a JavaScript function to generate and print the first n Fibonacci numbers using a
loop. The function should take n as input.
function generateFibonacci(n) {
if (n <= 0) {
console.log("Please enter a positive integer.");
return;
}
19. Write a JavaScript function that takes an array of numbers as input and returns the sum
of all elements.
function sumOfArray(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i]; // Add each element to sum
}
return sum;
}
// Example usage
let numbers = [10, 20, 30, 40, 50];
console.log("Sum of array elements:", sumOfArray(numbers));