10 Tricky things of JavaScript
1. Differnce between double equal and triple equal.
ans: when we check two operands are equal or not then we use double equal.
there can be one operand is string and other operand number or two operand are strings or two operand are numbers.
when we check two operands are equal or not and their data-type are equal or not then we use triple equal.
2. Find the largest elemnt of an array.
var array=[1,2,3,4,5];
var largest= array[0];
for (let i = 1; i < array.length; i++) {
if(array[i]>largest){
largest=array[i];
}
}
console.log(largest);
3. Remove duplicate item from an array.
var array=[1,2,3,4,5,5];
var newArray=[];
for (let i = 1; i < array.length; i++) {
var item= array[i];
var index=newArray.indexOf(item);
if(index==-1){
newArray.push(item);
}
}
console.log(newArray);
4. Count the number of words in a string.
var song="amar sonar bangla ami tomay valo bashi";
var count = 0;
for (let i = 0; i < song.length; i++) {
const element = song[i];
if(element==" " && song[i-1]!=" "){
count++;
}
}
count++;
console.log(count);
5. Reverse a string
function reverseString(str){
var reverse="";
for (let i = 0; i < str.length; i++) {
var element = str[i];
reverse = element + reverse;
}
return reverse;
}
var statement="amr sonar bangla ami tomay valobashi";
var myStatement = reverseString(statement);
console.log(myStatement);
6. Calculate Factorial of a number using for loop
function factorialNumber(num){
if(num==0 || num == 1){
return 1;
}
else{
return num * factorialNumber(num-1);
}
}
var result=factorialNumber(5);
console.log(result);
7. Check whether a number is a prime Number or not
function primeNumber(num){
for (let i = 2; i < num; i++) {
if(num%i == 0){
return "notprimeNumber";
}
}
return "PrimeNumber";}
var result=primeNumber(90);
console.log(result);
8. Create a Fibonacci series using a for loop
function fibonacci(n) {
var fibo = [0, 1];
for (var i = 2; i <= n; i++) {
fibo[i] = fibo[i - 1] + fibo[i - 2];
fibo.push(fibo[i]);
}
return fibo;
}
var result = fibonacci(12);
console.log(result);
9. Calculate Factorial in a Recursive function
function factorial(n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
var result = factorial(10);
console.log(result);
10. Create Fibonacci series in recursive way
function fibonacci(n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}var result = fibonacci(10);
console.log(result);