0% found this document useful (0 votes)
5 views19 pages

fs

JavaScript is a high-level, interpreted programming language primarily used for web development, differing from Java in its execution, typing, and usage scope. Key features include variable declaration methods (var, let, const), data types (Number, String, Boolean, Object), and control structures (if-else, switch-case). The document also covers array creation, loops, functions, and object creation methods in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views19 pages

fs

JavaScript is a high-level, interpreted programming language primarily used for web development, differing from Java in its execution, typing, and usage scope. Key features include variable declaration methods (var, let, const), data types (Number, String, Boolean, Object), and control structures (if-else, switch-case). The document also covers array creation, loops, functions, and object creation methods in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

1. Define JavaScript. How is it different from Java?

JavaScript (JS) is a high-level, interpreted programming language primarily used for


creating dynamic and interactive web pages. It is a lightweight, multi-paradigm language
that supports event-driven, functional, and object-oriented programming. JavaScript runs
in web browsers and enables client-side interactivity, such as updating content dynamically,
handling user input, and making asynchronous requests.

Difference Between JavaScript and Java

Feature JavaScript Java


Type Interpreted language Compiled language
Runs in JVM (Java Virtual
Platform Runs in web browsers (client-side)
Machine)
Used for web, desktop, mobile,
Usage Primarily used for web development
and enterprise applications
Syntax Loosely typed (dynamic typing) Strongly typed (static typing)
Runs directly in the browser (via the Needs to be compiled into
Execution
JavaScript engine) bytecode before execution
Single-threaded with event-driven, Multi-threaded with built-in
Concurrency asynchronous programming (via callbacks concurrency support (via
& promises) threads)
Object
Prototype-based Class-based
Model
Key Takeaways
• JavaScript is not related to Java; they just share a similar name due to marketing
strategies.
• JavaScript is mainly used for front-end and web-based applications, whereas Java is a
general-purpose language used in a wide range of applications.
• JavaScript is dynamically typed and interpreted, while Java is statically typed and
compiled.

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

// z = 40; // TypeError: Assignment to constant variable

const person = { name: "Alice" };


person.name = "Bob"; // Allowed (object properties can be changed)
console.log(person.name); // Bob

// person = {}; // TypeError: Assignment to constant variable

Key Differences Summary:


Feature var let const

Scope Function Block Block

Yes (initialized Yes (not Yes (not


Hoisting initialized)
as undefined) initialized)

Re- Not Allowed


Allowed Not Allowed
declaration
Not Allowed
Reassignment Allowed Allowed (except object
properties)

When to Use What?


• Use const by default, unless you need to reassign the variable.
• Use let if you need reassignment.
• Avoid var unless maintaining older code.

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.

4.How do you create an array in JavaScript? Demonstrate with an example.

In JavaScript, you can create an array using one of the following methods:

1. Using Square Brackets (Recommended)

javascript

CopyEdit

let fruits = ["Apple", "Banana", "Cherry"];


console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]

2. Using the Array Constructor

javascript

CopyEdit

let numbers = new Array(1, 2, 3, 4, 5);

console.log(numbers); // Output: [1, 2, 3, 4, 5]

3. Creating an Empty Array and Adding Elements

javascript

CopyEdit

let cars = [];

cars[0] = "Toyota";

cars[1] = "Honda";

console.log(cars); // Output: ["Toyota", "Honda"]

The preferred way is using square brackets [] as it is more concise and readable.

5. Differentiate between for loop and while loop in JavaScript.

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.

Example of for Loop:


javascript
CopyEdit
for (let i = 0; i < 5; i++) {
console.log(i); // Outputs: 0, 1, 2, 3, 4
}

Example of while Loop:


6. javascript
7. CopyEdit
8. let i = 0;
9. while (i < 5) {
10. console.log(i); // Outputs: 0, 1, 2, 3, 4
11. i++;
}

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.

