Top Javascript Questions

Q (1): What is difference between document.getElementById() and document.querySelector()?

  • document.getElementById()

Returns an element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

element = document.getElementById(id);
  • document.querySelector()

Returns the first matching Element node within the node's subtree. If no matching node is found, null is returned.

element = document.querySelector(selectors);
  • document.querySelectorAll()

Returns a NodeList containing all matching Element nodes within the node's subtree, or an empty NodeList if no matches are found.

element = document.querySelectorAll(selectors);

Note: querySelector() is more useful when we want to use more complex selectors.

<div align="right"> <b><a href="#">↥ back to top</a></b> </div>


Q (2): When to use reduce(), map(), foreach() and filter() in JavaScript?

  • forEach()

It takes a callback function and run that callback function on each element of array one by one.

Basically forEach works as a traditional for loop looping over the array and providing array elements to do operations on them.

var arr = [10, 20, 30];

arr.forEach(function (elem, index){
   console.log(elem + ' comes at ' + index);
})

Output

10 comes at 0
20 comes at 1
30 comes at 2
  • filter()

The main difference between forEach() and filter() is that forEach just loop over the array and executes the callback but filter executes the callback and check its return value. If the value is true element remains in the resulting array but if the return value is false the element will be removed for the resulting array.

Note: filter does not update the existing array it will return a new filtered array every time.

var arr = [10, 20, 30];

var result = arr.filter(function(elem){
    return elem !== 20;
})
console.log(result)

Output

[10, 30]
  • map()

map() like filter() & forEach() takes a callback and run it against every element on the array but whats makes it unique is it generate a new array based on your existing array.

Like filter(), map() also returns an array. The provided callback to map modifies the array elements and save them into the new array upon completion that array get returned as the mapped array.

var arr = [10, 20, 30];

var mapped = arr.map(function(elem) {
    return elem * 10;
});
console.log(mapped)

Output

[100, 200, 300]
  • reduce()

reduce() method of the array object is used to reduce the array to one single value.

var arr = [10, 20, 30];

var sum = arr.reduce(function(sum, elem) {
    return sum + elem;
});
console.log(sum); // Output: 60

<div align="right"> <b><a href="#">↥ back to top</a></b> </div>


Q (3): What is Hoisting in JavaScript?

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

Example 01: Variable Hoisting

console.log(message); // output : undefined
var message = "The variable Has been hoisted";

The above code looks like as below to the interpreter,

var message;
console.log(message);
message = "The variable Has been hoisted";

Example 02: Function Hoisting

function hoist() {
  a = 20;
  var b = 100;
}

hoist();

console.log(a);
/*
Accessible as a global variable outside hoist() function
Output: 20
*/

console.log(b);
/*
Since it was declared, it is confined to the hoist() function scope.
We can't print it out outside the confines of the hoist() function.
Output: ReferenceError: b is not defined
*/

All declarations (function, var, let, const and class) are hoisted in JavaScript, while the var declarations are initialized with undefined, but let and const declarations remain uninitialized.

console.log(a);
let a = 3;

// Output: ReferenceError: a is not defined

They will only get initialized when their lexical binding (assignment) is evaluated during runtime by the JavaScript engine. This means we can’t access the variable before the engine evaluates its value at the place it was declared in the source code. This is what we call Temporal Dead Zone, A time span between variable creation and its initialization where they can’t be accessed.

Note: JavaScript only hoists declarations, not initialisation

<div align="right"> <b><a href="#">↥ back to top</a></b> </div>


Q (4): What are closures?

A closure is the combination of a function and the lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables. The closure has three scope chains

  • Own scope where variables defined between its curly brackets
  • Outer function’s variables
  • Global variables
function Welcome(name) {
  var greetingInfo = function(message) {
    console.log(message+' '+name);
  }
  return greetingInfo;
}
var myFunction = Welcome('John');
myFunction('Welcome '); // Output: Welcome John
myFunction('Hello Mr.'); // output: Hello Mr.John

