Question : example of Map Reduce
Answer :
Question : What is IIFE?
Answer : Immediately Invoked function expression e.g. (function(){}()). usually pronounces as "effy".
Question : Why the script tag should be added at the bottom or before the end of the body tag?
Answer : It helps the html page to render quickly without even downloading the script which may be getting downloaded from the slow CDN.
there are other alternative like async and defer as well, which are supported primarily on new browsers.
<script src="bower_components/angular/angular.min.js" defer></script>
<script src="bower_components/jquery/dist/jquery.min.js" defer></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js" defer ></script>
<script src="script.js" defer></script>
</body>
Question : what is instanceof operator in javascript?
Answer : The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
The instanceof operator tests the presence of constructor.prototype in object's prototype chain.
Below is the code example to demonstrate the same
Question : What is typeof operator?
Answer : The typeof operator returns a string indicating the type of the unevaluated operand.
Question : Look at the below code
Explain what is happening over here?
Answer : the function cat is defined and it can accept color parameter which will initialize color variable for the current context.
Now when we call cat("white") then runtime will try to find the current context which is by default global when it is node environment, and window when the code is ran in browser, so this is referring to global or window based on the runtime environment.
Next let cuteCat = new cat("Blue"), in this scenario we are calling the constructor for the cat hence the returned object or created object will be the current context and hence color variable will associated with the cuteCat object.
Question : What is call function ?
Answer : The call function is the function which helps the function to change the execution context which leads to determine what should be the current "this", or in other words the call can override the default this for the current function.
e.g.
Question : What is the use of the Object.getOwnPropertyDescriptor(cuteCat,"color"))
Answer : this will be able to give you the default values, of its internal properties.
Question : How can you make the internal value non modifiable / constant?
Answer: object.defineProperty(cuteCat, 'color', {writable: false});
Question : What will be the output of the below code?
Answer : The output will be "blue" for both the console.log, since we have made {writable : false}, before modifying the value of the color, it will not throw any error but the value will not get changed.
Question : What if we "use strict" mode for the above scenario?
Answer : We will get the error, /Users/vcmishra/learn/coding/test.js:9
cuteCat.color = "SuperBlue";
^
TypeError: Cannot assign to read only property 'color' of object '#<cat>'
Question : How can iterate over the property name?
Answer :
Question : How to create a getter and setter for a property.
Answer :
Question : Can you create an method call which can be chained?
Answer :
Another example using the this keyword.
Question : Give an example of the inheritance using the prototype.
Answer :
So last line is very important which proves that Cat prototype is refering to the Animal prototype as after the assignment of the prototype of Animal to Cat, we added another function to the Animal Prototype, and still we are able to call the new method from the cat instance object.
Question : demonstrate the scope?
Answer :
line one start with the global scope, now foo is also declared in the bar(), but the scope is local as it is declared along with the var keyword, so changed will not affect the value of foo in the global scope.
As baz() is declared inside the bar() and also executed when bar() executed , now when the baz() is executed then it also initializes the zaz variable, pay attention the zaz is not declared with the var keyword so it assumes that, it must be declared at the parent scope, so it tries to find it in the scope of the bar() which is parent of baz(), but there is no variable declared at the bar() with the name zaz, so it tries to see if there is any variable declared at the parent of the bar(), which turns out to be global, so that leads to creation of the new variable named zaz at the global scope. hence it can be accessed from outside as it is now part of global scope, even though it was declared way inside of the baz().
Question : Show using the IIFE, that we can modularize the code?
Answer : following is the self explanatory code to demonstrate the same.
Question : What will be the output and why?
reason : the function declaration are hoisted so it will be placed at the top during the compilation phase, so after compilation the code may look like as follows.
Question what will be the output of the below code?
reason : the function expression are not hoisted and hence it will be not placed at the top, so at the line one runtime is not able to see if there is variable which may be function, the point to be noted is var is always hoisted so the variable declaration will be definitely hoisted, so it will assume that the variable declared may be just a data holder.
so after compilation phase the above code is converted to the following
So you can see that, the hoisting works partially, it is just informing the compiler to hoist the variable and that's good enough to at least inform that a variable is declared but no value is assigned to it.
So if you modify the code.
Then you will not get any TypeError as the var is hoisted, so runtime knows there is a variable and it is safe to execute this line.
Question : What is the output of below code.
Answer : It will display "I am displaying",
Reason : as the display is without the var keyword, so certainly it will not be hoisted, but it will be added to the global scope, so when display() is called, then it will look for curent scope, which by default global, and it will find the definition of it and hence execute it.
Ideally the above code should have run same way as it has ran when we declared the var, but problem here is at line one, display is searched in global scope, but due no var keyword with the display, hoisting was not done for the display, and it is still not yet the part of the global scope.
What is call()?
Answer : Look at the below code, so the job of the call is to associate the execution context, by default, display execution context is global but it can be changed by using the .call(), pass the object along the call function to change the this pointer to the current passed object.
Can we make the call() without the argument?
Answer : Yes we can do that and we will not get any error, and it will be same as without the .call()
i.e
Question : What is "arguments"?
Answer : every function at the time of execution holds a meta variable known as arguments, it holds the information regarding caller and calee and with what arguments it has made the call.
e.g.
What is apply?
Answer : The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).
You can assign a different this object when calling an existing function. this refers to the current object, the calling object. With apply, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
apply is very similar to call(), except for the type of arguments it supports. You use an arguments array instead of a list of arguments (parameters). With apply, you can also use an array literal, for example, func.apply(this, ['eat', 'bananas']), or an Array object, for example, func.apply(this, new Array('eat', 'bananas')).
You can also use arguments for the argsArray parameter. arguments is a local variable of a function. It can be used for all unspecified arguments of the called object. Thus, you do not have to know the arguments of the called object when you use the apply method. You can use arguments to pass all the arguments to the called object. The called object is then responsible for handling the arguments.
Since ECMAScript 5th Edition you can also use any kind of object which is array-like, so in practice this means it's going to have a property length and integer properties in the range (0..length-1). As an example you can now use a NodeList or a custom object like { 'length': 2, '0': 'eat', '1': 'bananas' }.
Question : Give example of the casting in the javascript?
Answer :
Question : How can you change window location?
Answer : We can use the window.location.href property to change the same.
Question: What are the different data type in Javascript?
Answer :
(() => {
let aNumberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let sum = aNumberArray.map(data => data * 2)
.reduce((ongoing, data) => ongoing + data);
console.log(sum);
})()
Question : What is IIFE?
Answer : Immediately Invoked function expression e.g. (function(){}()). usually pronounces as "effy".
Question : Why the script tag should be added at the bottom or before the end of the body tag?
Answer : It helps the html page to render quickly without even downloading the script which may be getting downloaded from the slow CDN.
there are other alternative like async and defer as well, which are supported primarily on new browsers.
<script src="bower_components/angular/angular.min.js" defer></script>
<script src="bower_components/jquery/dist/jquery.min.js" defer></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js" defer ></script>
<script src="script.js" defer></script>
</body>
Question : what is instanceof operator in javascript?
Answer : The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
The instanceof operator tests the presence of constructor.prototype in object's prototype chain.
Below is the code example to demonstrate the same
var p = {};
console.log(p instanceof Object); //true
p = function () {};
console.log(p instanceof Function); //true
p = 123;
console.log(p instanceof Number);
// false, as it is not of type Number(), it is primitive number
p = new Number(123);
console.log(p instanceof Number); // true
p = "hello"; // false, as it is not of type Number(), it is primitive String
console.log(p instanceof String);
p = new String("hello");
console.log(p instanceof String); // true
p = new Date();
console.log(p instanceof Date); // true
p = ["a","b","c","d"];
console.log(p instanceof Array); // true
p = new Array("a","b","c","d");
console.log(p instanceof Array); // true
Question : What is typeof operator?
Answer : The typeof operator returns a string indicating the type of the unevaluated operand.
var p = {};
console.log(typeof p ); //object
p = undefined;
console.log(typeof p ); //undefined
p = function () {};
console.log(typeof p); //function
p = 123;
console.log(typeof p); //number
p = NaN;
console.log(typeof p); //number
p = new Number(123);
console.log(typeof p ); // object
p = "hello"; //String
console.log(typeof p );
p = new String("hello");
console.log(typeof p ); // object
p = new Date();
console.log(typeof p ); // object
p = ["a","b","c","d"];
console.log(typeof p ); // object
p = new Array("a","b","c","d");
console.log(typeof p ); // object
p = true;
console.log(typeof p ); // boolean
Question : Look at the below code
function cat(color){
this.color = color
}
cat("white");
let cuteCat = new cat("Blue");
console.log(cuteCat.color);
console.log(global.color);
--Output-----
Blue
white
Explain what is happening over here?
Answer : the function cat is defined and it can accept color parameter which will initialize color variable for the current context.
Now when we call cat("white") then runtime will try to find the current context which is by default global when it is node environment, and window when the code is ran in browser, so this is referring to global or window based on the runtime environment.
Next let cuteCat = new cat("Blue"), in this scenario we are calling the constructor for the cat hence the returned object or created object will be the current context and hence color variable will associated with the cuteCat object.
Question : What is call function ?
Answer : The call function is the function which helps the function to change the execution context which leads to determine what should be the current "this", or in other words the call can override the default this for the current function.
e.g.
global.bar = "hello";
//if it is browser var bar = "hello";
function display() {
console.log(this.bar);
}
var obj = {bar: "no hello"};
var obj2 = {bar: "one more no hello"};
display();
display.call(obj);
display.call(obj2);
Question : What is the use of the Object.getOwnPropertyDescriptor(cuteCat,"color"))
Answer : this will be able to give you the default values, of its internal properties.
{
value: 'Blue',
writable: true,
enumerable: true,
configurable: true
};
Question : How can you make the internal value non modifiable / constant?
Answer: object.defineProperty(cuteCat, 'color', {writable: false});
Question : What will be the output of the below code?
function cat(color) {
this.color = color}
let cuteCat = new cat("Blue");
console.log(cuteCat.color);
Object.defineProperty(cuteCat, 'color', {writable: false});
cuteCat.color = "SuperBlue";
console.log(cuteCat.color);
Answer : The output will be "blue" for both the console.log, since we have made {writable : false}, before modifying the value of the color, it will not throw any error but the value will not get changed.
Question : What if we "use strict" mode for the above scenario?
Answer : We will get the error, /Users/vcmishra/learn/coding/test.js:9
cuteCat.color = "SuperBlue";
^
TypeError: Cannot assign to read only property 'color' of object '#<cat>'
Question : How can iterate over the property name?
Answer :
function Cat(color) {
this.name = "pussy";
this.color = "white";
this.tail = "short";
this.age = 3;
}
let meow = new Cat("white");
for(let propertyName in meow){
console.log(propertyName);
}
name
color
tail
age
Question : How to create a getter and setter for a property.
Answer :
function Cat(color) {
this.name = "pussy";
this.color = "white";
this.tail = "short";
this.age = 3;
}
let meow = new Cat("white");
Object.defineProperty(meow, 'fullName', {
get : function () {
return `Name of cat is ${this.name} of color ${this.color} has ${this.tail}
tail and is ${this.age} years old`;
}
, set : function(){
}
});
Question : Can you create an method call which can be chained?
Answer :
function util() {
return {
chained :"",hello: function () {
this.chained += " Hello";return this;},hi: function () {
this.chained += " Hi";return this;},show: function () {
console.log(this.chained);this.chained =""}
};}
let ux = new util();ux.hi().hello().show();//hi helloux.hello().hi().show();//hello hi
Another example using the this keyword.
global.bar = "do you know";
function foo() {
this.baz = "bazzing";
this.hi = function () {
this.baz += "hi";
return this
};
this.hello = function () {
this.baz += "hello";
return this
};
this.show = function () {
console.log(this.baz);
this.baz = ""
};
}
var hell = new foo();
hell.hi().hello()
Question : Give an example of the inheritance using the prototype.
Answer :
function Animal() {//Adding a prototype function speak
this.__proto__.Speak = ()=>("Speak");
}
function Cat(){
console.log("cat");}
// assigning the Animal prototype object to the cat, now prototype object of Animal is
// same as prototype of the cat.
Cat.prototype = Object.create(Animal.prototype);
let X = new Animal();
let Y = new Cat();
console.log(X.Speak()); //Output :: Speak
console.log(Y.Speak()); // Output :: Speak
Animal.prototype.scratch = ()=>("Scratch");
console.log(Y.scratch()); // Output :: scratch
So last line is very important which proves that Cat prototype is refering to the Animal prototype as after the assignment of the prototype of Animal to Cat, we added another function to the Animal Prototype, and still we are able to call the new method from the cat instance object.
Question : demonstrate the scope?
Answer :
let foo = "foo"; //for global scope
function bar() {
//current bar function scope
var foo = "kick";
function baz(loo) {
var foo = loo;//foo from the bar scope
console.log(foo); //output :: koo
zaz = "yay";
}
baz("koo");
console.log(foo);//output :: kick
}
bar();
console.log(foo);//output : foo
console.log(zaz);//output : yay
line one start with the global scope, now foo is also declared in the bar(), but the scope is local as it is declared along with the var keyword, so changed will not affect the value of foo in the global scope.
As baz() is declared inside the bar() and also executed when bar() executed , now when the baz() is executed then it also initializes the zaz variable, pay attention the zaz is not declared with the var keyword so it assumes that, it must be declared at the parent scope, so it tries to find it in the scope of the bar() which is parent of baz(), but there is no variable declared at the bar() with the name zaz, so it tries to see if there is any variable declared at the parent of the bar(), which turns out to be global, so that leads to creation of the new variable named zaz at the global scope. hence it can be accessed from outside as it is now part of global scope, even though it was declared way inside of the baz().
Question : Show using the IIFE, that we can modularize the code?
Answer : following is the self explanatory code to demonstrate the same.
var t = (function some(){
return {
hi : ()=> console.log("Hi"),
hello : ()=> console.log("hello"),
ok : ()=> console.log("ok")
}
});
var q = (function some(){
return {
hi : ()=> console.log("nHi"),
hello : ()=> console.log("nhello"),
ok : ()=> console.log("nok")
}
});
var p = new t();
var qt = new q();
p.hi(); //Hi
p.hello(); //hello
p.ok(); //ok
qt.hi(); //nHi
qt.hello(); //nhllo
qt.ok();//nok
Question : What will be the output and why?
display();
function display(){
console.log("I am displaying");
}Answer : It will be displayed as the "I am displaying",
reason : the function declaration are hoisted so it will be placed at the top during the compilation phase, so after compilation the code may look like as follows.
function display(){
console.log("I am displaying");
}
display();
Question what will be the output of the below code?
display();
var display = function (){
console.log("I am displaying");
}Answer : TypeError : display is not a function,
reason : the function expression are not hoisted and hence it will be not placed at the top, so at the line one runtime is not able to see if there is variable which may be function, the point to be noted is var is always hoisted so the variable declaration will be definitely hoisted, so it will assume that the variable declared may be just a data holder.
so after compilation phase the above code is converted to the following
var display;display();
display = function () {
console.log("I am displaying");
}
So you can see that, the hoisting works partially, it is just informing the compiler to hoist the variable and that's good enough to at least inform that a variable is declared but no value is assigned to it.
So if you modify the code.
display;var display = function () {
console.log("I am displaying");
}
Then you will not get any TypeError as the var is hoisted, so runtime knows there is a variable and it is safe to execute this line.
Question : What is the output of below code.
display = function () {
console.log("I am displaying");
}
display();
Answer : It will display "I am displaying",
Reason : as the display is without the var keyword, so certainly it will not be hoisted, but it will be added to the global scope, so when display() is called, then it will look for curent scope, which by default global, and it will find the definition of it and hence execute it.
display;
display = function () {
console.log("I am displaying");
}
//Error : display is not yet declared.
Ideally the above code should have run same way as it has ran when we declared the var, but problem here is at line one, display is searched in global scope, but due no var keyword with the display, hoisting was not done for the display, and it is still not yet the part of the global scope.
What is call()?
Answer : Look at the below code, so the job of the call is to associate the execution context, by default, display execution context is global but it can be changed by using the .call(), pass the object along the call function to change the this pointer to the current passed object.
global.bar = "hello";//if it is browser var bar = "hello";function display() {
console.log(this.bar);}
var obj = {bar: "no hello"};var obj2 = {bar: "one more no hello"};display();display.call(obj);display.call(obj2);
Can we make the call() without the argument?
Answer : Yes we can do that and we will not get any error, and it will be same as without the .call()
i.e
display.call();
// above is same as the below.display();
Question : What is "arguments"?
Answer : every function at the time of execution holds a meta variable known as arguments, it holds the information regarding caller and calee and with what arguments it has made the call.
e.g.
function greet (){
function meet(){
console.log(arguments.callee.caller.name) // greet
console.log(arguments.callee.caller.arguments) //{ '0': 'Hello' }
console.log(arguments.callee.arguments) //{ '0': 'Hi', '1': 'and', '2': 'bye' }
}
meet("Hi","and", "bye")
}
greet("Hello");
What is apply?
Answer : The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).
You can assign a different this object when calling an existing function. this refers to the current object, the calling object. With apply, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
apply is very similar to call(), except for the type of arguments it supports. You use an arguments array instead of a list of arguments (parameters). With apply, you can also use an array literal, for example, func.apply(this, ['eat', 'bananas']), or an Array object, for example, func.apply(this, new Array('eat', 'bananas')).
You can also use arguments for the argsArray parameter. arguments is a local variable of a function. It can be used for all unspecified arguments of the called object. Thus, you do not have to know the arguments of the called object when you use the apply method. You can use arguments to pass all the arguments to the called object. The called object is then responsible for handling the arguments.
Since ECMAScript 5th Edition you can also use any kind of object which is array-like, so in practice this means it's going to have a property length and integer properties in the range (0..length-1). As an example you can now use a NodeList or a custom object like { 'length': 2, '0': 'eat', '1': 'bananas' }.
var greet = function () {
console.log(this.callerName); for (var msg in arguments) {
console.info(arguments[msg], "\r"); }
};
var obj = {callerName: "objX"};
var obj2 = {callerName: "objX2"};
greet.apply(this, ["Hello", "hi", "how"]);
greet.apply(obj, ["Hello", "hi", "how"]);
greet.apply(obj2, ["Hello", "hi", "how"]);
Question : Give example of the casting in the javascript?
Answer :
var p = "123";console.log(typeof p); //string
var p = Number("123");console.log(typeof p); //number//Notice this is without new operator;
var p = Boolean("123");console.log((typeof p) , p); //boolean, any value will result to true
var p = Boolean("false");console.log((typeof p) , p); //boolean, true
var p = Date();console.log((typeof p) , p); //string, todays date, date casting doesn't work
var p = Array("21","23");console.log((typeof p) , p);//object, ['21','22'], returns array with the values initialized with the passed argument//almost same as new Array("21","23")
Question : How can you change window location?
Answer : We can use the window.location.href property to change the same.
function backToNormal() {
setTimeout(function (){
var sharkImage = window.location.href.split('#');
window.location.href = sharkImage[0];
},6000);
}
Question: What are the different data type in Javascript?
Answer : In general we have only two data type
- Primitive Data Type
- String
- Boolean
- Number
- Null
- Undefined
- Symbol
- Reference Data Type
- Arrays
- Object
- Function
- Dates
Comments
Post a Comment