Javascript Advanced Topics & Problems Solving
Truthy and Falsy Values
All values are truthy unless only without these.
List of Falsy values in JavaScript:
- False
- Null
- Undefined
- 0
- Nan
- Empty template string
Null vs Undefined
In JavaScript, undefined is a type, whereas null an object.
undefined It means a variable declared, but no value has been assigned a value.
Example :
const demo;
alert(demo);
null Whereas, null in JavaScript is an assignment value. You can assign it to a variable.
Example :
const demo = null;
alert(demo);
Double Equals (==) vs Triple Equal (===)
When using double equals . we are testing for loose equality .
77 == ‘’77'’ // False
When using Triple equals . we are testing both the type and the value are comparing.
5 === 5 // True
Map, Filter, Reduce, Find
Map() Methods : Map returns an array with the same length
Filter() Methods : Filter as the name implies, it returns an array with less items than the original array
Reduce() Methods : Reduce returns a single value
Find() Methods : Find returns the first items in an array that satisfies a condition
Bind, Call, Apply
Bind( ) : this methods create a new function and sets this key word to the object
Call ( ) : this method sets this keyword inside the function & immediately executes.
Apply ( ) : this method is similar to call method . this methods accepts an array arguments instead separated values
Calculate Factorial in a Number
function factorial(n) {
var fact = 1;
for (var i = 1; i <= n; i++) {
fact = fact * i;
} return fact;
}
var result = factorial(6);
console.log(result);
Calculate Factorial in a Recursive Function
If the number is 0 then its value will be one. And if the number is greater than zero, then subtract 1 from the number and multiply that number. If the number is a bit then its value will be one.
function factorial(n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n — 1);
}}
var result = factorial(10);
console.log(result);
Create a Fibonacci Series
function fibonacci(n) {
var fibo = [0, 1];
for (var i = 2; i <= n; i++) {
fibo[i] = fibo[i — 1] + fibo[i — 2];
} return fibo;
}
var result = fibonacci(12);
console.log(result);
Fibonacci Element in a 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);
Check a Number is a Prime or not
If you divide the number by 0, the remainder is 0. Then the number is not a prime number. And if the number is not divisible by 0, then the number is a prime number.
function isPrime(n) {
for (i = 2; i < n; i++) {
if (n % i == 0) {
return ‘Not a prime number’;
}
}
return ‘Your Number is a Prime Number’;
}
var result = isPrime(139);
console.log(result);