Quiz Space

January 2025 term · Modern Application Development II · BSCS2006

MAD 2 End Term: 13 April 2025, Set QDD1 (January 2025 term)

The IIT Madras BS Modern Application Development II (MAD 2) End Term paper sat on 13 Apr 2025, in the January 2025 term, set QDD1: 32 questions for 100 marks in 180 minutes. Every question is below with its answer. Take it as a timed mock test to be marked, or read it through first.

Questions
32
Marks
100
Duration
180 min
MCQ
28
MSQ
3
Numerical
1

Updated

Official paper: IIT M DIPLOMA AN EXAM QDD3 13 Apr 2025 · No negative marking.

Question 1

+2 marksOne correct option

Which of the following statements is true regarding the "this" keyword in JavaScript?

  1. A

    It always refers to the global object.

  2. B

    Arrow functions have their own "this" context.

  3. C

    "this" in an event listener always refers to the window object.

  4. D

    None of these

Show answer

Correct answer

  • D

    None of these

Question 2

+2 marksOne correct option

Which of the following correctly describes the lifecycle of a Vue.js component?

  1. A

    beforeCreate -> created -> beforeMount -> mounted -> beforeUpdate -> updated -> beforeUnmount -> unmounted

  2. B

    beforeCreate -> created -> beforeMount -> beforeUpdate -> mounted -> updated -> beforeUnmount -> unmounted

  3. C

    created -> beforeCreate -> beforeMount -> mounted -> updated -> beforeUnmount -> unmounted

  4. D

    created -> beforeCreate -> beforeMount -> mounted -> beforeUnmount -> updated -> unmounted

Show answer

Correct answer

  • A

    beforeCreate -> created -> beforeMount -> mounted -> beforeUpdate -> updated -> beforeUnmount -> unmounted

Question 3

+2 marksOne correct option

Consider the below JavaScript program.

javascript
const promise = new Promise((resolve, reject) => {
resolve('Success!');
reject('Failed!');
});
promise.then(console.log).catch(console.log);

What will be the output of the above program?

  1. A

    Success
    Failed

  2. B

    Success

  3. C

    Failed

  4. D

    Error

Show answer

Correct answer

  • B

    Success

Question 4

+2 marksOne correct option

Which of the following is NOT a common performance metric measured by Google Lighthouse?

  1. A

    First Contentful Paint (FCP)

  2. B

    Time to Interactive (TTI)

  3. C

    Total Blocking Time (TBT)

  4. D

    Database Query Time (DQT)

Show answer

Correct answer

  • D

    Database Query Time (DQT)

Question 5

+2 marksOne correct option

Which of the following is a key difference between Web Sockets and Server-Sent Events (SSE)?

  1. A

    SSE allows bidirectional communication, while WebSockets only allow server- to-client communication.

  2. B

    WebSockets maintain a persistent connection, while SSE creates a new connection for each message.

  3. C

    SSE works over HTTP and only supports server-to-client communication, whereas WebSockets provide full-duplex communication.

  4. D

    WebSockets require an HTTP request for every message sent.

Show answer

Correct answer

  • C

    SSE works over HTTP and only supports server-to-client communication, whereas WebSockets provide full-duplex communication.

Question 6

+2 marksOne correct option

Which HTTP method is typically used for sending webhook notifications?

  1. A

    GET

  2. B

    POST

  3. C

    DELETE

  4. D

    PATCH

Show answer

Correct answer

  • B

    POST

Question 7

+3 marksOne correct option
  1. A

    6

  2. B

    NaN

  3. C

    undefined

  4. D

    0

  5. E

    NULL

Show answer

Correct answer

  • B

    NaN

Question 8

+3 marksOne correct option

Consider the below JavaScript program.

javascript
const obj = {
num: 5,
multiply: function () {
return this.num * 2;
},
};
const multiply = obj.multiply;
console.log(multiply());

What will be the output of the above program?

  1. A

    10

  2. B

    undefined

  3. C

    NaN

  4. D

    NULL

  5. E

    Error

Show answer

Correct answer

  • C

    NaN

Question 9

+3 marksOne correct option

Consider the below Vuex store configuration:

javascript
const store = new Vuex.Store({
state: {
items: [],
},
mutations: {
addItem(state, item) {
state.items.push(item);
},
},
actions: {
addItemAsync({ commit }, item) {
setTimeout(() => {
commit('addItem', item);
}, 1000);
},
},
});

If the addItemAsync action is dispatched with the item 'Vue.js', what will be the state of items after 2 seconds?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 10

+3 marksOne correct option

