Explain Map, Reduce and Filter functions.

Map, Reduce and Filter are three functions which operate on a given array of values.

  • Map function works like a projection, where we can project each value from the input set into some transformed output.
  • It takes a callback function which has two parameters - the current value and the index of the current value and expects a return value from the callback.
let arr = [1, 2, 3, 4, 5];
let result2 = arr.map(function (current, index) {
    return current % 2;
});
// output:
[ 1, 0, 1, 0, 1 ]
  • Reduce function works like an aggregate function, where we can create an aggregation from a given input set.
  • It takes a callback function which has three parameters - the previous value, the current value and the current index and expects a return value from the callback, which is applied onto the next array element iteration.
let result1 = arr.reduce(function (prev, current) {
    console.log(`${prev}, ${current}`);
    return prev + current;
});
// output:
1, 2
3, 3
6, 4
10, 5
result1: 15
  • Filter function is an extraction function where the input array is filtered based on a condition.
  • It takes a callback function which has two parameters - the current value and the current index and expects a boolean return value which represents whether the current element satisfies the condition or not.
let result3 = arr.filter(function (current, index) {
    return current % 2 === 0;
});
// output:
[ 2, 4 ]

How can you extract the id attribute of all the elements in the document with JavaScript?

We can do it in three steps.

  1. Pull all the elements in the document irrespective of their Tag.
  2. Loop through all the Elements and see if the element has an attribute id
  3. If exists collect the attribute value into the output array
<!DOCTYPE html>
<html>
<body id="myBody">
    <div id="mainContainer" class="container-fluid">
        <div id="firstRow" class="row">
            <div id="fullCol" class="col-md-12">
                <h1 id="headingText">Hello World!</h1>
                <p id="subHeadingText">
                This is some sample text you're viewing on the Page.</p>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        (function () {
            let elements = document.getElementsByTagName("*");
            let ids = [];
            for (let i = 0; i < elements.length; i++) {
                let element = elements[i];
                if (element.id) {
                    ids.push(element.id);
                }
            }
            console.log(JSON.stringify(ids));
        })();
    </script>
</body>
</html>

output:
["myBody","mainContainer","firstRow","fullCol","headingText","subHeadingText"]

What is closure in Javascript?

  • In Javascript, a closure can be imagined as a concept of a function scope within a function.
  • The global execution context can be treated as a whole function in which all the script contents are present, and when we run the script the global function is called.
(function () {
    let k = 1;
    function kd() {
        console.log(`value of k is ${k}`);
    }
    kd();
})();

output:
value of k is 1
  • the inner functions present in this function can access all the variables that are defined in the outer scope and can modify them.
  • interestingly, these variables are still available even after the outer function has been executed and removed from memory.
function outer() {
    let counter = 0;
    function inner() {
        counter++;
        return counter;
    }
    return inner;
}

let instance = outer();
console.log(instance());
console.log(instance());
console.log(instance());

output:
1
2
3
  • In the above code block, the outer function is called only once, while when we call the inner function multiple times the variable counter which is native to the outer function is modified by the inner function and value persists.
  • This is conceptually similar to the context of methods and properties in a class where the methods can access and modify the variables of the class in an Object Oriented Language.

What is hoisting in JavaScript?

  • In Javascript, Hoisting is a concept in which Javascript brings all the variables declarations to the top of the script during execution.
  • This means that if a variable is initialized at some part of the script while being accessed before its definition is valid and doesn't throw an error.
  • But the assignment of variables happen at their original places which means that although variables are available before their actual place of declaration, their value is undefined.
console.log(`The value of x before is ${x}`);
var x = 10;
console.log(`The value of x after is ${x}`);

output:
The value of x before is undefined
The value of x after is 10
  • variables declared using var keyword in the global execution context are "hoisted", which is why the above code works without issue.
  • let keyword on the other hand by its design doesn't allow this to happen
console.log(`The value of x before is ${x}`);
let x = 10;
console.log(`The value of x after is ${x}`);

output:
console.log(`The value of x before is ${x}`);
                                        ^
ReferenceError: Cannot access 'x' before initialization

What is the difference between double equals (==) and triple equals (===) ?

In JavaScript, double equal operator (==) stands for value compare. The operands on either sides are converted into a common type and are compared for their values.

// JS converts the right type to equivalent left type
// 5 == '5'
// 5 == number('5') == 5
// result is true
5 == '5' 

the triple operator (===) stands for both value and type compare. The operands are not type converted and instead are looked for their type match as well.

5 === '5' // result is false since we're comparing a number and a string