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

Javascript code

Uploaded by

aowladhussain99
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)
6 views

Javascript code

Uploaded by

aowladhussain99
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/ 7

// 1.

Reverse a String
let str = 'hello';
let reversedStr = str.split('').reverse().join('');
console.log(reversedStr);

// 2. Check if a string is a palindrome


let str = 'racecar';
let isPalindrome = str === str.split('').reverse().join('');
console.log(isPalindrome);

// 3. Find the maximum number in an array


let arr = [1, 3, 2, 8, 5];
let max = Math.max(...arr);
console.log(max);

// 4. Find the minimum number in an array


let arr = [1, 3, 2, 8, 5];
let min = Math.min(...arr);
console.log(min);

// 5. Sum of all elements in an array


let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce((sum, num) => sum + num, 0);
console.log(sum);

// 6. Count vowels in a string


let str = 'hello world';
let count = 0;
for (let char of str) {
if ('aeiou'.includes(char.toLowerCase())) count++;
}
console.log(count);

// 7. Count words in a string


let str = 'This is a sentence';
let wordCount = str.split(' ').length;
console.log(wordCount);
// 8. Fibonacci sequence
let n = 5;
let a = 0, b = 1;
for (let i = 2; i <= n; i++) {
let temp = a + b;
a = b;
b = temp;
}
console.log(b);

// 9. Find the index of an element in an array


let arr = [1, 2, 3, 4, 5];
let element = 3;
let index = arr.indexOf(element);
console.log(index);

// 10. Check if a number is even or odd


let num = 4;
let result = (num % 2 === 0) ? 'Even' : 'Odd';
console.log(result);

// 11. Factorial of a number


let num = 5;
let result = 1;
for (let i = 2; i <= num; i++) {
result *= i;
}
console.log(result);

// 12. Palindrome number


let num = 121;
let str = num.toString();
let isPalindrome = str === str.split('').reverse().join('');
console.log(isPalindrome);

// 13. Convert Celsius to Fahrenheit


let celsius = 30;
let fahrenheit = (celsius * 9 / 5) + 32;
console.log(fahrenheit);
// 14. Find the length of a string
let str = 'hello';
let length = str.length;
console.log(length);

// 15. Replace all occurrences of a character


let str = 'hello world';
let replacedStr = str.split('o').join('x');
console.log(replacedStr);

// 16. Remove duplicates from an array


let arr = [1, 2, 3, 4, 1, 2];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr);

// 17. Sort an array in ascending order


let arr = [3, 1, 4, 2, 5];
arr.sort((a, b) => a - b);
console.log(arr);

// 18. Check if a number is prime


let num = 7;
let isPrime = num > 1;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
isPrime = false;
break;
}
}
console.log(isPrime);

// 19. Sum of digits in a number


let num = 123;
let sum = num.toString().split('').reduce((acc, digit) => acc
+ Number(digit), 0);
console.log(sum);
// 20. Simple calculator (add, subtract, multiply, divide)
let a = 10, b = 5, operation = 'add';
let result;
switch (operation) {
case 'add':
result = a + b;
break;
case 'subtract':
result = a - b;
break;
case 'multiply':
result = a * b;
break;
case 'divide':
result = a / b;
break;
default:
result = 'Invalid operation';
}
console.log(result);

21.Javascript Error handling


Code:
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero!");
}
return a / b;
}

try {
let result = divide(10, 0);
} catch (error) {
console.error(error.message); // "Cannot divide by zero!"
}
Asynchronous:
22.Callback Functions
Code:
function fetchData(callback) {
setTimeout(() => {
const data = { id: 1, name: 'John' };
callback(data); // Callback function is executed after
2 seconds
}, 2000);
}

function processData(data) {
console.log("Processing data:", data);
}

fetchData(processData); // The `processData` function is passed


as a callback

23.Promises
Code:
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { id: 1, name: 'John' };
resolve(data); // Promise resolves with data
}, 2000);
});
}

fetchData()
.then(data => {
console.log("Data received:", data); // Data is
available here
})
.catch(error => {
console.error("Error:", error); // Handle any errors
that occur
});
24.Asynch/Await
Code:
async function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { id: 1, name: 'John' };
resolve(data); // Resolve the promise after 2
seconds
}, 2000);
});
}

async function process() {


try {
const data = await fetchData(); // Wait until the
promise resolves
console.log("Data received:", data);
} catch (error) {
console.error("Error:", error); // Catch any errors
}
}

process();

25.Arrow functions
Code:
// Arrow Function
const multiply = (a, b) => {
const result = a * b;
return result;
};

// Regular Function
function multiply(a, b) {
const result = a * b;
return result;
}

console.log(multiply(3, 4)); // Output: 12


26.

You might also like