6. Write a JavaScript function to find the factorial of a given number.

function factorial(n) {

if (n < 0) return "Factorial not defined for negative numbers";

let fact = 1;

for (let i = 1; i <= n; i++) {

fact *= i;

return fact;

// Taking user input

let num = parseInt(prompt("Enter a number to find its factorial:"));

if (!isNaN(num)) {

console.log(`Factorial of ${num} is ${factorial(num)}`);

} else {

console.log("Please enter a valid number.");

7. Explain how JavaScript objects are created. Illustrate with an example using object
properties and methods.

In JavaScript, objects are created in several ways, such as:

1. Using Object Literals


2. Using the new Object() Constructor
3. Using Constructor Functions
4. Using ES6 Classes
5. Using Object.create() Method

1. Using Object Literals

This is the simplest and most common way to create objects.

javascript

CopyEdit

let person = {

firstName: "John",

lastName: "Doe",

age: 30,

fullName: function() {

return this.firstName + " " + this.lastName;

};

console.log(person.firstName); // Output: John

console.log(person.fullName()); // Output: John Doe

2. Using the new Object() Constructor

Another way to create an object is by using the Object constructor.

javascript

CopyEdit

let person = new Object();

person.firstName = "Jane";

person.lastName = "Smith";

person.age = 25;
person.fullName = function() {

return this.firstName + " " + this.lastName;

};

console.log(person.fullName()); // Output: Jane Smith

3. Using Constructor Functions

This method is useful when creating multiple objects of the same type.

javascript

CopyEdit

function Person(firstName, lastName, age) {

this.firstName = firstName;

this.lastName = lastName;

this.age = age;

this.fullName = function() {

return this.firstName + " " + this.lastName;

};

let person1 = new Person("Alice", "Brown", 28);

console.log(person1.fullName()); // Output: Alice Brown

4. Using ES6 Classes

A modern and structured way to create objects.

javascript

CopyEdit

class Person {
constructor(firstName, lastName, age) {

this.firstName = firstName;

this.lastName = lastName;

this.age = age;

fullName() {

return `${this.firstName} ${this.lastName}`;

let person2 = new Person("Michael", "Johnson", 35);

console.log(person2.fullName()); // Output: Michael Johnson

5. Using Object.create()

This method creates an object with a specified prototype.

javascript

CopyEdit

let prototypePerson = {

fullName: function() {

return this.firstName + " " + this.lastName;

};

let person3 = Object.create(prototypePerson);

person3.firstName = "Emma";
person3.lastName = "Wilson";

console.log(person3.fullName()); // Output: Emma Wilson

8. Describe the different types of string methods available in JavaScript with examples.

String Methods in JavaScript

JavaScript provides various string methods to manipulate and work with strings. Here are
some commonly used string methods:

1. length (Property)

• Returns the number of characters in a string.


• Example:

js

CopyEdit

let text = "Hello, World!";

console.log(text.length); // Output: 13

2. toUpperCase() & toLowerCase()

• Converts a string to uppercase or lowercase.


• Example:

js

CopyEdit

let str = "JavaScript";

console.log(str.toUpperCase()); // Output: "JAVASCRIPT"

console.log(str.toLowerCase()); // Output: "javascript"

3. charAt(index)

• Returns the character at the specified index.


• Example:

js

CopyEdit

let text = "Hello";

console.log(text.charAt(1)); // Output: "e"

4. indexOf(substring) & lastIndexOf(substring)

• indexOf() finds the first occurrence of a substring.


• lastIndexOf() finds the last occurrence of a substring.
• Example:

js

CopyEdit

let message = "Hello, world! Hello again!";

console.log(message.indexOf("Hello")); // Output: 0

console.log(message.lastIndexOf("Hello")); // Output: 14

5. slice(start, end)

• Extracts a portion of a string from start to end (excluding end).


• Example:

js

CopyEdit

let str = "JavaScript";

console.log(str.slice(0, 4)); // Output: "Java"

console.log(str.slice(-6)); // Output: "Script"

6. substring(start, end)

• Similar to slice(), but doesn’t accept negative indexes.


• Example:

js

CopyEdit

let str = "JavaScript";

console.log(str.substring(0, 4)); // Output: "Java"

7. replace(oldValue, newValue)

• Replaces the first occurrence of oldValue with newValue.


• Example:

js

CopyEdit

let text = "Hello World";

console.log(text.replace("World", "JavaScript")); // Output: "Hello JavaScript"

8. split(separator)

• Splits a string into an array based on a given separator.


• Example:

js

CopyEdit

let sentence = "apple,banana,grape";

console.log(sentence.split(",")); // Output: ["apple", "banana", "grape"]

9. trim()

• Removes whitespace from both ends of a string.


• Example:

js

CopyEdit
let text = " Hello World! ";

console.log(text.trim()); // Output: "Hello World!"

10. concat()

• Joins two or more strings together.


• Example:

let str1 = "Hello";

let str2 = "World";

console.log(str1.concat(" ", str2)); // Output: "Hello World"

9. Explain if-else and switch-case statements in JavaScript with examples.

JavaScript provides if-else and switch-case statements to control the flow of execution based
on conditions.

1. if-else Statement

The if-else statement is used to execute code based on a condition.

Syntax:

js

CopyEdit

if (condition) {

// Code to execute if condition is true

} else {

// Code to execute if condition is false

Example:

js

CopyEdit
let age = 18;

if (age >= 18) {

console.log("You are eligible to vote.");

} else {

console.log("You are not eligible to vote.");

Output: "You are eligible to vote."

if-else if Example:

js

CopyEdit

let marks = 85;

if (marks >= 90) {

console.log("Grade: A");

} else if (marks >= 75) {

console.log("Grade: B");

} else {

console.log("Grade: C");

Output: "Grade: B"

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:

// Code to execute if expression === value1

break;

case value2:

// Code to execute if expression === value2

break;

default:

// Code to execute if no cases match

Example:

js

CopyEdit

let day = "Monday";

switch (day) {

case "Monday":

console.log("Start of the work week!");

break;

case "Friday":

console.log("Weekend is coming!");

break;

case "Sunday":
console.log("It's a holiday!");

break;

default:

console.log("It's a regular day.");

Output: "Start of the work week!"

Key Differences Between if-else and switch-case

Feature if-else switch-case


Condition Type Works with boolean expressions (`>, <, ==, &&,
Execution Speed Slower for multiple conditions Faster for multiple cases
Use Case Best for range-based conditions Best for fixed values

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";
}

let max = arr[0]; // Assume the first element is the largest


for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i]; // Update max if a larger value is found
}
}
return max;
}

// 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];

// Find the largest and smallest numbers using Math functions


let largest = Math.max(...numbers);
let smallest = Math.min(...numbers);

// Print the results


console.log("Numbers:", numbers);
console.log("Largest Number:", largest);
console.log("Smallest Number:", smallest);

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();

// Reverse the string


let reversedStr = upperCaseStr.split("").reverse().join("");

// Count the number of vowels


let vowelCount = (upperCaseStr.match(/[AEIOU]/g) || []).length;

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;
}

let fibSeries = [];


let a = 0, b = 1;

for (let i = 0; i < n; i++) {


fibSeries.push(a); // Add current Fibonacci number to array
let next = a + b; // Calculate next Fibonacci number
a = b; // Update a
b = next; // Update b
}

console.log(`First ${n} Fibonacci numbers:`, fibSeries);


}

// Taking user input


let num = parseInt(prompt("Enter the number of Fibonacci numbers to generate:"));
if (!isNaN(num)) {
generateFibonacci(num);
} else {
console.log("Invalid input. Please enter a valid number.");
}

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));

You might also like