MAD 2 AppDev 2 Graded and Practice Merged
MAD 2 AppDev 2 Graded and Practice Merged
1. Which of the following keywords can be used to declare a variable with global
scope? [MCQ : 1 point]
A. let
B. var
C. const
D. All of the above
Answer: D
Solution: All of these can be used to create variables with global scope, if a variable is declared
with them outside a function, which is not limited to any code block.
Answer: B and C
Solution: JavaScript language is a dynamically typed language because it doesn’t require the
data type of the variable is to be specified, when it is declared. It is also a weakly typed
language, as it allows various implicit conversions, and provides a lot of flexibility.
Answer: A, B and C
Solution: JavaScript is considered a forgiving programming language, as it gives a lot of
flexibility to the user like coercion etc. JavaScript doesn’t require a semicolon to be put at the
end of each statement explicitly, as it does it on its own. Both the blocks and functions make use
of curly braces ({ }) to define their body or scope, unlike Python, which uses indentation.
4. Consider the following program, and predict the last value shown on the console?
[MCQ : 3 points]
const timer = (time) => {
let x = 1
let handlar = setInterval(() => {
console.log(2 * x)
x++
}, 1000)
setTimeout(() => {
clearInterval(handlar)
}, time)
}
timer(5000)
A. 4
B. 8
C. 5
D. 10
Answer: B
Solution: In the program given above, setInterval() function is triggered after every 1 second
(1000 milliseconds), and will terminate after waiting for 5 seconds. The first value that will be
shown on the console is 2 (after waiting for 1 second), then 4 (after waiting for 1 more second),
then 6 (after waiting for 1 more second), then 8 (after waiting for 1 more second). The
setTimeout() function will be executed after waiting for 5 seconds. Thus, the last value shown on
the console is 8.
Answer: C
Solution: Using a const keyword while creating or declaring an object will make the
reference constant. However, the properties of the object (declared with const) can still
be changed.
obj.changeName('Mohit')
console.log(obj.name)
A. undefined
B. Rohit
C. Mohit
D. null
Answer: B
Solution: Arrow function does not have “this” of its own. Arrow functions establish "this" based
on the scope the Arrow function is defined within. So, the “name” property of the “obj” object will
not change. It will remain “Rohit”.
7. What will be the output of the following program? [MCQ : 3 points]
const obj = {
name: 'Rohit',
arrowFunction: null,
normalfunction: function () {
this.arrowFunction = () => {
console.log(this.name)
}
},
}
obj.normalfunction()
obj.arrowFunction()
A. Rohit
B. Mohit
C. undefined
D. Syntax Error
Answer: A
Solution: Arrow function does not have “this” of its own. Arrow functions establish "this" based
on the scope the Arrow function is defined within. So, the value of “this” will be the “obj” object.
Because arrowFunction is defined inside the normalFunction so it will inherit the value of “this”
from normalFunction.
8. Which of the following is correct output for the following code snippet? [MCQ : 2
points]
Answer: D
Solution: setTimeout() is an asynchronous function. So, the callback function will be called once
the call stack is empty, i.e. first the synchronous codes will be executed and then asynchronous
codes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script>
setTimeout(() => {
document.getElementById('div1').style.backgroundColor = 'yellow'
}, 0)
</script>
<title>Document</title>
</head>
<body>
<div
id="div1"
style="height: 100px; width: 100px; background-color: red"
></div>
</body>
</html>
What will be the background color of an element having ID ‘div1’ in the rendered webpage
corresponding to this document? [MCQ : 2 points]
A. red
B. black
C. yellow
D. None of the above
Answer: C
Solution: setTimeout() is an asynchronous function. So, the callback function will be called once
the call stack is empty, i.e. first the synchronous codes will be executed and then asynchronous
codes. Till the time, the statement document.getElementById('div1').style.backgroundColor =
'yellow' will be executed the DOM is already built.
setTimeout(() => {
clearInterval(handler)
}, (name.length + 1) * 1000)
}
startNamePrinter('orange')
What will be the last value shown on the console after 4 seconds? [MCQ : 3 points]
A. r
B. a
C. n
D. o
Answer: C
Solution: Callback function defined as the parameter of setIntervel will be executed after each 1
second. After every 1 second, it will pop one character from the string and logs it on the
console. So, after 4 seconds, it will log character ‘n’.
Week 2 Graded Questions
Q1: Which of the following shows the correct output, if the program written below is
executed?
A. []
B. Error
C. [5, 22, 55, 75]
D. [22, 5, 55, 75]
Answer: D
Solution: The sort() method sorts the elements in the alphabetical order by default. A user
defined function can be passed as an argument to this method in order to customize the default
sorting logic.
Q2: Which of the following shows the correct output, if the program written below is
executed?
a = {
name: 'Abhi',
age: 22
};
b = [];
for (let i = 0; i < 3; i++){
b.push(a)
}
b[1].name = 'Akshay';
console.log(b[0].name);
A. Abhi
B. Akshay
C. undefined
D. ReferenceError
Answer: B
Solution: Here, the same object reference “a” is pushed thrice to an array. Hence, a change in
one element of the array will affect all other elements of the array, as all the elements are
referencing to the same object.
Q3: Which of the following shows the correct output, if the program written below is
executed?
const a = {
name: 'Abhi',
age: 22
};
b = [];
for (let i = 0; i < 3; i++){
b.push({...a})
}
b[1].name = 'Akshay';
console.log(b[0].name);
A. Abhi
B. Akshay
C. Undefined
D. ReferenceError
Answer: A
Solution: Here, a destructured version of the object reference “a” is pushed thrice to an array.
Hence, a change in one element of the array will not impact any other element of this array, as
all the elements are referencing to the different objects.
x = [1, 2, 3, 4, 5, 6]
y = [...x, 7, 8, 9]
z = y.filter((x) => x % 2 == 0)
.map((i) => i * i)
.reduce((a, i) => a + i, (a = 0))
console.log(z)
A. 100
B. 120
C. 140
D. 160
Answer: B
Solution: Here, the filter() method returns an array of the even elements from the array “y”. The
result of which is given to the map() method, which returns an array of square of elements from
the array it got from the filter() method as the result. The resultant array is then passed to the
reduce() method, which computes the final answer as 120, which further gets displayed on the
console.
const obj = {
x: 1,
y: 1,
set nums(xCommay) {
numbers = xCommay.split(',')
this.x = numbers[0]
this.y = numbers[1]
},
get nums() {
return this.x + ',' + this.y
},
xPowery: function () {
let result = 1
for (let i = 1; i <= this.y; i++) {
result = result * this.x
}
return result
},
}
obj.nums = '2,3'
console.log(obj.xPowery())
A. 6
B. 5
C. 8
D. None of the above
Answer: C
Solution: The example uses getter and setter properties of an object. The setter modifies the
properties of the object, whereas the getter returns the properties. Then, it invokes a method,
which does some computations and returns the result.
const ePowerx = {
x: 1,
n: 1,
set parameters(param) {
param = param.split(' ')
this.x = param[0]
this.n = param[1]
},
get uptoNterms() {
let result = 1
let y = 1
for (let i = 1; i < this.n; i++) {
y = y * this.x
result = result + y
}
return result
},
}
ePowerx.parameters = '2 3'
console.log(ePowerx.uptoNterms)
A. 3
B. 5
C. 7
D. 15
Answer: C
Solution Above is the logic to compute 1+x+x^{2}+x^{2}+... upto n terms and in this problem x=2
and n=3 so, the answer is 1+2+4=7.
const course = {
courseName: 'Modern Application Development 2',
courseCode: 'mad2',
}
const student = {
__proto__: course,
studentName: 'Rakesh',
studentCity: 'Delhi',
}
A. Undefined
B. Modern Application Development 2
C. Will throw syntax error
D. None of the above
Answer: B
Solution: Student object inherit from the course object so, it will have access to all the properties
of course object so, Option B is correct.
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div id="div1" style="background-color: red"></div>
</body>
<script src="script.js"></script>
</html>
script.js:
var height = 0
var width = 0
var divStyle = document.getElementById('div1').style
let res = setInterval(() => {
height += 50
width += 50
divStyle.height = height + 'px'
divStyle.width = width + 'px'
console.log(height)
}, 1000)
setTimeout(() => {
clearInterval(res)
}, 10050)
Assuming that the index.html and script.js are kept inside the same directory, then what will be
the height of the HTML element having ID ‘div1’ after 20 seconds, if rendered using a browser?
A. 500px
B. 1000px
C. 0px
D. None of the above
Answer: A
Solution: The callback function inside the setInterval will get executed every 1 second but
because after 10050 milliseconds callback function inside the setTimeout will get executed and
will clear the interval. And, the callback function inside setInterval increases the height of div by
50px, and it will run 10 times so, its final height will be 500px.
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<script src="module1.js" type="module"></script>
</head>
<body>
<div id="div1" style="border: 2px solid black"></div>
</body>
</html>
module1.js:
import { divStyle1, divStyle2 } from './module2.js'
divStyle1.width = "50px"
const div1Style = document.getElementById('div1').style
div1Style.backgroundColor = divStyle1.color
div1Style.height = divStyle2.height
div1Style.width = divStyle1.width
module2.js:
export const divStyle1 = {
color: 'red',
height: '100px',
width: '100px',
}
Assuming that the index.html, module1.js, and module2.js are kept inside the same directory,
then what will be the background color, height and width of the HTML element having ID ‘div1, if
rendered using a browser?
Solution: width property of divStyle1 has been override inside the module 1 so, width of the div1
is 50px, and backgroundColor comes from divStyle1 so, it will be red and height comes from
divStyle2 so, it will be 50px.
console.log(standsFor('A'))
A. Application
B. Programming
C. Interface
D. A
Answer: B
Solution: Program will log the first value whose key is not ‘A’. So, it will be “Programming”.
Week 3 Graded Questions
Q1: Which of the following are examples of system level state that needs to be
maintained for the entire app?
Ans: A and C
Explanation: User preference is frontend state, shopping cart is user specific application state.
Q2: Which of the following could be considered user specific application state?
Ans: D
Explanation: User shopping cart content is specific to the user. So, it can be considered as user
specific application state.
Q3: When you view the online discourse forum, there is a line indicating “last visit” -
posts above this have been updated since the last time you visited the forum. What kind
of state information is this indicator conveying?
A. Ephemeral UI state
B. Application state
C. System state
D. None of the above
Ans: B
Explanation: Although this is temporary and changes each time the user loads the page, it still
needs to be stored at the server to keep it up to date.
Q4: Which of the following methods can be used to ensure that the displayed state and
system state are kept in sync at all times?
Explanation: Vue bindings by themselves do not synchronize state, and reloading a page will
most likely cause loss of any ephemeral information.
A. Ephemeral UI state
B. Application state
C. System state
D. None of the above
Ans: C
Explanation: The main idea of persistent storage is that you can reconstruct system state from
the stored data
Q6. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">{{newMessage}}</div>
app.js:
const dataObj = {
message: 'Welcome',
}
const optObject = {
el: '#app',
data: dataObj,
}
A. Welcome
B. Welcome to iitm online degree
C. App with give a warning and will show a blank page.
D. None of the above
Answer: C
Explanation: properties in data are only reactive when they are present when instance was
created and “newMessage” is not present in data object it was assigned after the instance was
created so, app will not be able to identify the property.
Q7. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
app.js:
const dataObj = {
count: 10000,
}
const optObject = {
el: '#app',
data: dataObj,
}
const app = new Vue(optObject)
setInterval(() => {
app.count -= 1
}, 1000)
A. 10000
B. 9999
C. 9940
D. None of the above
Answer: C
Explanation: After each 1 second callback function of setInterval will reduce the count property
of data object by 1 so after 1 minute it well be reduced by 60 so, answer is 9940.
Q8. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
app.js:
const dataObj = {
message: 'IITM online',
divStyle: {
backgroundColor: 'red',
padding: '20px',
fontSize: '2em',
},
}
const optObject = {
el: '#app',
data: dataObj,
}
What will be the color, background color and font-size of the div with ID “app”?
Answer: A
Explanation: v-bind will bind the style property of div element with divStyle property of data
object, and it already has color white assigned so, option A is correct.
Q9. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
app.js:
const dataObj = {
message: 'IITM online',
fontSize: 2,
}
const optObject = {
el: '#app',
data: dataObj,
methods: objMethods,
}
const app = new Vue(optObject)
If the font size of the text ‘IITM Online’ increases by 1 em each time the user clicks on the
button, which one of the following is the definition of objMethod?
A. const objMethods = {
zoom() {
this.fontSize += 1em
},
}
B. const objMethods = {
zoom() {
fontSize += 1
},
}
C. const objMethods = {
zoom() {
this.fontSize += 1
},
}
D. const objMethods = {
zoom() {
fontSize += 1em
},
}
Answer: C
Explanation: Each time user clicks on the button, zoom method will be triggered, and style
property is bind with the object {fontSize:fontSize+'em'} so, in order to change the font size we
zoom need to change the fontSize property of data object. So, Option C is correct.
Q10. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">
<p directive1>{{message}}</p>
<button directive2>click</button>
</div>
app.js:
If you want to toggle between the presence of p element on click of the button element, what are
the possible value of directive1 and directive2 and their respective values?
A. v-if=”seen”, v-on:click=”toggleSeen”
B. v-if:”seen”, v-on:click:”toggleSeen”
C. v-if=”seen”, @click=”toggleSeen”
D. v-if:”seen”, @:click:”toggleSeen”
Answer: A and C
Explanation: v-on will bind the click event to the method “toggleSeen” which will change the
value of seen property according to the previous set property. And v-if will control the display of
p element based on truth value of seen property. And @ is shorthand for v-on. So, A and C are
correct.
Week 4 Graded Questions
Q1. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">
<ol>
<li v-for="item in items">{{item}}</li>
</ol>
<button @click="addItem">Add Item</button>
</div>
<script src = "app.js"> </script>
app.js:
Suppose the application adds a “New item” in the list every time you click on the button “Add
Item”, what can be the possible definition of the method “addItem”?
A. addItem() {
items.push('New item')
},
B. addItem() {
this.items.push('New item')
},
C. addItem() {
this.items = 'New item'
},
Answer: B
Solution: addItem() {
this.items.push('New item')
},
Will add ‘New item’ in items array.
Answer: A and D
Solution: V-bind directive is used for one way binding, and v-model is used for 2-way binding.
Q3. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">
<h4>total payable amount is {{totalPayableAmount}}</h4>
</div>
<script src = "app.js"> </script>
app.js:
appData = [
[2000, 10, 2],
[3000, 20, 3],
[5000, 30, 4],
]
Answer: B
Solution: After every 1 second, callback function will add simpleInterest in totalPayableAmount.
So, after 1 second it will be: 0+6000=400, after 2 seconds it will be 6000+1800=7800 and after 3
seconds it will be 7800+400 = 8200 and after that stack will be empty. Thus, the total amount
will not be modified further.
Q4. Consider the following Vue application with markup index.html and JavaScript file app.js,
index.html:
app.js:
A. 0
B. 1
C. 20
D. None of the above
Answer: B
Solution: For loop will increase the data x by 1 at each iteration. So, watcher x will be called,
and it will modify the value of y only if new value is greater than old value and also new value is
greater than 10. Thus, the value of y will be modified to 1.
Q5. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
app.js:
A. undefined, 40
B. undefined, 20
C. 20, 40
D. 40, 40
Answer: A
Solution: beforeCreate hook will be called synchronously immediately after the instance has
been initialized, before data observation and event/watcher setup (Reference: Vue
documentation).
So, function will not have access to data x. Thus, it will log undefined.
Q6. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
app.js:
created(){
console.log(this.x)
},
})
A. undefined, 40
B. undefined, 20
C. 20, 40
D. 40, 40
Answer: C
Solution: Called synchronously after the instance is created. At this stage, the instance has
finished processing the options which means the following have been set up: data observation,
computed properties, methods, watch/event callbacks. However, the mounting phase has not
been started, and the $el property will not be available yet (Reference: Vue documentation)
So, created() function will have access to the data x. Thus, it will log 20.
Q7. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">
<p directive> data </p>
</div>
app.js:
const players = [
{ name: 'Rohit Sharma', role: 'Batsman', team: 'MI' },
{ name: 'Virat Kohli', role: 'Batsman', team: 'RCB' },
{ name: 'Jaspreet Bumrah', role: 'Bowler', team: 'MI' },
]
If your app displays the name of the players who play for “MI”. What can be the possible value
for directive and data respectively in the above code (mentioned in the element with ID app)?
Answer: A and C
Solution: Because app has to display the player's name who play for MI we need v-if =
“player.team == ‘MI’, and it has to display all the players so will need v-for="player in players" to
iterate over all the players. {{player.name}} will display the name property of player.
Q8. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">
<comp1></comp1>
</div>
<script src = "app.js"> </script>
app.js:
const comp1 = {
template: '<h4> This is {{name}}</h4>',
data: function () {
return {
name: 'component 1',
}
},
}
A. This is
B. This is component 1
C. No text will be shown on the browser
D. None of the above
Answer: B
index.html:
<div id="app">
<comp1></comp1>
</div>
<script src = "app.js"> </script>
app.js:
const comp1 = {
template: '<h4> This is {{name}}</h4>',
data: {
name: 'component 1',
},
}
A. This is
B. This is component 1
C. No text will be shown on the browser
D. None of the above
Answer: A
Solution: data option inside the components comp should be a function. So, interpolation will not
work here because name property will not be recognized. The browser will only manage to
render “This is “. So, option A is correct.
Q10. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">
<comp-a></comp-a>
</div>
<script src = "app.js"> </script>
app.js:
A. Hello:
B. Hello: Welcome to IITM
C. No text will be shown on the browser
D. None of the above
Answer: B
Solution: compA is global component so, we don't need to register it inside the app we can use
it directly. So, ‘Hello: Welcome to IITM’ will be rendered.
Week 5 Graded Questions
const a = fetch("https://httpbin.org/get")
a.then(r => {
if (!r.ok){
throw new Error("HTTP status code: " + r.status);
}
return r.json();
}).then(d => {
console.log("Got the data !!");
}).catch(e => {
console.log(e);
})
What will be shown on the browser console if the above program is executed?
Answer: C
Solution: The fetch() method will return the first promise, which will resolve into the response
object (r), since the URL given was valid. After that, a second promise will be returned by the
statement “r.json()”, which will further resolve into data (d), since there is no error.
Solution: The fetch() method works asynchronously by default, but can be made work in a
synchronous manner by using async and await keywords. Fetch method always returns a
promise which resolves, reject or generate an error. Fetch method can be used to create almost
all types of HTTP requests.
Q3: Consider the following files are present inside the same directory,
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
</body>
<script src="app.js"></script>
</html>
app.js:
const a = fetch("sample.txt")
a.then(r => {
if (!r.ok){
throw new Error("HTTP status code: " + r.status);
}
return r.text();
}).then(d => {
console.log("Got the data !!", d);
}).catch(e => {
console.log(e);
})
sample.txt:
Hello World !!
What will be shown on the browser console if index.html is rendered with the help of a browser?
Answer: A
Solution: The fetch() method will return the first promise, which will resolve into the response
object (r), since the URL given was valid. After that, a second promise will be returned by the
statement “r.json()”, which will further resolve into data (d), since there is no error, and print the
message “Got the data !! Hello World !!” on the console.
Q5: How to extract “temp” from the given API call and display the information in the
index.html?
To get output in a format like Temperature:26.5°C, fill Code1
index.html:
<div id="app">
<p>Temperature:Code1</p>
</div>
<script src="app.js"></script>
app.js:
new Vue({
el: '#app',
data(){
return{
weather:[]
}
},
async created(){
return
fetch('https://fcc-weather-api.glitch.me/api/current?lat=12.97&lon=77.59')
.then(response => response.json())
.then(responseJson => {
this.weather=responseJson
console.log(this.weather)
})
.catch(error => {
console.error(error);
});
}
})
A. {{weather.main.temp}}degreeC
B. {{weather.main.temp}}°C
C. {{weather.main.temp}}C
D. None of the above
Answer: B
Solution : The entire json data from the url is first stored in weather[] .
To get the temperature from the given we can use weather.main.temp .
( check the data format of the api
https://fcc-weather-api.glitch.me/api/current?lat=12.97&lon=77.59 )
To get the degree symbol we can use the unicode use
° or °
Q6: Suppose the server at “worldtimeapi.org” is down. What will be shown on the
console?
app.js:
new Vue({
el: '#app',
data(){
return{
time:[]
}
},
created(){
fetch('http://worldtimeapi.org/api/timezone/Asia/Kolkata')
.then(response => response.json())
.then(responseJson => {
this.time=responseJson
console.log(this.time)
})
.catch(error => {
console.log(“Failed to Fetch”);
});
}
})
A. Failed to fetch
B. Reference error
C. Server Down
D. None of the above
E.
Answer A
Solution : If a fetch to the url fails, it will enter the catch and print the error message.
let x = 2,
n = 3,
k = 4
A. 2
B. 4
C. 8
D. Bad Promise
Answer: D
function promiseGenerator(s) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Will resolve after ${s} seconds`)
}, s * 1000)
})
}
async function asyncFunc() {
console.log('Initial statement') // statement 1
let prom1Val = await promiseGenerator(20)
console.log(prom1Val) // statement 2
let prom2Val = await promiseGenerator(30)
console.log(prom2Val) // statement 3
}
asyncFunc()
What is the approximate time (in seconds) taken by statement 2 to run after statement 1 and
time taken by statement 3 to run after statement 1?
A. 20, 30
B. 30, 30
C. 20, 50
D. 50, 50
Answer: C
Note: This question is inspired by the example given under the heading “Async functions and
execution order” in the document
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
#async_functions_and_execution_order
Q9: Consider the following JavaScript program, and predict the output if executed.
let start = 5;
function check() {
return new Promise((res, rej) => {
let a1 = setInterval(() => {
start++;
if (start === 7) {
console.log("Reached");
clearInterval(a1);
res("Pass");
rej("Fail");
}
else {
console.log("Yet to Reach");
}
}, 500);
})
}
check().then(
pass => console.log(pass)
).catch(
fail => console.log(fail)
);
A. Yet to Reach
Reached
Pass
B. Yet to Reach
Reached
Pass
Fail
C. Yet to Reach
Reached
Fail
D. Yet to Reach
Yet to Reach
Reached
Pass
Fail
Answer: A
Solution: The function named “check” returns a promise. This promise resolves when the value
of variable start becomes 7 (a number). It will take one iteration for the value to become 7, since
it is initialized with the value “5”. So, it will log “Yet to Reach” firstly. Once, the value of the
variable named “start” becomes 7, it logs the message “Reached” on the console, and resolves
the promise with the message “Pass”, which will be logged on the console as well, as the “then”
simply logs this value on the console.
Q10: Consider the following JavaScript program,
console.log("Finished");
}
func2();
}
func1();
What will be the minimum time taken by the above program to log the message “Finished” on
the console?
A. 4 seconds
B. 6 seconds
C. 0 seconds
D. 2 seconds
Answer: D
Solution: The function named “func1” is an async function, and the keyword “await” can be used
inside it. The function defined a promise asynchronously, also this function contains a nested
function with name “func2”, which again defined a promise, but it will be executed
synchronously, and there will be a wait of minimum 2000 milliseconds (2 second) to execute the
console.log(“Finished”) statement, since the promise will take 2 seconds to get resolved. After
waiting for 2 more second, the promise in the outer function will also get resolve
Week 6 Graded Questions
Q1: In the below code snippet, which takes a number as input and stores it in
localStorage so that on refreshing the page, the previous number stored should show
up in the input area. Fill in code 1 and code 2.
index.html:
<div id="app">
My lucky Number is
<input type="number" v-model=code1>
<button v-on:click="addNumber">ADD</button>
</div>
app.js:
code2 }
}
});
A. code1: “number”
code 2: localStorage.number = this.number;
B. code1: “newNumber”
code 2: localStorage.number = this.newNumber;
C. code1: “newNumber”
code 2: localStorage.number = this.number;
D. code1: “number”
code 2: localStorage.number = this.newNumber;
Answer: A
Solution: To be able to see the previous number entered in the input box upon refresh, the
number taken as input should be stored somewhere and fetched back when the application
reloads.
In the above question, local storage is used. In the mounted(), the number from localStorage
Is being placed in this.number. So, this is the number that needs to reflect in the input box.
Thus, <input type="number" v-model=number>.
And when the Add button is clicked , the number in the input box should update the
localStorage,with localStorage.number = this.number;
Q2: In order to ensure that items entered to the toDoList persist after screen refresh by
adding it to localstorage, choose the code that can be placed in code1 as marked
below.
index.html:
<input v-model="newData"
placeholder="Enter your List"/>
<button @click="addTodoList">Add</button>
app.js:
data:{
title:"To Do List",
newData:'',
todoList:new Array(),
},
methods:{
addTodoList(){
this.todoList.push(this.newData)
code1
}
}
A. localStorage.setItem(STORAGE_KEY,JSON.stringify(this.todoList))
B. localStorage.getItem(STORAGE_KEY,JSON.stringify(this.todoList))
C. localStorage.setItem(STORAGE_KEY,JSON.parse(this.todoList))
D. localStorage.getItem(STORAGE_KEY,JSON.parse(this.todoList))
Answer A
Solution: The key value pairs stored in localStorage are in string format. So when handling arrays
and objects, JSON.stringify() can be used when placing data into the local storage with the
setItem().
(https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)
Q3: Consider the following markup index.html and JavaScript file app.js for an
application,
index.html:
<div id="app">
<named-slot v-slot:header="slotProp">
Name: {{slotProp.user.name}}, District:
{{slotProp.user.dist}}</named-slot
>
</div>
<script src="app.js"></script>
app.js:
const namedSlot = {
template: `
<div>
<slot name = "header" :user="currentUser"></slot>
</div>
`,
data() {
return {
users: [
{
user_id: 1,
name: 'Narendra',
dist: 'Ballia',
},
{
user_id: 2,
name: 'Abhisek',
dist: 'Delhi',
},
],
currentUser: null,
}
},
props: ['current_user_id'],
created() {
current_user = sessionStorage.getItem('userId')
current_user_id = current_user ? current_user : 2
this.currentUser = this.users.find(
(user) => user.user_id == current_user_id
)
sessionStorage.setItem('userId', current_user == 1 ? 2 : 1)
},
}
Answer: B
Solution: If the value is not stored in sessionStorage 2 will be stored in the current_user and if
already stored then it will store 2 if its value is 1 and 2 if value stored is 2. So if you will run the
application for first time then 2 will be stored in sessionStorage and information related to id 2
will be rendered so, Option B is correct.
Q4. Consider the app.js and index.html from the Question number 3.
What will be rendered by the browser after refreshing the page 2021 times?
Answer: A
Solution: If the value is not stored in sessionStorage 2 will be stored in the current_user and if
already stored then it will store 2 if its value is 1 and 2 if value stored is 2. So if you will refresh
the page an odd number of times information related to id 1 will be rendered, Option A is
correct.
Q5. Consider the following markup index.html and JavaScript file app.js for an
application,
index.html:
app.js:
Suppose the application is running on http://localhost:8080. If a user visit the page “index.html”,
and clicks on the button normal, and then close the tab in which the application is open, and
then again visit the website, what will be the background color of div with ID “app”?
A. black
B. red
C. white
D. None of the above
Answer: A
Solution: Because we are using session storage, once you close the session data stored inside
the session storage is lost. And if you will again open the application, dark mode will be stored
inside the session storage. So, option A is correct.
Q6. Consider the following markup index.html and JavaScript file app.js for an
application,
index.html:
app.js
Suppose the application is running on http://localhost:8080. If a user visits the page “index.html”,
and click on the button normal, and then close the tab in which the application is open, and then
again visit the website, what will be the background color of div with ID “app”?
A. black
B. red
C. white
D. None of the above
Answer: B
Solution: Because localStoreage is being used even if you will close the tab, the data stored
inside the local storage will persist. And mode stored inside the local storage is normal so,
background color will be red.
Q8: Consider the following Vue application with markup index.htm, and javascript file
app.js,
index.html:
<div id = "demo">
<input v-model = "name" v-on:change = "check" />
<p :class = "[isError ? 'btn btn-danger' : 'btn btn-success']"> Correct?
</p>
</div>
<script src = "app.js">
app.js:
const app = new Vue({
el: '#demo',
data: {
name : "",
isError : true,
},
mounted () {
if (localStorage.name) {
this.name = localStorage.name;
this.isError = localStorage.isError;
}
},
methods: {
check: function () {
if (this.name.length > 3)
this.isError = false;
else
this.isError = true;
localStorage.name = this.name;
localStorage.isError = this.isError;
}
}
})
Say you open the “index.html” file in a browser, and write “abhi” in the text input shown on
screen, and click on the paragraph element with text “Correct?”, then force reload the page.
What will be the value in the input text box and class applied to the paragraph element with text
“Correct?”, respectively?
Answer: C
Solution: When you enter the text “abhi” in the text box and click anywhere outside the text box
(not necessarily the paragraph), the “change” event gets triggered which stores two key value
pairs (“name : abhi” and “isError : true”) in the local storage. After force reloading the page, the
mounted() hook will be triggered, which will fetch the values of keys “name” and “isError” in the
local storage, which are “abhi” and “true”, but both the values will be JavaScript strings. And
since the value of “isError” is “true” (in string), the condition evaluates to true, and “btn
btn-danger” class will be applied to the paragraph.
Q9: Which of the following statement(s) is/are false regarding localStorage API?
Answer: B and D
Solution: Local Storage is a client side storage mechanism which allows storing key value pairs
in the browser for a specific origin. It provides several methods like “removeItem()” to delete a
key value pair from the local storage, and “length” that returns the number of key-value pairs
stored in it currently. The local storage data for a specific domain is not accessible to its
subdomains.
Q10: In order to test that the app is correctly validating the username, what should be
the expected assertions below in C1,C2,C3,C4?
HTML:
<template>
<div>
<input v-model="username">
<div
v-if="error"
class="error"
>
Validation Failed
</div>
</div>
</template>
<script>
export default {
name: 'Hello',
data () {
return {
username: ''
}
},
computed: {
error () {
if(this.username.trim().length < 7){
return true
}
else{
let charCode=username.charCodeAt(0)
if((charCode >= 33 && charCode <= 47) || (charCode >= 58 &&
charCode <= 64)){
console.log("special char not allowed");
return true
}
else{
return false
}
}
}
}
</script>
JS:
test('Login', () => {
// render the component
const wrapper = shallowMount(Hello)
expect(wrapper.find('.error').exists()).toBe(C1)
expect(wrapper.find('.error').exists()).toBe(C3)
expect(wrapper.find('.error').exists()).toBe(C4)
})
Answer A
Solution: The test case here is trying to check if the Vue component is validating the username
properly, i.e., if the username is less than 7 characters or if the first character entered is a
special character. So, if an invalid username is passed using the wrapper.setData(), the test
expects a true value, i.e., the computed method should return a true value
Week 7 Graded Questions
Q1: Consider the following markup index.html and JavaScript app.js for a Vue
application.
index.html:
<div id="app">
<div>
<router-link :to="{name:'home'}"> Home </router-link>
<router-link :to="{name:'profile', params:{name:'Abhisek'}}">
Profile</router-link
>
</div>
<router-view />
</div>
<script src="app.js"></script>
app.js:
const home = {
template: `<h1> Home </h1>`,
}
const profile = {
template: `<h1> Hello {{ name }}</h1>`,
props: ['name'],
}
const routes = [
{ path: '/', name: 'home', component: home },
{ path: '/profile/:name', name: 'profile', props: true, component:
profile },
]
What will be rendered inside the router-view when user loads the application for the first time
and when user clicks on the link “Profile", respectively?
Answer: C
Solution: Because base property of router instance is ‘/’. A component associated with ‘/’ which
is home will be rendered inside the router-view component. Once the user clicks on the Profile,
the user will be redirected to the route with the name ‘profile’ along with the parameter name =
Abhisek. props = true so, parameters will be passed as props. So, answer C is correct.
Q2: Consider the following markup index.html and JavaScript app.js for a Vue
application.
app.js:
const player = {
template: `<div>
<h1> Name: {{ name }}</h1>
<router-view />
</div>`,
props: ['name'],
}
const test = {
template: '<div><h1> Test Runs: {{ runs }} </h1></div>',
data() {
return { runs: 5000 }
},
}
const oneDay = {
template: '<div><h1> Oneday Runs: {{ runs }} </h1></div>',
data() {
return { runs: 10000 }
},
}
const routes = [
{
path: '/player/:name',
component: player,
children: [
{ path: '', component: oneDay },
{ path: 'test', component: test },
{ path: 'oneday', component: oneDay },
],
props: true,
},
{ path: '*', component: test },
]
const router = new VueRouter({
routes,
base: '/',
})
<div id="app">
<router-view></router-view>
</div>
<script src="app.js"></script>
Suppose the application is running on http://localhost:8080, and user visits the URL
“http://localhost:8080/#/player/rohit”. What will be rendered inside the router-view?
A. Name: Rohit
Oneday Runs: 10000
C. Name: Rohit
Test Runs: 5000
Answer: A
Q3: Consider the app.js and index.html given in the Question No.2.
Suppose the application is running on http://localhost:8080, and the user visits the URL
“http://localhost:8080/#/player/rohit/test”. What will be rendered by the browser?
A. Name: Rohit
Oneday Runs: 10000
C. Name: Rohit
Test Runs: 5000
Q4: Consider the app.js and index.html given in the Question No.2.
Suppose the application is running on http://localhost:8080, and the user visit the URL
“http://localhost:8080/#/player/rohit/t20”. What will be rendered by the browser?
A. Name: Rohit
Oneday Runs: 10000
C. Name: Rohit
Test Runs: 5000
Answer: B
Solution: Because ‘/t20’ is after the “http://localhost:8080/#/player/rohit”. So, router will not be
able to find any match. So, the component associated with ‘*’ will be rendered inside the
router-view of div with ID “app”.
Q5: Consider the following markup index.html and JavaScript app.js for a Vue
application.
index.html:
<div id="app">
<div>
<router-link to="/profile" replace> Profile </router-link>
<router-link to="/post"> Post </router-link>
</div>
<div>
<router-view />
</div>
</div>
app.js:
const profile = {
template: '<div> <p> Profile Page </p> </div>',
}
const post = {
template: '<div><p> Users Post </p></div>',
}
const routes = [
{ path: '/profile', component: profile },
{ path: '/post', component: post },
{ path: '*', component: post },
]
const router = new VueRouter({
routes,
base: '/',
})
A. ‘Profile Page’ will be rendered inside router-view, the user will not be able to navigate
back to the default post page using browser’s back button.
B. ‘Profile Page’ will be rendered inside router-view, the user will be able to navigate back
to the default post page using browser’s back button.
C. ‘Users Post’ will be rendered inside router-view, the user will not be able to navigate
back to the default post page using browser’s back button.
D. ‘Users Post’ will be rendered inside router-view, the user will be able to navigate back to
the default post page using browser’s back button.
Answer: A
Solution: Once the user visit the app for first time, post component will be rendered inside the
router view and ‘/post’ will be pushed inside the browser’s history stack. When the user click on
‘Profile’, profile component will be rendered inside the router-view and ‘/post’ will be replaced
with the ‘/profile’ because of replace props so, the browser’s history stack will look something
like [‘/profile’] so, user will not be able to go back to default post page using browsers back
button. So, option A.
A. ‘Profile Page’ will be rendered inside router-view, the user will not be able to navigate
back to the default post page using browser’s back button.
B. ‘Profile Page’ will be rendered inside router-view, the user will be able to navigate back
to the default post page using browser’s back button.
C. ‘Users Post’ will be rendered inside router-view, the user will not be able to navigate
back to the default post page using browser’s back button.
D. ‘Users Post’ will be rendered inside router-view, the user will be able to navigate back to
the default post page using browser’s back button.
Answer: C
Solution: When the user visits the app for the first time, the default ‘/post’ will be pushed to
the browser’s history stack. And then when the user clicks on the ‘profile’ link, ‘/post’ will be
replaced with the ‘/profile’ because of the ‘replace’ prop. Again, when the user visits the post
page, ‘/post’ will be pushed to the history stack. So at the end stack will look something like
[’/profile’, ‘/post’] so, user will not be able to navigate back to the default ‘post’ page using
browsers back button.
Q7: In the code snippet below, the Vuex store has a state called product.
Fill in the code in code1 inside the “products” computed property in order to render the name
and prices of the different products.
index.html:
<div id = "app">
<table border="1px">
<tr>
<td>Product</td>
<td>Price</td>
</tr>
<tr v-for="product in products">
<td>{{product.name}}</td>
<td>{{product.price}}</td>
</tr>
</table>
</div>
app.js:
})
new Vue({
el:"#app",
store:store,
computed:{
products(){
return code1
}
}
})
A. store.commit.products
B. store.state.products
C. store.dispatch.products
D. None of the above
Answer: B
Solution: One can retrieve the values in the central store by returning the store state
within a computed property. In the above example, it should be store.state.products
Q8: Fill in code1, inside a mutation handler, which can be used to reduce the price of
each of the products in the state by a certain discount.
app.js:
}
}
})
A. this.$store.state.products.forEach(product => {
product.price -= (state.discount)/100*product.price;})
B. state.products.forEach(product => {
product.price -= (state.discount)/100*product.price;})
C. commit.products.forEach(product => {
product.price -= (state.discount)/100*product.price;})
D. dispatch.products.forEach(product => {
product.price -= (state.discount)/100*product.price;})
Answer: B
Solution: Correct option is B. The mutation handler receives state as its first argument.
The discount needs to be applied on each of the products.
Answer A, C and D
Solution: Reference :
https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Introduction
Answer: D
Q1: Which of the following statements is false regarding REST and GraphQL?
Answer: D
Solution: GraphQL is a query language for our API, which helps to make complex queries and
helps to retrieve only the data that is required.
Ref: https://graphql.org/
Q2: Which of the following statement(s) is/are false regarding REST and GraphQL?
A. GraphQL can fetch the data from multiple sources and return the fused response.
B. In REST, the GET requests are not cacheable in general.
C. In GraphQL, the POST requests are cacheable in general.
D. GraphQL can execute a complex query to return a complex data set with a single
request, whereas, REST APIs may require to make multiple requests for the same.
Answer: B and C
Solution: A GraphQL query can be constructed, requesting data from multiple resources. A
request is generally cacheable, when the response can be constructed with just the URL, and
the reason for GET requests being cacheable is that a GET request has all the required data in
the URL. However, a POST request has data in the request body, which is not cacheable in
general.
A. GET
B. POST
C. PUT
D. All of the above
Answer: A
Solution: A request is generally cacheable, when the response can be constructed with just
seeing the URL, and the reason for GET requests being cacheable is that a GET request has all
the required data in the URL. However, a POST or PUT request has data in the request body,
which is not cacheable in general.
Answer: B and C
Solution: A GraphQL request can be constructed with the “Content-Type” header value as both
“application/graphql” and “application/json”, but the body content should match with the header
value. The response to a GraphQL request is generally a JSON response, with the data stored
in “data” field.
A. All the responses to the GraphQL requests should return 200 as the status code in
general.
B. A GET request cannot be made in GraphQL, and it must always send POST requests.
C. All the endpoints in a RESTful API should return 200 as the status code.
D. None of the above
Answer: B and C
Solution: An endpoint in an REST API should return an appropriate status code with the
response, and it need not be 200 always. You can read more about GraphQL at GraphQL -
GraphQL (dgraph.io)
Q6: Which of the following statement(s) is/are true?
Answer: A, B, C and D
Solution: A web component can be used to create custom HTML tags or elements (just the way
components in Vue work), and each of the web component can have styling specific to them,
which is not applied to other parts of the web page.
HTML is considered to be a more verbose language, if compared with Markdown, which has
inline styling in general.
Answer: A and B
Solution : In GraphQL query is used to retrieve information and mutations can be used to
change the underlying data store. The API’s in GraphQL are organized through types (entities)
and corresponding fields.
Reference : https://graphql.org/
Answer: A, C and D
Solution: GraphQL is a query language for API. It can be thought of as a layer on the server
side through which we can make complex queries, usually over the POST body of the request.
It can connect to multiple data sources.
Answer: A, B and C
Solution: Headless CMS the content is decoupled from the front end. Content API can then be
used to access content where needed - website/mobile app.
Q10: Which of the following is the most commonly used representation for resources in
web APIs?
A. xml
B. json
C. webp
D. woff
Answer: B
Reference: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON
Week 9 Graded Questions
Q1: Consider the flask application app.py and an HTML file index.html,
app.py:
app = Flask(__name__)
@app.route('/')
def home():
time.sleep(10)
return jsonify(datetime.now().second), 200,
{'Access-Control-Allow-Origin': '*'}
@app.route('/profile')
def profile():
time.sleep(30)
return jsonify(datetime.now().second), 200,
{'Access-Control-Allow-Origin': '*'}
if __name__ == "__main__":
app.run(debug=True)
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<script>
function test() {
const res1 = fetch('http://127.0.0.1:5000')
const res2 = fetch('http://127.0.0.1:5000/profile')
res1
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data)
})
res2
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data)
})
}
test()
</script>
</body>
</html>
If a user visits index.html at 10:10:10 AM (in format HH:MM:SS), what will be logged in the
console (approximately)?
A. 20, 50
B. 20, 40
C. 40, 40
D. 50, 50
Answer: B
Solution: The flask application is being run in the threaded mode (default). This means that the
application will be able to accept and process multiple requests simultaneously. Thus, if 2
requests are sent at the same time (10:10:10), the route “/” will take a minimum of 10 seconds to
respond, and route “/profile” will take a minimum of 30 seconds, but both will be processed
simultaneously in different threads.
Q2: Consider the flask application app.py and an HTML file index.html,
app.py:
app = Flask(__name__)
@app.route('/')
def home():
time.sleep(10)
return jsonify(datetime.now().second), 200,
{'Access-Control-Allow-Origin': '*'}
@app.route('/profile')
def profile():
time.sleep(30)
return jsonify(datetime.now().second), 200,
{'Access-Control-Allow-Origin': '*'}
if __name__ == "__main__":
app.run(threaded=False, debug=True)
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<script>
function test() {
const res1 = fetch('http://127.0.0.1:5000')
const res2 = fetch('http://127.0.0.1:5000/profile')
res1
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data)
})
res2
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data)
})
}
test()
</script>
</body>
</html>
If a user visits index.html at 10:10:10 AM (in format HH:MM:SS), what will be logged in the
console (approximately)?
A. 20, 50
B. 20, 40
C. 40, 40
D. 50, 50
Answer: A
Solution: The flask application is being run in the non-threaded mode. This means that the
application will not accept any new request before it finishes processing the previous request.
Thus, if 2 requests are sent at the same time (10:10:10), firstly, the route “/” will take a minimum
of 10 seconds to respond, and then the next request will be accepted, and the route “/profile”
will take a minimum of 30 seconds before responding.
Answer: A and D
Answer: Redis is an in-memory database, which can be made to store data in the disk, and it
stores the data in the form of key-value pairs, but it stores the data in main-memory by default.
Even, if the data is stored in the disk, the data needs to be brought to the main memory for
manipulating it.
Answer: A, B and C
Solution: Redis is an in-memory database, which supports various data types. It is always
possible to store data with timeouts. The TTL value of -1 indicates that the data is not meant to
be expired. It is also possible to have an authentication layer with Redis.
Q5: Which of the below is true for Celery?
Answer: A, B and D
Solution: Celery is a python based task queue, which provides multiples workers to perform
heavy computed job asynchronously. It generally retries certain times in case of a connection
loss. Celery supports brokers other than Redis and RabbitMQ like Amazon SQS. It is always
helpful for scheduling tasks or jobs.
A. The concurrency is achieved by executing multiple tasks overlapping in time periods, but
not always simultaneously.
B. The concurrency can be achieved in both single-core and multi-core environments.
C. The concurrency is always achieved via “context switching” in a multi-core environment.
D. None of the above
Answer: C
Solution: Concurrency is the notion of carrying out multiple tasks or threads overlapping in time
periods or even simultaneously (at the same time). Concurrency is achieved via
“context-switching” in a single core environment, whereas, the same can be achieved using
“parallelism” in a multi core environment.
Q7: Which of the following statements is false regarding concurrency and parallelism?
Answer: B
Solution: Kindly refer to this thread on discourse: W9 Graded Assignment : Q7 - Courses /
Modern Application Development - II - IITM-PDS
Q8: Which of the following statement(s) is/are correct regarding message queue?
Answer: A, B, D
Q9: Which of the following is/are the true regarding message broker?
Answer: A and C
Answer: A and C
Solution: A sender sending a message need not worry about the present state of the receiver, if
the communication is happening using a message broker, as the message broker receives the
message from the sender and inform the receiver once it is available to take new requests. This
communication is generally asynchronous, as the sender need not wait for the receiver to
accept the previous request before sending anew request.
Week 10 Graded Questions
Answer: A and D
Solution: A Webhook is meant to work synchronously and should result in an instant response.
Webhooks can post JSON as well as form-encoded data.
A public receiver URL can be secured using security tokens to authenticate the request. A trivial
flask application (with at least 1 endpoint) can easily act as webhook receiver.
Q2: Which of the following statement(s) is/are correct, regarding Webhooks and Web
sockets?
Answer: A, B and C
Solution: Webhooks use HTTP protocol to post messages. A web socket is meant to be used to
achieve 2-way communication between the client and the server, where the connection between
the two is left open, unlike webhooks.
A webhook is primarily used for server-to-server communication because the receiver URL also
belongs to an application, which is responding to the requests it gets.
Q3: Which of the following statement(s) is/are true regarding polling and long poll?
A. In Polling, a client make repetitive calls to the server at fixed time intervals.
B. Polling requires a persistent connection to the server.
C. In long polling, the connection is kept open till the response is sent.
D. All of the above
Answer: A and C
Solution: Polling (i.e., short polling) is a process in which a client repeatedly requests the
information from the server at a fixed time interval. It doesn’t require a persistent connection, as
the client makes request to the server again and again.
While, in long polling, the client makes a request to the server, and waits or keeps the
connection open till the server responds.
Q4: Which of the following statements is false regarding server sent events?
Answer: B
Solution: Server sent events are used to push information to the clients, which are currently
connected via a sse stream, which is meant to be an infinite stream. It requires the service
workers to be running in the background to ensure a smooth flow of information from the server
to the client.
Q5: Which of the following statement(s) is/are true regarding short polling?
A. The client sends a request to the server, and the server responds to the client
immediately, even if it does not have data.
B. The client sends a request to the server, and the server waits to respond to the client if it
does not have data and keep the connection open.
C. Request is sent after fixed delay periodically.
D. All of the above
Answer: A, C
Solution: Polling (i.e., short polling) is a process in which a client repeatedly requests the
information from the server at a fixed time interval.
Q6: Which of the following is true regarding long polling?
A. The client sends a request to the server, and the server responds to the client even if it
does not have data.
B. The client sends a request to the server, and the server waits to respond to the client if it
does not have data and keep the connection open.
C. Request is sent after fixed delay periodically.
D. The client must send the next request immediately after it receives the response.
Answer: B
Solution: In long polling, the client makes a request to the server, and waits or keeps the
connection open till the server responds.
It is not at all must or required to send the request new request to the server as soon as it
responds, and depends on the application.
Answer: A, C and D
Solution: An API is capable of both pushing (POST, PUT etc.) and pulling (GET) messages
from/to an application. A Webhook is meant to work synchronously, and it usually pushes
(POST) messages to an application.
Answer A and D
Solution: A message broker performs various functions. It makes sure that the message is
delivered only to that recipient, it is meant for, and can be configured to deliver messages to
multiple recipients. It generally processes the messages in FIFO (First-In-First-Out) order.
Answer: A and D
Solution: A Webhook typically pushes (POST) the messages to an application, and the content
is sent as part of the request body. A webhook response should indicate the status code of the
request, and should have minimal or no data in the response body.
Webhooks are meant for one way messaging (i.e., the connection is not kept open), and they
are typically invoked by machine clients, when the event a webhook is configured for, is
triggered.
Week 11 Graded Questions
A. The cache decorator includes the function parameters in the cache key.
B. The memoize decorator includes the function parameters in the cache key.
C. Both the cache and memoize decorators work the same way for functions not having any
parameters.
D. All of the above
Answer: B and C
Answer: A and C
Solution: Caching can be done at various levels, like browser level, proxy server level, database
level etc. A hard refresh clears the browser’s cache, and forces the browser to load or get the
most recent version of the web page from the server.
A. A cached resource stored at a proxy server serves its copy to multiple users.
B. Hard refreshing a web page can still result in a cached response being served from a
proxy server.
C. Caching at browser level provides the least latency, if compared with proxy level.
D. All of the above
Answer: D
Solution: A resource being cached on the proxy server is meant to be served to multiple users,
without hitting the origin or the database server. A hard refresh forces the browser to get the
most recent version of the web page, but it can still be a cached version available at the proxy
server.
The cached resources that are available on the client’s browser provides the least latency, as
the browser need not even make a network call to fetch the resource.
Q4: Which of the following criterions should be directly considered while measuring the
performance of an application?
A. The number of requests an application can handle for a given time interval with as much
as little latency.
B. How does the application scale over load.
C. The application should be written in Python based flask or Django framework.
D. All of the above
Answer: A and B
Solution: It is not at all mandatory for an application to be written in flask or Django to provide a
good performance.
Q5: Which of the following tools can be used to measure or analyze the performance of
a web application?
A. GTmetrix
B. Postman
C. Lighthouse
D. All of the above
Answer: A and C
Solution: Both Lighthouse and GTmetrix are the tools that can be used for performance
measurement of a website or a web application, whereas, Postman is a web client, majorly used
for testing the APIs.
Q6: Which of the following is the correct statement?
Answer: A and C
Solution: A cookie set with the domain will be sent to the server with each request. So,
unnecessary cookie will create unnecessary traffic. And cookie with large size may slow down
the website because of the requirements of higher bandwidth.
Q7: Suppose you have a web page which includes a paragraph with some content,
images and a stylesheet. You want to update the content of the paragraph with
JavaScript. Which of the event, among load and DOMContentLoaded, you should wait
to fire before updating the content for better performance?
A. load
B. DOMContentLoaded
C. Both of them will result in same performance.
D. DOM is not required to be loaded fully before updating the content.
Answer: B
Solution: The load event is fired when every thing including images and stylesheets are fully
loaded, but DOMContentLaded is fired as soon as the HTML is loaded without waiting for
stylesheet and images to load. In order to change the content of paragraph only DOM is
required so, DOMContentLoaded will result in better performance.
Q8: Suppose you want to embed an image of 100*100 px in your webpage. Which of
the following statement is correct?
A. Using an image with dimension 200*200 px and scaling it using HTML will perform better
than using a 100*100 px image directly.
B. Using an image with dimension 200*200 px and scaling it using HTML will perform worse
than using a 100*100 px image directly.
C. Scaling using HTML does not impact the performance.
D. None of the above
Answer: B
Solution: Using the exact size image as required gives the better performance, as the resize of
the image or scaling may affect the performance of a web page by some margin.
Q9: Which of the following is/are correct regarding the E-Tag and If-Match?
Answer: A, B and C
Solution: E-Tag is an HTTP response header, which acts as an identifier for a particular version
of the resource. A new E-Tag must be generated if the resource at a specified URL changes.
You can read more about it here: ETag - HTTP | MDN (mozilla.org)
Answer: A, B and C
Solution: CDN (Content Delivery Network) is mainly used to deliver the static content with a high
speed. The content is served from the nearest CDN server to the user to provide high
performance.
Week 1 Practice Questions
Answer: D
Solution: Being a programming language, the programs written in JavaScript language can be
executed independently, without always needing a document context using some JavaScript
runtimes like NodeJS, Deno etc.
2. What will be the output on console if the following JavaScript program is executed
using command line? [MCQ]
Code:
{
let x = 5;
}
console.log(x)
A. 5
B. undefined
C. null
D. Reference Error
Answer: D
Solution: The variables declared using keyword “let” have block scope. And, they cannot be
used or referred to, outside the scope or block, which they have been declared in. If done, it will
generate an error.
3. What is AJAX? [MSQ]
A. AJAX is an acronym for Asynchronous JavaScript and XML.
B. It is a technology used to send request to the server without reloading the page via
JavaScript.
C. Only XML data can be transported using AJAX.
D. All of the above
Answer: A and B
Solution: AJAX (Asynchronous JavaScript and XML) is a technology used to communicate with
the servers behind the scenes, and use the server responses to make the user experience
better. It is not mandatory to use XML data while working with AJAX, it can even be done using
JSON format. In fact, JSON is preferred over XML these days.
let x
Answer: A
Solution: The variables declared using keyword “let” will result undefined, if used or referred
before assigning.
Solution: An assignment to a variable declared using “const” keyword afterwards will always
result in a Type Error. It can only be assigned once, that too during declaration.
obj.changeColor("Yellow")
A. SyntaxError
B. Red
C. Yellow
D. Undefined
Answer: C
Solution: The value of “this” keyword is obj (calling object) itself. So, the object’s method
“changeColor” will change the color property from “red” to “Yellow”.
obj.changeName('Mohit')
console.log(obj.name)
A. undefined
B. Rohit
C. Mohit
D. null
Answer: C
Solution: The value of “this" keyword is obj (calling object) itself. So, the object’s method
“changeName” will change the name property from “Rohit” to “Mohit”.
Answer: A, B, C and D
Solution: If the function has only one argument, the parenthesis can be skipped. And if it has
only return statement, { } can be skipped as well. So, all the given options refer to valid function
definitions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script>
document.getElementById('div1').style.backgroundColor = 'yellow'
</script>
<title>Document</title>
</head>
<body>
<div
id="div1"
style="height: 100px; width: 100px; background-color: red"
></div>
</body>
</html>
What will be the background color of an element having ID ‘div1’ in the rendered webpage
corresponding to this document? [MCQ]
A. red
B. black
C. yellow
D. None of the above
Answer: A
Solution: Till the time script will run, DOM is not yet created so element with ID ‘div1’ will not be
found. So, script will not have any effect on the style.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div
id="div"
style="background-color: black; height: 50px; width: 50px"
></div>
<script>
const colors = {
color1: 'red',
color2: 'green',
color3: 'yellow',
}
let i = 1
let color = null
setInterval(() => {
if (i % 2 != 0) {
color = colors.color1
}
else if (i % 4 == 0) {
color = colors.color2
}
else {
color = colors.color3
}
document.getElementById('div').style.backgroundColor = color
i++
}, 1000)
</script>
</body>
</html>
What will be the background color of an element having ID ‘div’ after 6 seconds? [MCQ]
A. black
B. yellow
C. green
D. red
Answer: B
Solution: The setInterval() function will execute the callback function after every 1 second. So ‘i’
will be incremented after every 1 second, and after 6 seconds the value of ‘i’ will be 6, and it is
divisible by 2 but not by 4. So, code inside else block will be executed, which will make the color
‘yellow’.
Week 2 Practice Questions
Q1: Which of the following programs (code snippet 1 and code snippet 2) will generate
an error, if executed?
A. Code snippet 1
B. Code snippet 2
C. Both Code snippets 1 and 2
D. None of the above
Answer: A
Solution: In code snippet 1, the value of a const variable is attempted to be incremented in the
same scope, which causes the termination of the program with an error, whereas in code
snippet 2, a new variable will be created in a new scope with each iteration, so it will not cause
any error, and the program will complete its execution without any errors.
Q2: Which of the following shows the correct output, if the program written below is
executed?
A. 1
B. 2
C. 3
D. 4
Answer: C
Solution: The find() method returns the first element of an array that satisfies the condition
specified.
Q3: Which of the following shows the correct output, if the program written below is
executed?
let a = {
'name' : 'abhi',
'age' : 22,
'place' : 'delhi'
};
let { name : alt } = a;
console.log(name);
A. abhi
B. alt
C. Reference Error
D. None of the above
Answer: C
Solution: The object reference “a” is destructured, and the “name” attribute is imported and
renamed as “alt”. No “name” variable or reference exists in the current scope.
Answer: A
Solution: The first element of the array “arr” is of type “string”, the second element is of type
“boolean”, the third element is of type “number”, and the last element is of type “function”.
Answer: B
Solution: A string literal cannot be multiplied with a string literal, which has at least one
alphabetical character, and it returns “NaN”, if tried. Similarly, a function cannot be multiplied
with a function. However, a boolean value “true” is translated to literal 1 and “false” to 0, if
multiplied with another boolean.
fruit = {
name: 'Apple',
color: 'red',
}
description(fruit)
Answer: D
Solution: name and color comes from the fruit object after destructing but shape property is not
there in fruits, it will take default value ‘Spherical’.
class Player {
constructor(name) {
this.name = name
this.team = 'Indian Cricket Team'
this.nationality = 'Indian'
}
}
A. Bowler {
name: 'Jasprit Bumrah',
team: 'Indian Cricket Team',
nationality: 'Indian',
role: 'Bowler',
wicket: 101,
average: 22.79
}
B. Bowler {
name: 'Jasprit Bumrah',
team: undefined,
nationality: undefined,
role: 'Bowler',
wicket: 101,
average: 22.79
}
C. Bowler {
name: undefined',
team: undefined,
nationality: undefined,
role: 'Bowler',
wicket: 101,
average: 22.79
}
Answer: A
Solution: Bowler inherits from Player. So, Bowler has access to all the properties and method of
Player. So, the answer is A
class Player {
constructor(name, team) {
this.name = name
this.team = team
}
get describe() {
return `${this.name} from ${this.team} is a ${this.role}`
}
}
Answer: D
Solution: Batsman inherits from Player. So, Bowler has access to all the properties and method
of Player. So, the answer is D.
const obj = {
a: 10,
operation(x, y, n) {
return x ** n + y + this.a
},
}
Answer: B
Solution: p.bind(obj, 2)(3, 2) will pass the value of x = 2, y = 3 and n = 2 so, it will push 17 into
arr.
p.apply(obj, [2, 2, 3, 4, 5]) will pass 2, 2, 3 for x, y and n so, it will push 20 in arr.
p.call(obj, 2, 3, 4) will pass 2, 3, 4 for x, y and n respectively so, it will push 29 in the arr.
So, option B is correct.
const obj = {
firstName: 'Narendra',
lastName: 'Mishra',
get fName() {
return this.firstName
},
get lName() {
return this.lastName
},
set lName(name) {
this.lastName = name
},
}
obj.lName = 'Mourya'
obj.lName = console.log(obj.lName)
A. Mishra
B. Mourya
C. Syntax Error
D. None of the above
Answer: B
Solution: obj.lname = ‘Mourya’ will trigger the set lname() method and change the lastName
property and obj.lname will trigger the get lname() method so, will return lastName property. So,
option B is correct.
Week 4 Practice Questions
Q1. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">{{message}}</div>
<script src="app.js"></script>
app.js:
const dataObj = {
message: 'Welcome',
}
const optObject = {
el: '#app',
data: dataObj,
}
A. Welcome
B. Welcome to iitm online degree
C. App will give a warning and will show a blank page.
D. None of the above
Answer: B
Solution: The HTML renders the value of “message” variable defined in the Vue instance. Since,
its value has been changed using the object reference, the app will render the updated value of
variable “message”.
Q2. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">
<div directive></div>
</div>
<script src="app.js"></script>
app.js:
If the app renders “Hello IITM” (in red font color), what is the possible directive for “directive”
mentioned in div with ID “app”?
A. v-bind= “text”
B. v-html= “text”
C. Both A and B
D. None of the above
Answer: B
Solution: The “v-html” Vue directive is used to update the inner HTML of an element. It updates
the element’s inner HTML with the rendered HTML it gets as input.
Q3. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">
<p v-if="dark" v-bind:style="divStyle">{{message}}</p>
<p v-else>{{message}}</p>
<button @click="toggleTheme">change theme</button>
</div>
<script src="app.js"></script>
app.js:
If the application toggles between dark theme (color:white, background-color: black) and normal
theme(color: black, background-color:white) on the click of a button with text “change theme”,
what can be the possible definition of toggleTheme method? (Assume that the application is
running on a common browser which displays black colored text on white background)
A. toggleTheme() {
this.dark = !this.dark
}
B. toggleTheme() {
this.dark == !this.dark
}
C. toggleTheme() {
dark = !dark
}
D. toggleTheme() {
this.dark = divStyle
}
Answer: A
Solution: The “toogleTheme” method requires toggling the value of Vue instance variable “dark”
between “true” and “false”. Since, this variable is to be accessed inside a method defined in the
Vue instance, “this” reference must be used to access it.
Answer: A and C
Solution: The computed properties cache the values and only get triggered when one of its
reactive dependencies changes, else it serves the cached value each time a re-render happens.
Answer: C
Solution: A watcher is a type of function which is defined inside the watch object of a Vue
instance, and it gets triggered each time when the property it refers to changes.
Q6. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">
<comp1></comp1>
</div>
<script src="app.js"></script>
app.js:
const comp1 = {
template: '<h4> This is {{name}}</h4>',
data: {
name: 'component 1',
},
}
A. This is
B. This is component 1
C. No text will be shown on the browser
D. None of the above
Answer: C
Solution: An object with the properties of component is created, but it is not registered with the
main Vue instance. So, the browser will consider “<comp1> </comp1>” as the opening and
closing of a tag, and it will be ignored while rendering. Thus, nothing will be shown on the
browser screen.
Q7. Consider the following Vue application with markup index.html and JavaScript file
app.js,
index.html:
<div id="app">
<ol>
<comp v-for="message in messages" :message="message"></comp>
</ol>
</div>
<script src="app.js"></script>
app.js:
const comp = {
template: '<li> {{ message.message }} </li>',
props: ['message'],
}
A. 1. This is message1
2. This is message2
3. This is message3
B. 1. This is message1
1. This is message2
1. This is message3
C. 1. ‘This is message1’
2. ‘This is message2’
3. ‘This is message3’
D. 1. ‘This is message1’
1. ‘This is message2’
1. ‘This is message3’
Answer: A
Solution: A Vue directive “v-for” is being used for the Vue instance variable “messages”, which
will iterate over each element in this list. Each iterated element will be sent as a prop to the
component “comp”, which renders it as an element of an ordered list. The ordered list by default
uses numbers as prefix to each element.
Answer: A
Solution: VueJS is a JavaScript based frontend framework which can be used to develop much
interactive single page applications, and API calls can also be made in the framework. Thus, it can
be very well integrated with APIs.
Week 6 Practice Questions
A. It stores the data in the form of key value pairs in the browser for an origin.
B. Data stored in session storage expires when page session ends.
C. Session storage data persists even after the page session expires.
D. None of the above
Answer: A and B
A. It stores the data in the form of key value pairs in the browser for an origin.
B. Data stored in local storage expires when the page session ends.
C. Local storage data persists even after the page session expires.
D. None of the above
Answer: A and C
Solution: Some details about local storage can be found in below link
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Q3: Consider the following Vue application with markup index.html, and javascript file
app.js,
index.html:
<div id = "demo">
<input v-model = "name" v-on:change = "check" />
<p :class = "[isError ? 'btn btn-danger' : 'btn btn-success']"> Correct?
</p>
</div>
<script src = "app.js">
app.js:
if (this.name.length > 3)
this.isError = false;
else
this.isError = true;
localStorage.name = this.name;
localStorage.isError = this.isError;
}
}
})
Say you open the “index.html” file in a browser, and write “abhi” in the text input shown on
screen, and force reload the page (without clicking anywhere). What will be the value in the
input text box and class applied to the paragraph element with text “Correct?”, respectively?
Answer: D
Solution: When you enter the text “abhi” in the text box and force reload the page (without
clicking anywhere outside the text box), the “change” event will not be triggered. After force
reloading the page, the mounted() hook will not be triggered, but the values of keys “name” and
“isError” in the local storage are not present, so they will be initialized to their values defined in
the Vue app instance, which means, “name” will be initialized with an empty string, whereas,
“isError” will get the value “true” (a boolean value).
Answer: B
Solution: In general, the data should always be validated at the server end even if all the
validations are being done on front end using JavaScript, as a request may not always come
through a browser, but can be sent using CLI utilities like curl.
The browser does provide simple validations for some inputs elements.
Answer: A, B and D
Q6: The below code is trying to validate a form, ensuring the number of items ordered
are 10 and minimum of 2 items of each are added. Fill in code1.
index.html:
<form @submit.prevent="validateForm">
<p v-if="errors.length">
<b>Please correct the following error(s):</b>
<ul>
<li v-for="error in errors">{{ error }}</li>
</ul>
</p>
<h1>
Add to Grocery
</h1>
<p>
<input
v-model.number="bread" type="number"> Bread <br/>
<input
v-model.number="cheese" type="number"> Cheese <br/>
<input v-model.number="butter" type="number"
name="butter"> Butter <br/>
</p>
<p>
Total Items added : {{totalItems}}
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
app.js:
validateForm() {
this.errors = [];
if( code1){
this.errors.push('Minimum quantity of each item should be 2');
}
if (this.total != 10 ) {
this.errors.push('Total items must be 10!');
}
if (!this.errors.length) {
return true;
}
}
Answer: A
Solution: The validation needs to check that none of the items are less than 2, if anyone of the
items are less than 2, it should flag an error.
A. *.js
B. *.html
C. *.vue
D. None of the above
Answer: C
Solution: In SFC, a single file has HTML, JavaScript and CSS. The file extension is *.vue
Q8: Which of the following Vue directives can be used to selectively display error
messages?
A. v-if
B. v-show
C. v-html
D. Both A and B
Answer D
Solution : Both v-if and v-show can be used for conditional rendering ,difference being with
v-show the element remains on the DOM and toggles the display CSS property of the element.
Q9: Form data validations can be done at:
A. client-side
B. server-side
C. Both A and B
D. only on the client-side
Answer: C
Q1: Consider the following markup index.html and JavaScript app.js for a Vue
application.
app.js:
const home = {
template: `
<h2> Home Page</h2>
`,
}
const profile = {
template: `
<h2> Welcome {{this.$route.params.name}} </h2>
`,
}
const routes = [
{ path: '/', component: home },
{ path: '/profile/:name', component: profile },
]
<div id="app">
<div>
<router-link to="/"> Home </router-link>
<router-link to="/profile/narendra"> Profile </router-link>
</div>
<router-view></router-view>
</div>
<script src="app.js"></script>
What will be rendered inside the router-view, when user loads the application for first time, and
when user clicks on the link “Profile”, respectively?
Answer: A
Solution: Because the base property of router object is ‘ / ’. The components related to ‘ / ’.
Which is home will be rendered inside the router-view hence Home Page. Clicking on Profile
will redirect the user to the path mentioned in ‘to’ prop. So, the component related to ‘/profile’ will
be rendered and the value of the route parameter ‘name’ will be ‘narendra’. So, Option A is
correct.
Q2: Which of the following component is used to render the component matched by the
path in router-enabled app?
A. router-view
B. router-link
C. router-model
D. None of the above
Answer: A
Solution: router-view component is used to render the component matched by the path in
router-enabled app.
Q3: Which of the following component is used to enable user navigation in
router-enabled app?
A. router-view
B. router-link
C. router-model
D. None of the above
Answer: B
A. <h4>
B. <li>
C. <b>
D. <a>
Answer: D
Answer B, C and D
Solution: Vuex is a state management library for Vue.js applications, which helps create a
centralized store for all components in an application. This is especially useful in medium/ large
scale applications. State should be changed only through mutations, so that the changes can be
tracked easily(on Vue DevTools).
Q6: Which of the following should be used in order to compute derived state based on
store state, e.g. filtering through a list of data etc.?
A. Mutations
B. Getters
C. Actions
D. State
Answer B
Solution: Getters are used. Vuex allows us to write methods /handlers which can compute
derived state based on store state.
Answer D
Solution: One should change the state only through mutation handlers, so that the DevTools
can capture the state changes. So it is important that these handlers are synchronous, so that
every mutation can be logged. Whereas the Action handlers can be asynchronous, and in turn
the action handlers can commit mutations within it.
Q8: Which of the following statements holds good for Single-page applications (SPA)?
A. SPA loads only a single web document and then updates body content dynamically as
and when required.
B. SPAs are faster, and gives a better user experience.
C. Some frameworks supporting SPA are AngularJS, ReactJS and VueJS.
D. All of the above
Answer D
Solution: In SPA, dynamic updation of the page happens instead of the browser loading a whole
new page, which in turn makes transactions faster and gives a better user experience.
Q9: When a component needs to make use of multiple store state properties, which of
the below can we make use of?
A. mapGetters
B. mapState
C. mapActions
D. None of the above
Answer: B
Solution: The “mapState” helper, generates computed getter functions for us, which helps us
avoid some repetitive coding.
A. mail.google.com
B. drive.google.com
C. twitter.com
D. wikipedia.org
Answer: D
Week 8 Practice Questions
Answer: D
Solution: All the given options are considered to be good aspects for implementing a web API.
A. Python
B. Java
C. C++
D. None of the above
Answer: A, B and C
Solution: GraphQL provides support for many programming languages. You can read the list at
GraphQL Code Libraries, Tools and Services
Answer: A and C
Solution: A CMS (Content Management System) allows a user to create a website without the
knowledge of any programming language. For Ex: WordPress
Every CMS does not necessarily allow user management.
Q4: Which of the following statement(s) is/are true regarding REST API?
Answer: A and C
Solution: An API is generally implemented for a frontend developer to utilize, which helps in
decoupling the frontend from the backend. An API can have multiple endpoints for
fetching/creating/updating resources.
Q5: Which of the following statement(s) is/are true regarding RESTful APIs?
Answer: A and C
Solution: A REST API consists of multiple endpoints, where a single endpoint generally deals
with a single entity or resources. An API endpoint can be meant for reading or writing operations
on the database.
Q6: Which of the following statement(s) is/are false in the context of REST?
A. The HTTP GET method should not trigger a write operation on the database.
B. The HTTP POST method should not trigger a write operation on the database.
C. The HTTP DELETE method should be safe.
D. The HTTP PATCH method requests are not cacheable.
Answer: B and C
Solution: These are the convention, which a developer should adhere to while implementing and
API. A GET request is meant for a reading operation, but a POST or PATCH request creates
resources or make changes in the database.
Q7: Which of the following can be considered the best practices for defining the
endpoints in a REST API?
Answer: A and B
Solution: These are the convention, which a developer should keep in mind to while
implementing and API.
A. A permalink is a permanent link which is not expected to change throughout the lifetime
of a resource.
B. A permalink is always human-readable.
C. A permalink can be used to identify a resource uniquely.
D. An access link to a Google Doc is an example of a permalink.
Answer: B
Solution: A permalink (also known as permanent link) is meant to be the same throughout the
lifetimes of the resource. They are not always human-readable, and can consist of arbitrary
characters. Google Doc access link is an example of permalink, as it never gets changed after
its creation.
Week 10 Practice Questions
Answer: B and D
Solution: Webhooks are also called “Reverse API” because it used to push information to the
client. It uses HTTP protocol.
Answer: A and C
Solution: Using Curl and insomnia, you can send request to the server so, it can be used to
debug webhooks.
GraphQL is not a tool, but a specification or a new API standard.
Answer: B
Solution: Webhooks typically use HTTP POT method. Its response should indicate the status
code and should have minimal content in the response.
Answer: A and C
Solution: Web socket is a protocol layered over the TCP. It is used for bidirectional
communication and keep the connection open throughout the communication.
Q5: Which of the following statement(s) is/are true regarding browsers Push API?
A. It can push messages to the application only when the application is loaded on a user
agent.
B. It can push messages to the application even if the application is not loaded on a user
agent.
C. Application should have an active service worker.
D. Application may not have an active service worker.
Answer: B and C
Solution: Push API can push messages to the application even if the application is not loaded
on a user agent. It requires an active service worker.
A. Polling is a mechanism in which a client sends a request for data repetitively after a fixed
time interval.
B. Response from the server can be empty.
C. Response from the server can never be empty.
D. None of the above
Answer: A and B
Solution: Polling is a mechanism in which client sends a request for message repeatedly after a
fixed amount of time interval and if server has the message then it will send the message or it
can send out empty response.
Answer: A and B
Solution: A webhook allow two applications to communicate with each other. It pushes the
message on the channel to the clients who have subscribed for the channel.
A. There are three main components of the architecture, event producer, event router,
event consumer.
B. Event producer publish messages to the event router.
C. Event producer publish messages to the event consumer.
D. Event router publish the messages to the event consumer.
Answer: A, B and D
Solution: In event driven architecture there are three main components, even producer, event
router and event consumer. Event producers publish the message to the event router, which
filters and pushes the event to the event consumer.