0% found this document useful (0 votes)
18 views

Css 4-6

Uploaded by

luxurypointhub
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)
18 views

Css 4-6

Uploaded by

luxurypointhub
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/ 20

Here are the answers to the questions you asked:

1. Arithmetic and Logical Operators in JavaScript

Arithmetic Operators:

+ (Addition)

- (Subtraction)

* (Multiplication)

/ (Division)

% (Modulus)

++ (Increment)

-- (Decrement)

Logical Operators:

&& (Logical AND)

|| (Logical OR)

! (Logical NOT)

2. Features of JavaScript (5 features)

Dynamic Typing: JavaScript allows variables to hold different data types at different times.
Interpreted Language: JavaScript is interpreted, meaning it is executed directly in the browser without prior
compilation.

Object-Oriented: JavaScript supports object creation with properties and methods.

Event Handling: JavaScript can respond to user actions like clicks, keypresses, etc.

Cross-Browser Compatibility: JavaScript runs on all modern web browsers without requiring additional plugins.

3. Use of Dot Syntax in JavaScript

Dot syntax is used to access properties and methods of objects.

Example:

var person = {

name: "John",

age: 25

};

console.log(person.name); // Accessing the "name" property

4. Difference Between prompt() and alert() (3 Differences)

prompt():

Accepts input from the user.

Returns the value entered by the user.

Example: var name = prompt("Enter your name");

alert():
Displays a message box.

Does not accept user input.

Example: alert("Hello!");

5. Use of Getters and Setters

Getters: Used to get the value of a property.

Setters: Used to set the value of a property.

Example:

