Home / Past papers / MAD2 End Term / this paper

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?
Consider the below JavaScript program. ```javascript let arr = [1, 2, 3]; let sum = arr.reduce((acc, val, idx, array) => acc + array[idx + 1], 0); console.log(sum); ``` What will be the output of the above program?

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?
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?
The image shows a single vertical bar character.

``` ['Vue.js', 'Vue.js'] ```

``` ['Vue.js'] ```

[object]

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"?
Consider the following Vue component using slots:
```
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?
```html <alert-box title="Custom Title">Custom content</alert-box> ```

```html
<alert-box>
<slot name="title">Custom Title</slot>Custom content
</alert-box>
```
```html
<alert-box>
<template v-slot:title>
Custom Title
</template>
Custom content
</alert-box>
```
```html <alert-box>Custom Title - Custom content</alert-box> ```
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?
```html
<user-list v-slot="{ user }">
<template>{{ user.name }} ({{ user.role }})</template>
</user-list>
```
```html
<user-list>
<template v-slot:default="{ user }">
{{ user.name }} ({{ user.role }})
</template>
</user-list>
```
```html
<user-list>
<template scope="{ user }">
{{ user.name }} ({{ user.role }})
</template>
</user-list>
```
```html
<user-list>
<template slot-scope="{ user }">
{{ user.name }} ({{ user.role }})
</template>
</user-list>
```
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);
```
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?
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?
```
{ status: 'http error' }
```
```
{ status: 'network error' }
```
JSON data