Consider the below Vue app.

html
<div id="app">
<router-link to="/foo">Go to Foo</router-link>
<router-view></router-view>
</div>
<script>
const Foo = { template: '<div>Foo</div>' };
const Bar = { template: '<div>Bar</div>' };
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
{ path: '/', component: Bar }
];
const router = new VueRouter({ routes });
new Vue({
el: '#app',
router
});
</script>

What happens when the user clicks "Go to Foo"?

  1. A

    Browser navigates to /foo and displays "Foo".

  2. B

    Browser navigates to /foo but displays nothing.

  3. C

    Error: No matching route.

  4. D

    None of these

Show answer

Correct answer

  • A

    Browser navigates to /foo and displays "Foo".

Question 11

+3 marksOne correct option

Consider the following Vue component using slots:

javascript
Vue.component("alert-box", {
template: `
<div class="alert-box">
<strong><slot name="title">Default title</slot></strong>
<slot>Default content</slot>
</div>
`,
});

How would you use this component to provide custom title and content in the slots?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • C

Question 12

+3 marksOne correct option

Consider the following Vue component.

javascript
Vue.component('user-list', {
data() {
return {
users: [
{ id: 1, name: 'Arbok', role: 'Admin' },
{ id: 2, name: 'Bayleaf', role: 'User' },
{ id: 3, name: 'Charzard', role: 'Moderator' }
]
}
},
template: `
<div>
<slot name="header"></slot>
<ul>
<li v-for="user in users" :key="user.id">
<slot :user="user">
{{ user.name }}
</slot>
</li>
</ul>
</div>
`
})

Which of the following is the correct way to use this component with a scoped slot?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • A

Question 13

+3 marksOne correct option

Consider the following JavaScript program, and predict the output, if executed.

javascript
let propA = 10;
const obj1 = {
propA : 20,
propB : function () {
console.log(propA, this.propA)
}
}
const obj2 = {
propA : 30,
propB : function () {
let func = () => console.log(propA, this.propA)
func()
}
}
obj2.propB.call(obj1);
  1. A

    10 30

  2. B

    10 undefined

  3. C

    10 20

  4. D

    The program will raise an error

Show answer

Correct answer

  • C

    10 20

Question 14

+3 marksOne correct option

Consider the following Flask application (server.py):

server.py

python
from flask import Flask
from flask_caching import Cache
import time
config = {
"DEBUG": True,
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_URL": "redis://localhost:6379/1",
"CACHE_DEFAULT_TIMEOUT": 300
}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)
@app.route('/data/<item>')
@cache.cached(timeout=100)
def get_data(item):
time.sleep(25)
return f"Data for {item}"
if __name__ == '__main__':
app.run()

The application runs on http://localhost:5000.\ A client makes two consecutive requests to http://localhost:5000/data/apple within 50 seconds
What will be the approximate absolute difference between their latencies?

  1. A

    25 seconds

  2. B

    35 seconds

  3. C

    0 seconds

  4. D

    15 seconds

Show answer

Correct answer

  • A

    25 seconds

Question 15

+3 marksOne correct option

Consider the following JavaScript code.

javascript
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) throw new Error('HTTP error');
const data = response.json();
return data;
} catch (error) {
if (error.name === 'TypeError') {
return { status: 'network error' };
}
return { status: 'http error' };
}
}

When the function is called, what will be returned if the request gives a 200 OK?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • D

Question 16

+3 marksOne correct option

Consider the following JavaScript code snippet. If the code is run on the browser, what will be the output on the console?

javascript
console.log("variable1")
setTimeout(() => {
console.log("variable2")
setTimeout(() => {
console.log("variable3")
}, 500);
}, 2000)
console.log("variable4")
  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • C

Question 17

+3 marksOne correct option

Which of the following options is the correct sequence of steps in JWT authentication?

  1. A

    Client sends credentials, server validates and responds with JWT, client stores JWT, client sends JWT with each request.

  2. B

    Client sends credentials, server validates and stores session ID, client sends session ID with each request.

  3. C

    Client sends JWT, server validates and issues a new JWT for each request.

  4. D

    Client sends JWT, server decrypts JWT and checks credentials again.

Show answer

Correct answer

  • A

    Client sends credentials, server validates and responds with JWT, client stores JWT, client sends JWT with each request.

Question 18

+3 marksOne correct option

Consider the below CORS enabled flask app.

python
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://localhost:5000"}})
@app.route("/api/data")
def data():
return {"message": "Hello from Flask"}

If a Vue.js frontend (simulation given below) at “http://localhost:3000” tries to fetch data, what will happen?