As per the above code, the inner function greetingInfo() has access to the variables in the outer function Welcome() even after outer function has returned.

<div align="right"> <b><a href="#">↥ back to top</a></b> </div>


Q (5): How do you clone an object in JavaScript?

Using the object spread operator ..., the object own enumerable properties can be copied into the new object. This creates a shallow clone of the object.

const obj = { a: 1, b: 2 }
const shallowClone = { ...obj }

With this technique, prototypes are ignored. In addition, nested objects are not cloned, but rather their references get copied, so nested objects still refer to the same objects as the original. Deep-cloning is much more complex in order to effectively clone any type of object (Date, RegExp, Function, Set, etc) that may be nested within the object.

Other alternatives include:

  • JSON.parse(JSON.stringify(obj)) can be used to deep-clone a simple object, but it is CPU-intensive and only accepts valid JSON (therefore it strips functions and does not allow circular references).
  • Object.assign({}, obj) is another alternative.
  • Object.keys(obj).reduce((acc, key) => (acc[key] = obj[key], acc), {}) is another more verbose alternative that shows the concept in greater depth.

<div align="right"> <b><a href="#">↥ back to top</a></b> </div>


Q (6): What are the possible ways to create objects in JavaScript?

a.) Object constructor: The simpliest way to create an empty object is using Object constructor. Currently this approach is not recommended.

 var object = new Object();

b.) Object create method: The create method of Object creates a new object by passing the prototype object as a parameter

 var object = Object.create(null);

c.) Object literal syntax: The object literal syntax is equivalent to create method when it passes null as parameter

 var object = {};

d.) Function constructor: Create any function and apply the new operator to create object instances,

 function Person(name) {
  var object = {};
  object.name = name;
  object.age = 26;
  return object;
 }
 var object = new Person("Alex");

e.) Function constructor with prototype: This is similar to function constructor but it uses prototype for their properties and methods,

function Person(){}
Person.prototype.name = "Alex";
var object = new Person();

This is equivalent to an instance created with an object create method with a function prototype and then call that function with an instance and parameters as arguments.

function func {};

new func(x, y, z);

// **(OR)**

// Create a new instance using function prototype.
var newInstance = Object.create(func.prototype)

// Call the function
var result = func.call(newInstance, x, y, z),

// If the result is a non-null object then use it otherwise just use the new instance.
console.log(result && typeof result === 'object' ? result : newInstance);

f.) ES6 Class syntax: ES6 introduces class feature to create the objects

class Person {
 constructor(name) {
    this.name = name;
 }
}

var object = new Person("Alex");

g.) Singleton pattern: A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance and this way one can ensure that they don't accidentally create multiple instances.

var object = new function() {
  this.name = "Alex";
}

<div align="right"> <b><a href="#">↥ back to top</a></b> </div>


Q (7): What are the javascript data types?

Below are the list of javascript data types available

  1. Number
  2. String
  3. Boolean
  4. Object
  5. Undefined

<div align="right"> <b><a href="#">↥ back to top</a></b> </div>


Q (8): What are global variables?

Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable

msg = "Hello" // var is missing, it becomes global variable

The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.

<div align="right"> <b><a href="#">↥ back to top</a></b> </div>


Q (9): What is variable shadowing in javascript?

Variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed.

If there is a variable in the global scope, and you'd like to create a variable with the same name in a function. The variable in the inner scope will temporarily shadow the variable in the outer scope.

var val = 10;

function Hoist(val) {
    alert(val);
}

Hoist(20);

Output

20

<div align="right"> <b><a href="#">↥ back to top</a></b> </div>


Q (10): What is an event flow?

Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event each of its parent elements first, starting at the top with the global window object.

There are two ways of event flow

  • Top to Bottom(Event Capturing)
  • Bottom to Top (Event Bubbling)

<div align="right"> <b><a href="#">↥ back to top</a></b> </div>