The promise will remain pending

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")
```
variable1 variable2 variable3 variable4

variable1 variable4 variable3 variable2

variable1 variable4 variable2 variable3

variable1 variable3 variable4 variable2

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));
```
Consider the below Vuex setup.
What is logged to the console immediately after dispatching the action?```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 will be logged to the console when the following JavaScript code runs? ```javascript const alpha = [3, 5, 7, 9, 11, 13, 15, 17]; const beta = alpha.map(x => x ** 3); const gamma = beta.filter(y => (y % 7 === 6) || (y % 5 === 4)); const delta = gamma.slice(0, 3); console.log(delta); ```

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?
Consider the following Vue apps in script.js and the index.html file.
What will be rendered on the browser?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>
```
Consider the following Vue App and the HTML document given below.
What will be the output on the browser?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')
```
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);
```
```json
{ "message": "Hello user!" }
```
```json
{ "error": "Token expired" }
```
```json
{
"error": "Invalid token"
}
```
```json
{
"message": "Access granted"
}
```
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?

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));
```
The request will be processed successfully, and "Hello, student!" will be returned.

The request will fail with a 401 Unauthorized error.

The request will return an empty response with a 200 OK status.

The request will fail with a 403 Forbidden error.

What will be the result of the following fetch request.
```javascript
fetch("http://127.0.0.1:5000/protected", {
method: "GET",
headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.."
}
})
.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));
```
The request will be processed successfully, and "Hello, student!" will be returned.

The request will fail with a 401 Unauthorized error.

The request will return an empty response with a 200 OK status.

The request will fail with a 403 Forbidden error.
Consider the following Vue app with the Vue Router shown below and answer the given subquestions.
Consider the following Vue app with the Vue Router shown below and answer the given subquestions.
What will be rendered on the browser for the given value of localStorage?
```
{
token: 112,
userRole: "manager"
}
```Auto-generated summary from the source site. Handy as a checklist; the lessons above explain each idea from scratch.
Here’s a structured summary of the core topics, concepts, principles, and equations (where applicable) for the "Modern Application Development II" exam, along with Mermaid knowledge graphs to visualize relationships.
this Keyword
this; they inherit from the surrounding scope.this refers to the element that triggered the event (unless arrow functions are used).Promises & Async/Await
Promise represents an asynchronous operation (states: pending, fulfilled, rejected)..then() handles fulfillment, .catch() handles rejection.Example:
const promise = new Promise((resolve, reject) => resolve("Success!"));
promise.then(console.log); // Output: "Success!"Async/Await: Syntactic sugar for promises.
async function fetchData() {
const data = await fetch('url');
return data.json();
}Closures & Scope
Example:
function outer() {
let x = 10;
return function inner() { console.log(x); };
}
const innerFunc = outer();
innerFunc(); // Output: 10Event Loop & Asynchronous JavaScript
setTimeout, setInterval, I/O.Promise callbacks, queueMicrotask().Execution Order:
Array Methods
map, filter, reduce, slice, splice.Example (Reduce):
[1, 2, 3].reduce((acc, val) => acc + val, 0); // Output: 6Component Lifecycle Hooks
beforeCreate → created → beforeMount → mounted → beforeUpdate → updated → beforeUnmount → unmounted.Vuex (State Management)
Example:
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) { state.count++; }
},
actions: {
asyncIncrement({ commit }) {
setTimeout(() => commit('increment'), 1000);
}
}
});Vue Router
<router-link> and <router-view>.Example:
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
];
const router = new VueRouter({ routes });Slots (Content Distribution)
<slot></slot><slot name="header"></slot>Scoped Slots: Pass data to child components.
<template v-slot:default="{ user }">
{{ user.name }}
</template>Directives
v-for, v-if, v-show, v-bind, v-on, v-model.HTTP Methods
GET (retrieve), POST (create), PUT (update), DELETE (remove), PATCH (partial update).POST to send notifications.ws://, wss:// | HTTP | | Direction | Full-duplex | Server → Client | | Connection | Persistent | Persistent | | Binary Data | Yes | No (text-only) |CORS (Cross-Origin Resource Sharing)
Headers:
Access-Control-Allow-Origin: Specifies allowed origins.Access-Control-Allow-Methods: Allowed HTTP methods.JWT (JSON Web Tokens)
Header.Payload.SignatureFlow:
localStorage).Authorization: Bearer <token>).Performance Metrics (Lighthouse)
Flask Basics
Example:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World!"Flask-Caching (Redis)
Example:
from flask_caching import Cache
cache = Cache(app, config={'CACHE_TYPE': 'RedisCache'})
@app.route('/data')
@cache.cached(timeout=50)
def get_data():
return "Cached Data"Flask-JWT
Example:
from flask_jwt_extended import JWTManager, jwt_required
app.config["JWT_SECRET_KEY"] = "secret"
jwt = JWTManager(app)
@app.route('/protected')
@jwt_required()
def protected():
return "Authorized"Concurrency in Flask
threaded=True enables multithreading.Lighthouse Metrics
Caching Strategies
localStorage, sessionStorage.Asynchronous Loading
async/defer for scripts.import()).Debouncing & Throttling
(Not directly tested in this exam, but useful for array manipulations.)
Array Reduce ``javascript [a1, a2, ..., an].reduce((acc, val) => acc + val, initialValue); ``
[1, 2, 3].reduce((acc, x) => acc + x, 0) = 6Filtering Arrays ``javascript array.filter(x => condition); ``
[1, 2, 3].filter(x => x % 2 === 0) = [2]Modulo Operations
x % n gives the remainder of x / n.this in JavaScript
this.this refers to the element (unless arrow functions are used).Promises
resolve()/reject() are ignored.Example (Q4):
const promise = new Promise((resolve, reject) => {
resolve("Success!");
reject("Failed!"); // Ignored
});Vue.js Reactivity
array[0] = x) does not trigger reactivity.Vue.set or array methods like push, splice.Asynchronous Code
setTimeout with 0 delay still defers execution to the task queue.Example (Q17):
console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");
// Output: A → C → BCORS
Access-Control-Allow-Origin in responses.403 or 401 errors.JWT Expiry
exp claim.exp: 10s fails after 15s.Vuex State Updates
Slots in Vue.js
<slot></slot><slot name="header"></slot>Scoped slots: Pass data to parent.
<template v-slot:default="{ user }">
{{ user.name }}
</template>| Question | Topic | Key Takeaway |
|---|---|---|
| Q2 | this in JavaScript | Arrow functions inherit this; others depend on call context. |
| Q3 | Vue.js Lifecycle | Order: beforeCreate → created → beforeMount → mounted → ... |
| Q4 | Promises | First resolve/reject wins; others are ignored. |
| Q6 | WebSockets vs. SSE | WebSockets: full-duplex; SSE: server→client only. |
| Q7 | Webhooks | Typically use POST. |
| Q8 | Array reduce | Watch for undefined in edge cases. |
| Q9 | this in extracted methods | Loses context unless bound. |
| Q10 | Vuex Async Actions | dispatch is async; state updates after commit. |
| Q14 | this in Arrow Functions | Lexical scoping: this refers to the surrounding context. |
| Q15 | Flask Caching | First request: slow; subsequent requests: cached (faster). |
| Q16 | Async/Await | Missing return in fetch leaves the promise pending. |
| Q17 | Event Loop | setTimeout callbacks run after the call stack is empty. |
| Q18 | JWT Authentication | Flow: Credentials → JWT → Store → Send with requests. |
| Q19, Q30, Q31 | CORS & JWT | Check Access-Control-Allow-Origin and token expiry. |
| Q21 | Array Methods (map, filter) | Chaining operations: map → filter → slice. |
| Q22 | Flask Threading | Without threaded=True, requests block each other. |
| Q24 | Vue Slots | Default slots fall back to content; named slots require v-slot. |
| Q25 | JWT Expiry | Tokens expire based on exp; 403 if expired. |
| Q26 | Vue v-for | Syntax: item in array or (item, index) in array. |
| Q27 | GraphQL vs. REST | GraphQL reduces over-fetching; REST returns fixed structures. |
| Q28 | Event Loop | Single-threaded but non-blocking via event loop. |
| Q29 | Vuex Mutations | Must be synchronous; use actions for async. |
| Q32, Q33 | Vue Router & Auth | Redirects based on isAuthenticated and userRole. |