General Interview Questions Flashcards
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.
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
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 : undefinedvar 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() functionOutput: 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
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 JohnmyFunction(‘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.
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.
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 functionvar 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”; }
What are the javascript data types?
There are eight basic data types in JavaScript.
String
String is used to store text. In JavaScript, strings are surrounded by quotes:
- Single quotes: ‘Hello’
- Double quotes: “Hello”
- Backticks:
Hello
Example:
//Strings const firstName = ‘John’; const lastName = “K”; const result = The names are ${firstName} and ${lastName}
;
Number
Number represents integer and floating numbers (decimals and exponentials). A number type can also be +Infinity, -Infinity, and NaN (not a number).
const number1 = 3; const number2 = 3.433; const number3 = 3e5 // 3 * 10^5 const number1 = 3/0; console.log(number1); // Infinity const number2 = -3/0; console.log(number2); // -Infinity // strings can’t be divided by numbersconst number3 = “abc”/3; console.log(number3); // NaN
BigInt
In JavaScript, Number type can only represent numbers less than (253 - 1) and more than -(253 - 1). However, if you need to use a larger number than that, you can use the BigInt data type.
A BigInt number is created by appending n to the end of an integer.
// BigInt valueconst num1 = 900719925124740998n; const num2 = 900719925124740998n; const num3 = 10; // Adding two big integersconst result1 = num1 + num2; console.log(result1); // “1801439850249481996n” // Error! BitInt and number cannot be addedconst result2 = num1 + num2 + num3; console.log(result2); // Uncaught TypeError: Cannot mix BigInt and other types
Boolean
This data type represents logical entities. Boolean represents one of two values: true or false.
const dataChecked = true; const valueCounted = false;
undefined
The undefined data type represents value that is not assigned. If a variable is declared but the value is not assigned, then the value of that variable will be undefined.
let name; console.log(name); // undefined let name = undefined; console.log(name); // undefined
null
In JavaScript, null is a special value that represents empty or unknown value.
const number = null;
Symbol
A value having the data type Symbol can be referred to as a symbol value. Symbol is an immutable primitive value that is unique.
// Two symbols with the same description const value1 = Symbol(‘hello’); const value2 = Symbol(‘hello’); let result = (value1 === value2) ? true : false; // false; // Note: Though value1 and value2 both contain ‘hello’, they are different as they are of the Symbol type.
Object
An object is a complex data type that allows us to store collections of data.
const employee = { firstName: ‘John’, lastName: ‘K’, email: ‘john.k@gmail.com’ };
What are global variables?
Global variables are declared outside of a function or declared with a window object for accessibility throughout the program (unless shadowed by locals). If you declare a variable without using var, even if it’s inside a function, it will still be seen as global:
var x = 5; // globalfunction someThing(y) { var z = x + y; console.log(z); }someThing(4); // 9console.log(x); // 5
Note:Using Undeclared Variables
- In strict mode, if you attempt to use an undeclared variable, you’ll get a reference error when you run your code.
- Outside of strict mode, however, if you assign a value to a name that has not been declared with let, const, or var, you’ll end up creating a new global variable. It will be global no matter how deeply nested within functions and blocks your code is, which is almost certainly not what you want, is bug-prone, and is one of the best reasons for using strict mode!
- Global variables created in this accidental way are like global variables declared with var: they define properties of the global object. But unlike the properties defined by proper var declarations, these properties can be deleted with the delete operator.
var x = 5; // globalfunction someThing(y) { x = 1; // still global!var z = x + y; console.log(z); }someThing(4) // 5console.log(x) // 1
var x = 5; // globalfunction someThing(y) { var x = 3; // localvar z = x + y; console.log(z); }someThing(4); // 7console.log(x); // 5
A global variable is also an object of the current scope, such as the browser window:
var dog = “Fluffy”;console.log(dog); // Fluffy;var dog = “Fluffy”;console.log(window.dog); // Fluffy
To declare JavaScript global variables inside the function, you need to use a window object. For example:
window.value = 90;
Now it can be declared inside any function and can be accessed from any function. For example:
function m() { window.value = 100; //declaring global variable by window object } function n() { console.log(window.value); //accessing global variable from other function }
It’s a best practice to minimize global variables. Since the variable can be accessed anywhere in the program, they can cause strange behavior.
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
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)
What is event bubbling?
Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element.
Example: If you click on EM, the handler on DIV runs.
<div onclick=”alert(‘The handler!’)”> <em>If you click on <code>EMcode>, the handler on <code>DIVcode> runs.em>div>
- Stopping bubbling
<body onclick=”alert(the bubbling doesn\'t reach here
)”> <button onclick=”event.stopPropagation()”>Click mebutton>body>
What is event capturing?
Event capturing is a type of event propagation where the event is first captured by the outermost element and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the inner DOM element.
What is prototype chain?
Nearly all objects in JavaScript are instances of Object. That means all the objects in JavaScript inherit the properties and methods from Object.prototype. This is called Prototype chaining.
Prototype chaining is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language. The prototype on object instance is available through Object.getPrototypeOf(object) or __proto__ property whereas prototype on constructors function is available through Object.prototype.
function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; }//Person class createdPerson.prototype.getFullName = function() { return this.firstName + “ “ + this.lastName; }// we have added getFullName method in Person’s prototype.var person = new Person(“John”, “K”, 25);// It will create an instance of the Person class> person.hasOwnProperty(“firstName”); // true> person.hasOwnProperty(“getFullName”); // false> person.getFullName(); // John K
What is the difference between Call, Apply and Bind?
a.) call()
The call() method invokes a function with a given this value and arguments provided one by one
var employee1 = {firstName: ‘John’, lastName: ‘Rodson’};var employee2 = {firstName: ‘Jimmy’, lastName: ‘Baily’};function invite(greeting1, greeting2) { console.log(greeting1 + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName+ ‘, ‘+ greeting2); } invite.call(employee1, ‘Hello’, ‘How are you?’); // Hello John Rodson, How are you?invite.call(employee2, ‘Hello’, ‘How are you?’); // Hello Jimmy Baily, How are you?
b.) apply()
Invokes the function and allows you to pass in arguments as an array
var employee1 = {firstName: ‘John’, lastName: ‘Rodson’};var employee2 = {firstName: ‘Jimmy’, lastName: ‘Baily’};function invite(greeting1, greeting2) { console.log(greeting1 + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName+ ‘, ‘+ greeting2); } invite.apply(employee1, [‘Hello’, ‘How are you?’]); // Hello John Rodson, How are you?invite.apply(employee2, [‘Hello’, ‘How are you?’]); // Hello Jimmy Baily, How are you?
c.) bind()
returns a new function, allowing you to pass in an array and any number of arguments
var employee1 = {firstName: ‘John’, lastName: ‘Rodson’};var employee2 = {firstName: ‘Jimmy’, lastName: ‘Baily’};function invite(greeting1, greeting2) { console.log(greeting1 + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName+ ‘, ‘+ greeting2); }var inviteEmployee1 = invite.bind(employee1);var inviteEmployee2 = invite.bind(employee2); inviteEmployee1(‘Hello’, ‘How are you?’); // Hello John Rodson, How are you?inviteEmployee2(‘Hello’, ‘How are you?’); // Hello Jimmy Baily, How are you?
What is the difference between == and === operators?
JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators takes type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types,
- Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
- Two numbers are strictly equal when they are numerically equal. i.e, Having the same number value. There are two special cases in this,
- NaN is not equal to anything, including NaN.
- Positive and negative zeros are equal to one another.
- Two Boolean operands are strictly equal if both are true or both are false.
- Two objects are strictly equal if they refer to the same Object.
- Null and Undefined types are not equal with ===, but equal with ==. i.e, null===undefined –> false but null==undefined –> true
Examples
0 == false // true
0 === false // false
1 == “1” // true
1 === “1” // false
null == undefined // true
null === undefined // false
‘0’ == false // true
‘0’ === false // false
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory