Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Tuesday, 21 January 2025

JavaScript Hoisting


JavaScript Hoisting :

1. Functions, variables, and class definitions are hoisted to the top.

2. let and const are initialized only after they are used.

3. The most important concepts in JavaScript.

4. To avoid bugs, always declare all variables at the beginning of every scope.

Monday, 20 January 2025

Pure and Impure Functions in JavaScript.

 

JavaScript Pure and Impure Functions.

1. JavaScript Pure Functions.

    JavaScript Pure Function Without modifying value return. like predictable out value.

function add(x) {
    return x + 1;
}
console.log(add(10)); // output : 11
console.log(add(11)); // output : 12
console.log(add(12)); // output : 13

2. JavaScript Impure Functions. 

    JavaScript Impure Function value is change every time.

let x = 10;
function add() {
    return x++;
}
console.log(add()); // output : 10
console.log(add()); // output : 11
console.log(add()); // output : 12

JavaScript Spread and Rest Operators.

 


JavaScript Spread and Rest Operators.

1. JavaScript Spread Operator.

    JavaScript spread operator used for modifying or merging array.    

let a = [1,2,3,3];
let b = [4,5,6,7,3];

let output = [...a, ...b];
console.log('output--->', output);
// output : output---> [1, 2, 3, 3, 4, 5, 6, 7, 3]

2. JavaScript Rest Operator.

    JavaScript Rest Operator used for We don't know the number of parameters come in the function.

function call(...data) {
    console.log('data---->', data);    
}
call(1,2,3,4,5);
// output : data----> [ 1, 2, 3, 4, 5 ]

JavaScript Closures, Callbacks and Callback Hell, Currying.



JavaScript Closures, Callbacks and Callback Hell, Currying Function.

1. JavaScript Closures.

   Closures is the combination of a bundled function.

   Closures gives you access to an outer function's scope from an inner function.

function init() {
    var name = 'Mozilla';
    function displayName() {
        console.log('name --->', name);
        // output : name ---> Mozilla
    }
    displayName();
}
init();

2. JavaScript Callbacks.

   Function passed as an argument.

   
function test1(name, callback) {
    console.log('name---->', name);    
    callback();    
}

function test2() {
    console.log('test2---->');    
}

test1("Ankit", test2);
//output :
// name----> Ankit
// test2---->

3. JavaScript Callback Hell.

   Every callback depends / waits for the previous callback.

setTimeout(() => {
    console.log('test 1--->');
    setTimeout(() => {
        console.log('test 2--->');
    }, 2000);    
}, 5000);
// output :
// test 1--->
// test 2--->

4. JavaScript Currying Function.

function sendEmail(to) {
    return function (from) {
        return function (body) {            
            return to + ' - ' + from + ' - ' + body;
        }
    }
}

let to = sendEmail('to@gmail.com');
let from = to('from@gmail.com');
console.log(from('Body data'));
// output : to@gmail.com - from@gmail.com - Body data.

function sendEmail(to) {
    return function (from) {
        return function (body) {            
            return to + ' - ' + from + ' - ' + body;
        }
    }
}

console.log(sendEmail('to@gmail.com')('from@gmail.com')('Body data.'));
// output : to@gmail.com - from@gmail.com - Body data.

//using arrow function
const sendemail = (to) => (from) => (body) => { return to + ' - ' + from + ' - ' + body};
console.log('sendemail--->', sendemail('to@gmail.com')('from@gmail.com')('Body data.'));
// output : sendemail---> to@gmail.com - from@gmail.com - Body data.


Saturday, 18 January 2025

Javascript small practical interview questions and answers

Javascript small practical interview questions and answers.

1. Reverse string JavaScript.

let name = "Ankit";
let revName = name.split("").reverse().join("");
console.log("revName---->", revName); // output : revName----> tiknA

let revNames = "";
for(let i = name.length-1; i >= 0; i--) {
    revNames += name[i];
}
console.log("revNames---->", revNames); // output : revNames----> tiknA

2. Remove duplicate string from array JavaScript.

let cityName = ["pune", "ahmedabad", "nagpur", "pune"];
let uniqName = [...new Set(cityName)];
console.log("uniqName--->", uniqName);
// output : uniqName---> [ 'pune', 'ahmedabad', 'nagpur' ]

let uniqeCityName = [];
let filterCityName = cityName.map(x => {
    uniqeCityName.indexOf(x) === -1 && uniqeCityName.push(x);
});
console.log("uniqeCityName--->", uniqeCityName);
// output : uniqeCityName---> [ 'pune', 'ahmedabad', 'nagpur' ]

3. Swapping of two numbers JavaScript.

let a = 10, b = 20, tmp;
tmp=a; a=b; b=tmp;
console.log("a,b--->", a,b);
// output : a,b---> 20 10

let swapNumber = [a,b] = [b,a]; // Destructuring es6 method
console.log("swapNumber---->", swapNumber);
// output : swapNumber----> [ 10, 20 ]

4. Find highest and Second highest JavaScript.

let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let maxNumer = Math.max(...numArray);
console.log('maxNumer--->', maxNumer);
// output : maxNumer---> 99

let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let highestNum, secondHigh;
numArray.map(x => {
    if(!highestNum) highestNum = x;
   
    if(highestNum && x > highestNum){
        secondHigh = highestNum ;
        highestNum = x; }
    else {
        if(x > secondHigh) secondHigh = x;
    }
});
console.log('highestNum, secondHigh--->', highestNum, secondHigh);
// output : highestNum, secondHigh---> 99 33

5. Sorting array in Ascending and Descending order JavaScript.

let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];