var person = {

firstName: "John",

lastName: "Doe",

get fullName() {

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

},

set fullName(name) {

var parts = name.split(" ");

this.firstName = parts[0];

this.lastName = parts[1];

};

6. JavaScript to Display First 20 Even Numbers

document.write("First 20 even numbers: <br>");


for (var i = 1; i <= 40; i++) {

if (i % 2 === 0) {

document.write(i + "<br>");

7. Explanation of Terms

Object Name: The name used to refer to an object in JavaScript.

Property: A value associated with an object (like name or age).

Method: A function that belongs to an object.

Dot Syntax: Used to access properties or methods of an object (e.g., person.name).

8. JavaScript to Calculate Squares of 1 to 10 Using while Loop

var i = 1;

while (i <= 10) {

console.log("Square of " + i + " is " + i * i);

i++;

9. Explanation of Tokens

++a;: Increments the value of a by 1 before using it.

document.bgColor;: Refers to the background color of the document.

10. Syntax and Explanation of prompt() Method

Syntax:
prompt(message, defaultValue);

Explanation: prompt() displays a dialog box that prompts the user for input. message is the text displayed to the
user, and defaultValue is optional.

11. Ways to Display Output in JavaScript

console.log(): Prints to the browser console.

document.write(): Writes output to the HTML document.

alert(): Displays output in an alert box.

12. JavaScript to Reverse Array Elements

var arr = [1, 2, 3, 4, 5];

arr.reverse();

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

13. Syntax and Use of with Clause

Syntax:

with (object) {

// Statements

Use: Simplifies code by allowing you to reference an object’s properties without repeatedly specifying the
object name.

14. JavaScript Program to Check Prime Number


var num = parseInt(prompt("Enter a number: "));

var isPrime = true;

if (num === 1) {

isPrime = false;

} else {

for (var i = 2; i <= Math.sqrt(num); i++) {

if (num % i === 0) {

isPrime = false;

break;

alert(isPrime ? "Prime number" : "Not a prime number");

15. Explanation of for-in Loop

Use: The for-in loop iterates over the properties of an object.

Example:

var person = { name: "John", age: 30 };

for (var key in person) {

console.log(key + ": " + person[key]);

16. Role of <script> Tag

Purpose: Embeds JavaScript code within an HTML document.

Example:

<script>
alert("Hello, World!");

</script>

17. Definition and Syntax of Array

Definition: An array is a collection of elements stored in a single variable.

Syntax: var arr = [1, 2, 3];

18. charAt() and charCodeAt() Examples

charAt(): Returns the character at a specified index.

Example: "Hello".charAt(1) → 'e'

charCodeAt(): Returns the Unicode of the character at a specified index.

Example: "Hello".charCodeAt(1) → 101

19. toUpperCase() and toLowerCase() Examples

toUpperCase(): Converts a string to uppercase.

Example: "hello".toUpperCase() → "HELLO"

toLowerCase(): Converts a string to lowercase.

Example: "HELLO".toLowerCase() → "hello"


20. indexOf() Example

Use: Finds the index of the first occurrence of a value in a string.

Example: "Hello".indexOf("e") → 1

21. Use of Dot Syntax Example

Dot Syntax: Used to access object properties.

Example:

var car = { make: "Toyota", model: "Camry" };

console.log(car.model); // Output: "Camry"


1. **Object as Associative Array in JavaScript**:

In JavaScript, an object can be used as an associative array (also known as a dictionary). The keys are strings,
and they are used to access values associated with them. Here's an example:

```javascript

let student = {

name: "John",

age: 20,

grade: "A"

};

// Accessing properties using key names

console.log(student["name"]); // Output: John

```

In this example, `student` is an object with keys `name`, `age`, and `grade`, each associated with a specific
value.

---

2. **JavaScript Function to Count Vowels in a Given String**:

```javascript

function countVowels(str) {

let vowels = 'aeiouAEIOU';

let count = 0;

for (let char of str) {

if (vowels.includes(char)) {

count++;

return count;

}
console.log(countVowels("Hello World")); // Output: 3

```

This function iterates through the string, checks each character against a list of vowels, and increments the
count accordingly.

---

3. **Difference between `concat()` and `join()` Methods of Array**:

| Aspect | `concat()` | `join()` |

|----------------------------|------------------------------------|-----------------------------------|

| **Purpose** | Combines two or more arrays | Joins all array elements into a string |

| **Return Type** | Returns a new array | Returns a string |

| **Original Array** | Does not modify the original array | Does not modify the original array|

| **Syntax** | `array1.concat(array2)` | `array.join(separator)` |

| **Combines Arrays** | Yes, it combines multiple arrays | No, just joins elements of one array |

| **Separator** | No separator required | Requires a separator for joining |

---

4. **Querying, Setting, and Deleting Properties in JavaScript**:

- **Querying Properties**: Access a property using dot notation or bracket notation.

```javascript

let person = { name: "Alice", age: 25 };

console.log(person.name); // Output: Alice

console.log(person["age"]); // Output: 25

```

- **Setting Properties**: You can add new properties or modify existing ones by assigning values.

```javascript

person.city = "New York"; // Adds new property 'city'

person.name = "Bob"; // Modifies 'name' property

console.log(person);

```
- **Deleting Properties**: Use the `delete` keyword to remove a property from an object.

```javascript

delete person.age; // Removes the 'age' property

console.log(person);

```

---

5. **JavaScript to Generate Armstrong Numbers Between 1 and 100**:

```javascript

function isArmstrong(num) {

let sum = 0;

let temp = num;

while (temp > 0) {

let digit = temp % 10;

sum += Math.pow(digit, 3);

temp = Math.floor(temp / 10);

return sum === num;

function generateArmstrongNumbers() {

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

if (isArmstrong(i)) {

console.log(i);

generateArmstrongNumbers(); // Output: 1, 153 (Note: Only 1 between 1 and 100)

```

This script checks each number within the range 1 to 100 to see if it's an Armstrong number by summing the
cubes of its digits and comparing the result to the original number
1. Write a JavaScript program which compute, the average marks of the following students
Then, this average is used to determine the corresponding grade.

// Array of student marks

let marks = [80, 77, 88, 95, 68];

// Function to calculate the average of an array of numbers

function calculateAverage(arr) {

let total = 0;

for (let i = 0; i < arr.length; i++) {

total += arr[i];

return total / arr.length;

}
// Function to determine grade based on average marks

function determineGrade(average) {

if (average < 60) {

return "F";

} else if (average < 70) {

return "D";

} else if (average < 80) {

return "C";

} else if (average < 90) {

return "B";

} else {

return "A";

// Compute the average marks

let averageMarks = calculateAverage(marks);

// Determine the grade

let grade = determineGrade(averageMarks);

// Output the average and grade

console.log("Average Marks: " + averageMarks);

console.log("Grade: " + grade);.

Here are simple, easy-to-understand JavaScript solutions for each of the tasks:

---

### 7. Replace a Specified Value in a String

This replaces a word in a string with another word.

```javascript

let sentence = "I love apples";

let newSentence = sentence.replace("apples", "bananas");

console.log(newSentence); // Output: I love bananas


```

---

### 8. Input a String from the User and Calculate Its Length

This prompts the user to enter a string and then calculates its length.

```javascript

let userInput = prompt("Enter a string:");

console.log("The length of the string is: " + userInput.length);

```

---

### 9. Check if a String is a Palindrome

This checks if a string reads the same forwards and backwards.

```javascript

function isPalindrome(str) {

let reversed = str.split('').reverse().join('');

return str === reversed;

let word = prompt("Enter a word:");

if (isPalindrome(word)) {

console.log(word + " is a palindrome.");

} else {

console.log(word + " is not a palindrome.");

```

---

### 10. Convert Character to Unicode and Vice Versa, Display Data Type

This converts a character to its Unicode value and vice versa, and also shows its data type.

```javascript

let char = prompt("Enter a character:");


let unicode = char.charCodeAt(0);

console.log("Unicode of " + char + ": " + unicode);

console.log("Data type of Unicode: " + typeof unicode);

let charFromUnicode = String.fromCharCode(unicode);

console.log("Character from Unicode: " + charFromUnicode);

console.log("Data type of Character: " + typeof charFromUnicode);

```

---

### 11. Demonstrate All Bitwise Operators

This demonstrates bitwise operations using simple numbers.

```javascript

let a = 5; // 0101 in binary

let b = 3; // 0011 in binary

console.log("a & b: " + (a & b)); // AND

console.log("a | b: " + (a | b)); // OR

console.log("a ^ b: " + (a ^ b)); // XOR

console.log("~a: " + (~a)); // NOT

console.log("a << 1: " + (a << 1)); // Left shift

console.log("a >> 1: " + (a >> 1)); // Right shift

```

---

### 12. Find and Display the Number of Duplicate Values in an Array

This finds and counts duplicate values in an array.

```javascript

let arr = [1, 2, 2, 3, 4, 4, 5];

let duplicates = {};

arr.forEach((item) => {

duplicates[item] = (duplicates[item] || 0) + 1;

});
for (let key in duplicates) {

if (duplicates[key] > 1) {

console.log(key + " appears " + duplicates[key] + " times.");

```

---

### 13. Count the Number of Vowels in a Given String

This counts vowels in a string.

```javascript

function countVowels(str) {

let vowels = 'aeiouAEIOU';

let count = 0;

for (let char of str) {

if (vowels.includes(char)) {

count++;

return count;

let input = prompt("Enter a string:");

console.log("Number of vowels: " + countVowels(input));

```

---

### 14. Add Element to Array, Sort, and Display It

This takes 10 numbers, adds a new one, sorts the array, and displays the result.

```javascript

let numbers = [];

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


let num = parseInt(prompt("Enter number " + (i + 1) + ":"));

numbers.push(num);

let newNum = parseInt(prompt("Enter a new number to add:"));

numbers.push(newNum);

numbers.sort((a, b) => a - b);

console.log("Sorted numbers: " + numbers);

```

---

### 15. Demonstrate Getter and Setter

This demonstrates using getter and setter in JavaScript.

```javascript

let person = {

firstName: "John",

lastName: "Doe",

get fullName() {

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

},

set fullName(name) {

let parts = name.split(" ");

this.firstName = parts[0];

this.lastName = parts[1];

};

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

person.fullName = "Jane Smith";

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

```

---
### 16. Classify Age Group Using Nested Switch-Case

This classifies a person's age into a group.

```javascript

let age = parseInt(prompt("Enter your age:"));

switch (true) {

case (age >= 0 && age <= 12):

console.log("Child");

break;

case (age >= 13 && age <= 19):

console.log("Teenager");

break;

case (age >= 20 && age <= 64):

switch (true) {

case (age <= 39):

console.log("Young Adult");

break;

case (age <= 64):

console.log("Middle-Aged Adult");

break;

break;

case (age >= 65):

console.log("Senior");

break;

default:

console.log("Invalid age.");

```

---

### 17. Sort Employees by Salary and Display Top 3

This sorts employees by salary and displays the top 3.

```javascript
let employees = [

{ name: "John", salary: 60000 },

{ name: "Jane", salary: 80000 },

{ name: "Bob", salary: 50000 },

{ name: "Alice", salary: 90000 },

{ name: "Tom", salary: 70000 }

];

employees.sort((a, b) => b.salary - a.salary);

console.log("Top 3 highest paid employees:");

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

console.log(employees[i].name + ": $" + employees[i].salary);

```

---

### 18. Capitalize First Letter of Each Word in a Sentence

This capitalizes the first letter of each word in a sentence.

```javascript

function capitalizeWords(sentence) {

return sentence.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');

let sentence = prompt("Enter a sentence:");

console.log(capitalizeWords(sentence));

```

---

### 19. Function Definition Expression for Calculating Area of a Circle

This calculates the area of a circle using a function expression.

```javascript

let calculateArea = function(radius) {

return Math.PI * radius * radius;


};

let radius = parseFloat(prompt("Enter the radius of the circle:"));

console.log("Area of the circle: " + calculateArea(radius));

```

---

### 20. Demonstrate `shift()`, `unshift()`, `pop()`, and `push()`

This shows how to use these array methods.

```javascript

let arr = [1, 2, 3, 4];

// shift(): removes the first element

arr.shift();

console.log(arr); // Output: [2, 3, 4]

// unshift(): adds an element to the beginning

arr.unshift(0);

console.log(arr); // Output: [0, 2, 3, 4]

// pop(): removes the last element

arr.pop();

console.log(arr); // Output: [0, 2, 3]

// push(): adds an element to the end

arr.push(5);

console.log(arr); // Output: [0, 2, 3, 5]

```

These JavaScript snippets are simple, easy to understand, and demonstrate how to work with different functions
and features in JavaScript.

You might also like