javascript
fetch("http://localhost:5000/api/data")
.then(response => response.json())
.then(data => console.log(data));
  1. A

    The request will be blocked due to CORS policy.

  2. B

    The request will succeed and return { "message": "Hello from Flask" }.

  3. C

    The request will fail because Vue.js does not support CORS.

  4. D

    The server will crash due to incorrect CORS settings.

Show answer

Correct answer

  • A

    The request will be blocked due to CORS policy.

Question 19

+4.5 marksOne correct option

Consider the below Vuex setup.

javascript
const store = new Vuex.Store({
state: {
value: 0
},
mutations: {
setValue(state, payload) {
state.value = payload;
}
},
actions: {
async updateValue({ commit }) {
const newValue = await fetchData();
commit('setValue', newValue);
}
}
});
function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve(42), 2000);
});
}
store.dispatch('updateValue');
console.log(store.state.value);

What is logged to the console immediately after dispatching the action?

  1. A

    0

  2. B

    42

  3. C

    Undefined behavior

  4. D

    Error: Action did not resolve

Show answer

Correct answer

  • A

    0

Question 20

+4.5 marksOne correct option
  1. A

    [27, 125, 343, 729, 1331]

  2. B

    [125, 343, 729]

  3. C

    [27, 125, 343]

  4. D

    None of these

Show answer

Correct answer

  • B

    [125, 343, 729]

Question 21

+4.5 marksOne correct option

Consider the following Flask application (server.py) and an HTML file named index.html:

server.py

python
from flask import Flask
import time
app = Flask(__name__)
@app.route("/api/slow1")
def slow_api_1():
time.sleep(15)
return "Response from Slow API 1", 200, {'Access-Control-Allow-Origin':
'*'}
@app.route("/api/slow2")
def slow_api_2():
time.sleep(25)
return "Response from Slow API 2", 200, {'Access-Control-Allow-Origin':
'*'}
if __name__ == "__main__":
app.run(threaded=False)

index.html

html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Flask Fetch Example</title>
</head>
<body>
<h1>Fetching API Data...</h1>
<script>
fetch("http://127.0.0.1:5000/api/slow1")
.then(res => res.json())
.then(data => console.log("API 1 Response:", data));
fetch("http://127.0.0.1:5000/api/slow2")
.then(res => res.json())
.then(data => console.log("API 2 Response:", data));
</script>
</body>
</html>