// Sort in ascending order
let ascending = [...numArray].sort((a, b) => a - b);
console.log("ascending :", ascending);
// output : ascending : [ 1, 1, 2, 2,  3, 3, 4, 5, 6, 7, 33, 33, 99 ]

// Sort in descending order
let descending = [...numArray].sort((a, b) => b - a);
console.log("descending :", descending);
// output : descending : [ 99, 33, 33, 7, 6, 5, 4,  3, 3, 2, 2, 1, 1 ]

let sortString = ["mumbai", "pune", "ahmedabad", "botad"];
let ascStringSortFun = sortString.sort();
console.log("ascStringSortFun---->", ascStringSortFun);
// output : ascStringSortFun----> [ 'ahmedabad', 'botad', 'mumbai', 'pune' ]

let descStringSortFun = sortString.sort().reverse();
console.log("descStringSortFun---->", descStringSortFun);
// output : descStringSortFun----> [ 'pune', 'mumbai', 'botad', 'ahmedabad' ]

6. Find Even and Odd Numbers in an Array in JavaScript.

let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let evenNum = numArray.filter(x => {
    return x % 2 == 0 && x;    
});
console.log('evenNum--->', evenNum);
// output : evenNum---> [ 6, 2, 4, 2 ]

let oddNum = numArray.filter(x => {    
    return x % 2 != 0 && x;
});
console.log('oddNum--->', oddNum);
// output : oddNum---> [7,  1,  3, 99, 5, 1, 33, 33, 3]

7. Unique Values - Remove duplicates in an Array JavaScript.

let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];

let unqArr = [...new Set(numArray)];
console.log("unqArr--->", unqArr);
// output : unqArr---> [6, 7, 1, 2, 3, 99, 4, 5, 33]

let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];

let uniqeArray = [];
let filterNumArray = numArray.map(x => {
    uniqeArray.indexOf(x) === -1 && uniqeArray.push(x);
});
console.log("uniqeArray--->", uniqeArray);
// output : uniqeArray---> [ 6, 7, 1,  2, 3, 99, 4, 5, 33]

8. Find unique values from two array JavaScript.

let num1 = [1,22,33,44,55,99];
let num2 = [55,66,22];
let uniqData = [...new Set([...num1, ...num2])];
console.log('uniqData--->', uniqData);
// output : uniqData---> [1, 22, 33, 44, 55, 99, 66]

9. Find, Map, Filter and Reduce JavaScript.

// find : return only one value, otherwise return undeifned.
// map : return : true, false and array data
// filter : condition match the return array data otherwise return [] array
// reduce : use for mathematic operation

let x = [1, 2, 33, 44, 55, 66];

let findData = x.find((val) => { return val > 44 });
console.log("findData--->", findData); // return single value
// output : findData---> 55

let mapData = x.map((val, index) => { return val + 100; });
console.log("mapData--->", mapData); // return array
// output : mapData---> [ 101, 102, 133, 144, 155, 166 ]

let filterData = x.filter((val, index, array) => { return val > 22; });
console.log("filterData---->", filterData); // return array  
// output : filterData----> [ 33, 44, 55, 66 ]

let reduceSumData = x.reduce((total, val, index, array) => { return total + val; });
console.log("reduceSumData--->", reduceSumData); // return number value
// output : reduceSumData---> 201

10. Assume the output of example in JavaScript.

// ********example 1**********

console.log("1");

setTimeout(() => {
    console.log("2");
},0);

setTimeout(() => {
    console.log("3");
});

console.log("4");
// output : 1 4 2 3

// ********example 2**********

function logger(a,b,a) {
    console.log('a,b,a--->', a,b,a);
}

logger(1,2,3,4);
// output : a,b,a---> 3 2 3

// ********example 3**********

let aa = 5;
console.log('aa++--->',aa++);
// output : aa++---> 5

aa = 5;
console.log('++aa--->',++aa);
// output : ++aa---> 6

let bb = 5;
console.log('bb-- --->',bb--);
// output : bb-- ---> 5

bb = 5;
console.log('--bb --->',--bb);
// output : --bb ---> 4

// ********example 4**********

console.log(1);

for(let i=2;i<=10;i++){
  console.log(i);
}

setTimeout(() => {
  console.log(11)
}, 3000)

let promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('success')
  }, 500);
})

setTimeout(() => {
  console.log(12)
}, 500)

promise.then(res => {
  console.log(res)
})

console.log(13);

// output : 1 2 3 4 5 6 7 8 9 10 13 success 12 11

11. Callbacks - Promises - Async/Await in JavaScript.

// *******callback********
function test3(callback) {
    console.log('test3---->');
    callback();
}
function test4() {
    console.log('test4---->');
}
test3(test4);
// output :
// test3---->
// test4---->

// *******Promises***********
function test8() {
    console.log('test8--->');    
    return new Promise((resolve, reject) => {        
        resolve();
        // reject('reject error---->');
    })
}
function test9() {    
    console.log('test9--->');
}
test8().then(test9).catch(e => console.log('e--->', e));
// output :
// test8--->
// test9--->

// *******Async/Await********
async function test1() {
    console.log('test1---->');
    await test2();
}
function test2() {
    console.log('test2---->');
}
test1();
// output :
// test1---->
// test2---->

12. Event loop in JavaScript.

// ****event loop******
function test5() {
    console.log('test5---->');    
}
function test6() {
    setTimeout(() => {
        console.log('test6---->'); // execute after 5 second
    }, 5000);    
}
function test7() {
    console.log('test7---->');
}

test5();
test6();
test7();

// output :
// test5---->
// test7---->
// test6---->