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 core topics, concepts, and principles essential for the exam, along with key equations (where applicable) and Mermaid knowledge graphs to visualize relationships.
this Keyword:
this; they inherit from the enclosing lexical scope.this refers to the element that triggered the event (unless arrow functions are used).Promises & Async/Await:
Promise can only resolve or reject once (first call determines the outcome)..then() handles resolved values; .catch() handles rejections.setTimeout delays).Example:
new Promise((resolve) => resolve("Success"))
.then(console.log) // Logs "Success"
.catch(console.log); // SkippedEvent Loop & Asynchronous Operations:
setTimeout, fetch) are queued and executed after the call stack is empty.Promise callbacks).Example:
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
// Output: A → D → C → BClosures & Lexical Scoping:
this from their surrounding scope.Example:
const obj = { propA: 20 };
const func = () => console.log(this.propA); // `this` is lexical (not `obj`).
func.call(obj); // Logs `undefined` (or global `propA` if defined).Array Methods:
reduce((acc, val, idx, arr) => {...}, initialValue): Accumulates values.
arr[idx + 1] may return undefined for the last element.map, filter, slice: Functional transformations.Example:
[1, 2, 3].reduce((acc, _, idx, arr) => acc + arr[idx + 1], 0); // NaN (last iteration: `arr[3]` is undefined)Component Lifecycle Hooks:
beforeCreate → created → beforeMount → mounted → beforeUpdate → updated → beforeUnmount → unmounted.Key Hooks:
created: Data/props are initialized.mounted: DOM is ready.beforeUnmount: Cleanup (e.g., remove event listeners).Vuex (State Management):
commit).dispatch).Example:
actions: {
asyncUpdate({ commit }) {
const data = await fetchData();
commit("UPDATE_STATE", data); // Mutation
}
}Slots & Scoped Slots:
<slot></slot> (fallback content if not provided).<slot name="header"></slot>.Scoped Slots: Pass data from child to parent via v-slot.
Syntax:
<child-component>
<template v-slot:default="slotProps">
{{ slotProps.user.name }}
</template>
</child-component>Vue Router:
<router-link> and <router-view>.Navigation Guards: Redirect based on auth/roles.
Example:
router.beforeEach((to, from, next) => {
if (!isAuthenticated) next("/login");
else next();
});HTTP Methods:
POST: Used for webhooks (sending data to a server).GET: Retrieve data.PUT/PATCH: Update resources.DELETE: Remove resources.Performance Metrics (Lighthouse):
CORS (Cross-Origin Resource Sharing):
Headers:
Access-Control-Allow-Origin: Specifies allowed origins.Access-Control-Allow-Methods: Allowed HTTP methods.Example:
# Flask
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}})JWT (JSON Web Tokens):
Flow:
localStorage).Authorization: Bearer <token> header with each request.header.payload.signature (Base64-encoded).Flask Threading:
threaded=False: Requests are processed sequentially (blocking).
/slow endpoints with time.sleep(15) and time.sleep(25) will take 40 seconds total.threaded=True: Requests run in parallel.Caching (Redis):
Example:
@cache.cached(timeout=100) # Cache for 100 seconds
def slow_api():
time.sleep(25)
return "Data"Fetch API:
Common Errors:
TypeError: Network failure (e.g., CORS, offline).HTTP error: Non-200 status (e.g., 404, 500).Missing return:
const data = await response.json(); // Forgot `return` → Promise pending.Vue Reactivity:
state.items[0] = x) won’t trigger updates.Vue.set or array methods like push.Modulo Operations (Question 21):
y % 7 === 6: Checks if y leaves a remainder of 6 when divided by 7.y % 5 === 4: Checks if y leaves a remainder of 4 when divided by 5.27 % 7 = 6 (True), 125 % 5 = 0 (False).Array reduce Accumulation (Question 8):
acc + array[idx + 1]:
0 + 2 = 22 + 3 = 55 + undefined = NaNAsynchronous Timing (Question 22):
Sequential blocking requests:
/slow1 (15s) + /slow2 (25s) = 40s total (no threading).JavaScript:
this binding, event loop timing, and Promise states.reduce/map edge cases (e.g., undefined values).Vue.js:
v-slot syntax are frequently tested.Web Tech:
Performance:
Debugging:
return statements in async functions.