If you open index.html in a browser, approximately how long will it take for the second fetch call (http://127.0.0.1:5000/api/slow2) to complete and log the data to the console?

  1. A

    15 seconds

  2. B

    25 seconds

  3. C

    10 seconds

  4. D

    40 seconds

Show answer

Correct answer

  • D

    40 seconds

Question 22

+4.5 marksOne correct option

Consider the following Vue apps in script.js and the index.html file.

script.js

javascript
const app1 = new Vue({
el: '#app1',
data: {
value1: "VueJS",
value2: "Frontend"
}
})
const app2 = new Vue({
el: '#app2',
data: {
value3: "JavaScript"
}
})

index.html

html
<div id="app2">
{{value1}}
<div id="app1">
{{value2}}
</div>
{{value3}}
</div>
<script src="./script.js"></script>

What will be rendered on the browser?

  1. A

    Frontend

  2. B

    VueJS
    Frontend

  3. C

    VueJS
    JavaScript

  4. D

    Frontend
    JavaScript

Show answer

Correct answer

  • D

    Frontend
    JavaScript

Question 23

+4.5 marksOne correct option

Consider the following Vue App and the HTML document given below.

index.html

html
<div id="app">
<my-comp>
<slot>Hello Frontend</slot>
<slot>Hello VueJS</slot>
</my-comp>
</div>
<script src="script.js"></script>

script.js

javascript
const myComp = {
template: `
<div>
<slot></slot>
<slot></slot>
</div>
`
}
const app = new Vue({
components: {
"my-comp": myComp
}
}).$mount('#app')

What will be the output on the browser?

  1. A

    Hello Frontend Hello Frontend

  2. B

    Hello VueJS Hello VueJS

  3. C

    Hello Frontend Hello Vue JS

  4. D

    Hello Frontend Hello Vue JS Hello Frontend Hello Vue JS

Show answer

Correct answer

  • D

    Hello Frontend Hello Vue JS Hello Frontend Hello Vue JS

Question 24

+4.5 marksOne correct option

Consider the below flask implementation with JWT based authentication.

python
from flask import Flask, request, jsonify
import jwt
import datetime
app = Flask(__name__)
SECRET_KEY = "supersecret"
def generate_token(user):
return jwt.encode(
{"user": user, "exp": datetime.datetime.utcnow() +
datetime.timedelta(seconds=10)},
SECRET_KEY,
algorithm="HS256"
)
@app.route("/login", methods=["POST"])
def login():
user = request.json.get("user")
token = generate_token(user)
return jsonify({"token": token})
@app.route("/protected", methods=["GET"])
def protected():
token = request.headers.get("Authorization").split(" ")[1]
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
return jsonify({"message": f"Hello {payload['user']}!"})
except jwt.ExpiredSignatureError:
return jsonify({"error": "Token expired"}), 401
except jwt.InvalidTokenError:
return jsonify({"error": "Invalid token"}), 403

If a Vue.js client sends this request 15 seconds after login, what response will it receive (assume the token sent is the one, which was received from login)?

javascript
fetch("http://localhost:5000/protected", {
method: "GET",
headers: { "Authorization": "Bearer <JWT_TOKEN>" }
})
.then(res => res.json())
.then(console.log);
  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 25

+2 marksOne or more correct options

Which of the following is/are the correct usage of “v-for” directive in VueJS?

Select all that apply.

  1. A

    item in array

  2. B

    (item, index) of array

  3. C

    (item, index) as array

  4. D

    (item, index) in array

  5. E

    Item of array

Show answer

Correct answers

  • A

    item in array

  • D

    (item, index) in array

Question 26

+2 marksOne or more correct options

Which of the following are advantages of using GraphQL over REST?

Select all that apply.

  1. A

    It allows clients to fetch only the required fields, reducing over-fetching.

  2. B

    It replaces the need for authentication mechanisms.

  3. C

    It improves database performance automatically.

  4. D

    It enforces a strict API response format.

Show answer

Correct answer

  • A

    It allows clients to fetch only the required fields, reducing over-fetching.

Question 27

+3 marksOne or more correct options

Which of the following statements are true regarding event loop in JavaScript?

Select all that apply.

  1. A

    The event loop runs on a separate thread from the main JavaScript execution.

  2. B

    The event loop allows JavaScript to perform non-blocking operations despite being single-threaded.

  3. C

    Callbacks from setTimeout are placed in the task queue and executed after the call stack is empty.

  4. D

    All of these

Show answer

Correct answers

  • B

    The event loop allows JavaScript to perform non-blocking operations despite being single-threaded.

  • C

    Callbacks from setTimeout are placed in the task queue and executed after the call stack is empty.

Question 28

+4.5 marksNumerical answer

Consider the below Vuex store configuration.

javascript
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
});

And the below Vue component:

html
<template>
<div>
<button @click="increment">Increment</button>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
mapState(['count']),
},
methods: {
mapMutations(['increment']),
},
};
</script>

What will be displayed in the placeholder “{{ count }}” on the browser after clicking the "Increment" button 3 times?

Show answer

Correct answer: 3

Question 29

+3 marksOne correct option

Consider the following flask app implemented with JWT. The application running on http://127.0.0.1:5000 and the user logs in using the /login endpoint.

Read the following questions and select the correct statement.

python
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "supersecretkey"
jwt = JWTManager(app)
@app.route("/login", methods=["POST"])
def login():
user = {"username": "student", "role": "student"}
access_token = create_access_token(identity=user)
return jsonify(access_token=access_token)
@app.route("/protected", methods=["GET"])
@jwt_required()
def protected():
current_user = get_jwt_identity()
if current_user.get("role") != "admin":
return jsonify({"message": "Forbidden: Insufficient permissions"}),
403
return jsonify(message=f"Hello, {current_user['username']}!")
app.run()

Based on the above data, answer the given subquestions.

What will be the response by the following fetch request.

javascript
fetch("http://127.0.0.1:5000/protected", {
method: "GET"
})
.then(response => {
return response.json();
})
.then(data => console.log("Protected Route Response:", data))
.catch(error => console.error("Error:", error));
  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 30

+3 marksOne correct option

Consider the following flask app implemented with JWT. The application running on http://127.0.0.1:5000 and the user logs in using the /login endpoint.

Read the following questions and select the correct statement.

python
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "supersecretkey"
jwt = JWTManager(app)
@app.route("/login", methods=["POST"])
def login():
user = {"username": "student", "role": "student"}
access_token = create_access_token(identity=user)
return jsonify(access_token=access_token)
@app.route("/protected", methods=["GET"])
@jwt_required()
def protected():
current_user = get_jwt_identity()
if current_user.get("role") != "admin":
return jsonify({"message": "Forbidden: Insufficient permissions"}),
403
return jsonify(message=f"Hello, {current_user['username']}!")
app.run()

