General Questions Flashcards
What is strict mode and what kind of error it will give?
Strict mode
allows developers to apply more conditions so that the code is written in more organized and optimal way.
Some examples:
* Disallows global variable declaration ( without var, let or const)
* Disallows reassigning of const variables
* Duplicate param names not allowed in method
* Using with statement
* Using octal
* Declaring function in a block
“use strict”
Syntax:
What is the difference between null and undefined
Null
: It is usually used to mention of
absense of value of an object. Also the type of null is object and it needs to be assigned manually.
Undefined
: It is assigned by default and indicates that the variable is not be initialized.
It also indicated the absense of the variable it self.
What is difference between Window and Document
Window
represents entire browser window and it is parent of all elements. You can use this object to alert(), get size of window etc.
Document
which also known as Document Object Model (DOM) represents the page that is being loaded currently. You can get elements or modify them using this object. Fetch the object with window.document
What is an event flow
Event flow
means how an event initiates and progresses to all the element in the DOM.
Two types
In Event bubbling
the event starts from the target element and move up to all its parents and ends at DOM
In Event Capturing
the event starts from DOM and completes at target element.
Default one is Event bubbling
How do you redirect new page in javascript
You can use location object to redirect the user
window.location.href="newurl"
How do you loop through or enumerate javascript object
Two ways:
1. (for key in obj) then do something with key
2. let keys=Object.keys(obj); then loop over keys array
Keep in mind that above will also include keys in parent object or prototype. Use obj.hasOwnProperty(key) along with above.
What is an arguments object
- Arguments object is available inside any js function without explicitly mentioning it.
- You can use this object to get/loop through the argument being passed to function
- Keep in mind that even though the argument object has some props of array, it is not an array. You can not use push, add or slice methods of array to arguments
Example:
function hello(){ for( int i=0;i<arguments.length;i++){ console.log("Argument"+ ${i}+"=>"+${arguments[i]}`); } } hello(1,2,3);
What is a polyfill?
- A polyfill is a way to provide backward compatibility in the browsers that does not support new features (i.e ECMAScript 2016).
- In this cases you can provide fallback mechanism so that the feature work on all the browsers.
Example:
if(!Array.prototype.includes){ Array.prototype.includes=function(element){ for(int i=0;i<this.length;i++){ if(this[i]==element){ return true; } } return false; } }
What is App Shell model?
-
App Shell Model
is used in PWA to give quick UI to the end user the show static content while dynamic content gets loaded. - This is helpful in slow network situation which ensures that the user has something to interect with
- When App Shell is in place it gets loaded first with all static HTML, CSS and JS. After that the dynamic content gets loaded with Server side rendering and Client side JS
What is Tree Shaking?
-
Tree shaking
is a way to remove unwanted or unused code and make an optimal bundle for production. - Tree Shaking algorithm uses module approach and discards unused modules to create small build
What is eval?
With eval()
you can pass any code as string and it will be executed by js.
Example:
let x=1; let y=5; let exp='x+y'; let result=eval(exp); console.log(result);
Use of eval should be avoided as it can lead to code injestion attacks, slow performances.
How do you detect mobile browser?
- Most browsers send
User Agent
in request so you can match the user agent string with known mobile browsers like below
if('/Android|webOS|iPad/'.test(navigator.userAgent)){ //mobile browser } else{ // not a mobile browser }
Difference between “__proto__” and prototype
` __proto__ ` is used to get the reference of the prototype object of the current object. By using this you can check what methods are available with the prototype of current object.
prototype
on the other hand is used to enhance the current constructor to add new methods or variables for existing function
What is freeze method?
Object.freeze
method is used to freeze the object/arrays, in other words to make them immutable.
"use strict" let obj={ "name": "bac"}; Object.freeze(obj); obj.age=23; // This will give error.
What is a rest parameter?
- A
rest parameter
is a special function parameter that can have unlimited number of arguments. - These arguments are stored in the form of an array.
- Rest parameter is the last parameter of the function
Example:
function sum(...args){ int sum=0; for(let num of args){ sum+=num; } return sum } sum(1,2); sum(1,2,3,4);
If you don’t use rest param as last param in functon you will get // SyntaxError: Rest parameter must be last formal parameter error.
What is spread operator?
-
Spread operator
is mainly used with array or an object. It is somewhat reverse of rest parameter. - Purpose of this operator
for array
is to pass the elements of the array as individual elements in a function call.
Example:
const sum=(a,b,c)=>a+b+c; let arr=[1,2,3] sum(...arr) // 6
- And in case of
Object
spread operator can be used to copy properties of one object to another hence to enhance the existing object.
Example:
let obj1= {name:"abc"} let obj2={...obj1, city:"Pune"}
What is a proxy object
Proxy object
is used to to define default behavior or fallback mechanism for the given object.
Example:
let handler= (obj,prop)=>{ if(prop in obj){ return obj[prop] } else{ return 100; //default value } }; let proxy=new Proxy({}, handler); proxy.a=10; proxy.b=200; console.log(`${proxy.a}`);// 10 console.log(`${proxy.b}`);// 200 console.log(`${proxy.c}`);// 100 , default value
What are the differences between freeze and seal methods
Object.freeze
freeze the entire object so that you can not modify its existing properties and you can not add new properties.
Object.seal
on the other hand only prevents adding new properties. You can modify existing ones.
What is WeakSet
WeakSet
is similar to Set which is used to store unique objects. However, it has some limitations.
1. You can only store premitive objects ( int or strings are not allowed)
2. It will not prevent an object being garbage collected. If an object in the weakset is assign to null ref, it will be automatically deleted and garbage collected
Example:
const myWeakSet = new WeakSet(); const obj1 = { name: 'John' }; const obj2 = { name: 'Mary' }; const obj3 = { name: 'Bob' }; myWeakSet.add(obj1); myWeakSet.add(obj2); console.log(myWeakSet.has(obj1)); // true console.log(myWeakSet.has(obj3)); // false obj1 = null; // remove strong reference to obj1 // At this point, obj1 has no more strong references // and can be garbage collected, even though it's still in myWeakSet console.log(myWeakSet.has(obj1)); // false
What is anonymous function?
Anonymous function
is a function having no name and usually assigned to a variable.
Examples:
let func1=function(){ console.log("Func1"); } func1(); // Func1 let funcArrow= ()=>{ console.log("funcArrow"); } funcArrow() // funcArrow
What are the accessors?
Accessors
are the getters and setters of the object.
* By introducing the accessors you can encaspsulate the setting and getting of the object and get control over it.
* However, you can not enforce the use of the accessors same as you do in java with private keyword.
Example:
var user = { firstName: "John", lastName : "Abraham", language : "en", get lang() { return this.language; }, set lang(lang) { this.language = lang; } }; console.log(user.lang); // getter access lang as en user.lang = 'fr'; console.log(user.lang); // setter used to set lang as fr
What is Object.defineProperty
Object.defineProperty
is used to to add or modify property of the object. Along with this you can also decide if the property is writable, enumerable or configurable.
* writable: if the property can be mutated
* configurable: if the property can be deleted or redefined
* enumerable: if the property can be visible in Object.keys() or for … in …
Example:
let obj={name:"abc"} Object.defineProperty(obj,"newProp",{ value: 123, writable: true, configurable: false, enumerable: true } delete obj.newProp //error
You can also use getters and setters in the Object.defineProperty like below
const obj = { firstName: 'John', lastName: 'Doe' }; Object.defineProperty(obj, 'fullName', { get: function() { return this.firstName + ' ' + this.lastName; }, set: function(value) { const parts = value.split(' '); this.firstName = parts[0]; this.lastName = parts[1]; } }); console.log(obj.fullName); // Output: "John Doe" obj.fullName = "Jane Smith"; console.log(obj.firstName); // Output: "Jane" console.log(obj.lastName); // Output: "Smith"
How do you define multiple properties to an object?
By using Object.defineProperties
Example:
let newObj={}; Object.defineProperties(newObj,{ newProp1:{ value:1, configurable:true }, newProp2:{ value:2, configurable:false } });