Based on the above data, answer the given subquestions.

What will be the result of the following fetch request.

javascript
fetch("http://127.0.0.1:5000/protected", {
method: "GET",
headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVJ9.."
}
})
.then(response => {
if (response.status === 403) {
throw new Error("403 Forbidden: Insufficient permissions");
}
return response.json();
})
.then(data => console.log("Protected Route Response:", data))
.catch(error => console.error("Error:", error));
  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • D

Question 31

+4.5 marksOne correct option

Consider the following Vue app with the Vue Router shown below and answer the given subquestions.

javascript
const Login = { template: "<p>You are not logged in.</p>" }
const Profile = { template: "<p>Welcome to profile</p>" }
const Unauthorized = { template: "<p>You are not authorized</p>" }
const router = new VueRouter({
routes: [
{ path: '/login', component: Login },
{ path: '/unauthorized', component: Unauthorized },
{ path: '/profile', component: Profile }
]
})
new Vue({
el: '#app',
router,
data:{
userRole: '',
isAuthenticated: false
},
created() {
this.checkAuthentication();
},
methods: {
checkAuthentication() {
const token = localStorage.getItem('token');
console.log(`token got: ${token}`)
this.isAuthenticated = !!token;
// this.isAuthenticated = token ? true : false
if (this.isAuthenticated) {
this.userRole = localStorage.getItem('userRole') || 'user';
console.log(`role got: ${this.userRole}`)
} else {
console.log("no token got")
this.$router.replace('/login');
}
},
javascript
hasAccess(requiredRole) {
const roleHierarchy = {
'admin': 3,
'manager': 2,
'user': 1
};
const currentRoleLevel = roleHierarchy[this.userRole] || 0;
const requiredRoleLevel = roleHierarchy[requiredRole] || 0;
console.log(`current role: ${this.userRole}`)
console.log(`required role: ${requiredRole}`)
return currentRoleLevel >= requiredRoleLevel;
}
},
mounted() {
if (!this.hasAccess('manager')) {
console.log("has manager access")
this.$router.replace('/unauthorized');
}
else{
console.log(`has ${this.userRole} access`)
this.$router.replace('/profile')
}
}
})

What will be rendered on the browser if the application is loaded on the browser for the first time?

  1. A

    You are not logged in.

  2. B

    Welcome to profile

  3. C

    You are not authorized.

  4. D

    None of these.

Show answer

Correct answer

  • C

    You are not authorized.

Question 32

+3 marksOne correct option

Consider the following Vue app with the Vue Router shown below and answer the given subquestions.

javascript
const Login = { template: "<p>You are not logged in.</p>" }
const Profile = { template: "<p>Welcome to profile</p>" }
const Unauthorized = { template: "<p>You are not authorized</p>" }
const router = new VueRouter({
routes: [
{ path: '/login', component: Login },
{ path: '/unauthorized', component: Unauthorized },
{ path: '/profile', component: Profile }
]
})
new Vue({
el: '#app',
router,
data:{
userRole: '',
isAuthenticated: false
},
created() {
this.checkAuthentication();
},
methods: {
checkAuthentication() {
const token = localStorage.getItem('token');
console.log(`token got: ${token}`)
this.isAuthenticated = !!token;
// this.isAuthenticated = token ? true : false
if (this.isAuthenticated) {
this.userRole = localStorage.getItem('userRole') || 'user';
console.log(`role got: ${this.userRole}`)
} else {
console.log("no token got")
this.$router.replace('/login');
}
},
javascript
hasAccess(requiredRole) {
const roleHierarchy = {
'admin': 3,
'manager': 2,
'user': 1
};
const currentRoleLevel = roleHierarchy[this.userRole] || 0;
const requiredRoleLevel = roleHierarchy[requiredRole] || 0;
console.log(`current role: ${this.userRole}`)
console.log(`required role: ${requiredRole}`)
return currentRoleLevel >= requiredRoleLevel;
}
},
mounted() {
if (!this.hasAccess('manager')) {
console.log("has manager access")
this.$router.replace('/unauthorized');
}
else{
console.log(`has ${this.userRole} access`)
this.$router.replace('/profile')
}
}
})

What will be rendered on the browser for the given value of localStorage?

  1. A

    You are not logged in.

  2. B

    Welcome to profile

  3. C

    You are not authorized.

  4. D

    None of these.

Show answer

Correct answer

  • B

    Welcome to profile