Home / Past papers / MAD2 End Term / this paper

Consider the below JavaScript program.
```javascript
const promise = new Promise(((resolve, reject) => {
reject('Error!');
resolve('Success!');
}));
promise.then(console.log).catch(console.log);
```
What will be the output of the above program?
Consider the below JavaScript program. ```javascript let arr = [4, 5, 6]; let sum = arr.reduce((acc, val, idx, array) => acc + (array[idx - 1] || 0), 0); console.log(sum); ``` What will be the output of the above program?

Consider the below JavaScript program.
```javascript
const obj = {
num: 8,
multiply: function () {
return this.num * 3;
},
};
const multiply = obj.multiply.bind({ num: 2 });
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: ['Vue', 'React'],
},
mutations: {
removeItem(state, item) {
state.items = state.items.filter(i => i !== item);
},
},
actions: {
removeItemAsync({ commit }, item) {
setTimeout(() => {
commit('removeItem', item);
}, 500);
},
},
});
```
If the addItemAsync action is dispatched with the item 'Vue', what will be the state of items after 2 seconds?
Consider the below Vue app.
```html
<div id="app">
<router-link to="/home">Go to Home</router-link>
<router-view></router-view>
</div>
<script>
const Home = { template: '<div>Home</div>' };
const About = { template: '<div>About</div>' };
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About },
{ path: '*', redirect: '/home' }
];
const router = new VueRouter({ routes });
new Vue({
el: '#app',
router
});
</script>
```
What happens when the user navigates to an undefined route like "/random"?
Consider the following Vue component:
```javascript
Vue.component('search-component', {
data() {
return {
searchQuery: ''
}
},
watch: {
searchQuery(newQuery, oldQuery) {
this.fetchResults(newQuery)
}
},
methods: {
fetchResults(query) {
// Fetch search results
}
}
})
```
Which of the following statements is true?
Consider the following JavaScript code.
```javascript
function processArray(arr) {
let result = arr.filter(item => item > 5)
.map(item => item * 2)
.reduce((sum, item) => sum + item, );
return result;
}
```
What will be returned when processArray([2, 6, 4, 8, 3]) is called?
Examine the following JavaScript code.
```javascript
function processData() {
let data = [1, 2, 3, 4];
let result = data.forEach(item => {
if (item % 2 === 0) {
return item * 10;
}
});
return result;
}
```
What will be returned when processData() is called?
Consider the following JavaScript code.
```javascript
var value = 30;
const firstObj = {
value: 10,
displayValue: function() {
return this.value;
}
};
const secondObj = {
value: 20
};
const displayValue1 = firstObj.displayValue.apply(secondObj);
const displayValue2 = firstObj.displayValue.apply();
const displayValue3 = function() {
return firstObj.displayValue.apply(this);
}.call(secondObj);
const displayValue4 = firstObj.displayValue.bind(this)(20);
console.log("val1", displayValue1);
console.log("val2", displayValue2);
console.log("val3", displayValue3);
```
What will be the output of the above code on the browser's console?
Consider the following JavaScript code.
```javascript
export default {
data() {
return {
loginToken: '',
};
},
mounted() {
this.loginToken = sessionStorage.getItem('authToken') || '';
},
methods: {
updateToken(newToken) {
this.loginToken = newToken;
sessionStorage.setItem('authToken', newToken);
}
}
};
```
What will happen when a user calls the updateToken method with a new value and then refreshes the page?
The new token will be lost, and the "loginToken" data property will be reset to an empty string.

The new token will be preserved in session storage, and the "LoginToken" data property will be populated with the stored value on page refresh.

The method will throw an error because sessionStorage cannot be modified directly.

The "loginToken" data property will be updated, but the session storage will remain unchanged.

Consider the below Vuex setup.
```javascript
const store = new Vuex.Store({
state: {
number: 10
},
mutations: {
updateNumber(state, payload) {
state.number = payload;
}
},
actions: {
async fetchNumber({ commit }) {
const fetchedValue = await getData();
commit('updateNumber', fetchedValue);
}
}
});
function getData() {
return new Promise(resolve => {
setTimeout(() => resolve(100), 1500);
});
}
store.dispatch('fetchNumber');
console.log(store.state.number);
```
What is logged to the console immediately after dispatching the action?
Consider the below flask SSE implementation.
```python
from flask import Flask, Response
import time
app = Flask(__name__)
def event_stream():
for i in range(5):
yield f"data: Message {i}"
time.sleep(1)
@app.route('/events')
def sse():
return Response(event_stream(), mimetype="text/event-stream")
```
And the Vue.js frontend:
```html
<template>
<div>
<p v-for="msg in messages" :key="msg">{{ msg }}</p>
</div>
</template>
<script>
export default {
data() {
return { messages: [] };
},
mounted() {
const eventSource = new EventSource("http://localhost:5000/events");
eventSource.onmessage = (event) => {
this.messages.push(event.data);
};
},
};
</script>
```
What will happen when a user opens this page?
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>
```
The application runs on http://localhost:5000.
A client makes two requests, one to http://localhost:5000/data/apple and another to http://localhost:5000/data/orange, both within 50 seconds.
What will be the approximate absolute difference between their latencies?
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?
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?
Consider the following Vue Router configuration:
```javascript
const router = new VueRouter({
routes: [
{ path: '/', component: Home },
{ path: '/user/:id', component: User },
{ path: '/about', component: About },
{ path: '*', component: NotFound }
]
})
```
Which URL/URLs would render the NotFound component?
Consider the below Vuex store configuration.
```javascript
const store = new Vuex.Store({
state: {
count: 5,
},
mutations: {
decrement(state) {
state.count--;
},
},
});
```
And the below Vue component:
```html
<template>
<div>
<button @click="decrement">Decrement</button>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
...mapState(['count']),
},
methods: {
...mapMutations(['decrement']),
},
};
</script>
```
What will be displayed in the placeholder "{{ count }}" on the browser after clicking the "Decrement" button 4 times?
How many times will "Render" be logged in the console when the Vue component below is mounted?
```html
<div id="app">
<div>{{ computedValue }}</div>
</div>
<script>
new Vue({
el: "#app",
data() {
return { count: 0 };
},
computed: {
computedValue() {
console.log("Render");
return this.count * 2;
},
},
mounted() {
this.count++;
this.count++;
},
});
</script>
```

Which of the following statements
is correct for 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?
```json
{
"token": 112,
"userRole": "admin"
}
```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, and principles essential for the "Diploma Level: Modern Application Development II" exam, along with a Mermaid knowledge graph to visualize relationships.
this Keyword:
this from the enclosing lexical scope (parent scope).this; they inherit it.Example:
const obj = { num: 2, multiply: () => this.num * 2 }; // `this` is global/window (undefined in strict mode).Promises & Async/Await:
Promise represents an asynchronous operation (pending/fulfilled/rejected)..then() handles fulfillment, .catch() handles rejection.Promise rejects and resolves, the first call (reject/resolve) takes precedence.Example:
const promise = new Promise((resolve, reject) => {
reject("Error!"); // This executes first.
resolve("Success!"); // Ignored.
});
promise.then(console.log).catch(console.log); // Output: "Error!"Array Methods:
filter(): Returns a new array with elements that pass a test.map(): Transforms each element and returns a new array.reduce(): Reduces an array to a single value (e.g., sum).forEach() does not return a value (returns undefined).Example:
[1, 2, 3].reduce((acc, val) => acc + val, 0); // 6Closures & Scope:
Example:
function outer() {
let x = 10;
return function inner() { console.log(x); }; // Remembers `x`.
}bind, call, apply:
bind(): Returns a new function with a fixed this value.call()/apply(): Invokes a function with a specific this and arguments.Example:
const obj = { num: 2 };
function multiply() { return this.num * 2; }
multiply.call(obj); // 4Component Lifecycle:
beforeCreate → created → beforeMount → mounted → beforeUpdate → updated → beforeUnmount → unmounted.created is where you typically fetch initial data.Vuex (State Management):
commit).dispatch).Example:
mutations: {
updateState(state, payload) { state.value = payload; }
},
actions: {
fetchData({ commit }) {
api.call().then(data => commit("updateState", data));
}
}Vue Router:
:param (e.g., /user/:id).*) catches all undefined routes (e.g., redirect to /home).beforeEach, beforeEnter.Example:
routes: [
{ path: "/user/:id", component: User },
{ path: "*", redirect: "/home" }
]Slots:
Example:
<template>
<slot>Default Content</slot> <!-- Fallback -->
</template>Computed Properties vs. Watchers:
Example:
computed: {
fullName() { return this.firstName + " " + this.lastName; }
},
watch: {
searchQuery(newVal) { this.fetchResults(newVal); }
}Directives:
v-for: (item, index) in array (not of or as).v-if/v-show: v-if removes DOM element; v-show hides it with display: none.v-bind (:) and v-on (@).JWT (JSON Web Tokens):
Header.Payload.Signature (Base64-encoded).localStorage (persists) or sessionStorage (cleared on tab close).CORS (Cross-Origin Resource Sharing):
Headers:
Access-Control-Allow-Origin: Specifies allowed origins.Access-Control-Allow-Methods: Allowed HTTP methods.OAuth 2.0:
SSE (Server-Sent Events):
EventSource API in the browser.Example:
const eventSource = new EventSource("/events");
eventSource.onmessage = (e) => console.log(e.data);text/event-stream MIME type.Webhooks:
Task Queues (Celery/RabbitMQ):
Routes & Views:
@app.route("/path", methods=["GET", "POST"]).Example:
@app.route("/data")
def get_data():
return jsonify({"key": "value"})JWT with Flask:
flask-jwt-extended.@jwt_required() decorator.Example:
@app.route("/protected")
@jwt_required()
def protected():
current_user = get_jwt_identity()
return jsonify(message=f"Hello, {current_user}!")CORS in Flask:
flask-cors extension.Example:
from flask_cors import CORS
CORS(app, resources={r"/api/*": {"origins": "*"}})Client-Side Routing:
Advantages:
Disadvantages:
State Management:
No direct mathematical equations were present in the questions, but here are logical patterns relevant to the exam:
Promise Resolution:
resolve and reject are called, the first call determines the outcome.promise.then().catch() handles fulfillment/rejection.Array Reduce:
array.reduce((acc, val) => acc + val, initialValue)[1, 2, 3].reduce((acc, val) => acc + val, 0) // 6Vue Reactivity:
JavaScript:
this, promises, and array methods (reduce is tricky!).bind/call/apply scenarios.Vue.js:
Authentication:
localStorage vs. sessionStorage).Asynchronous Patterns:
Flask:
time.sleep).Debugging:
console.log to track this and scope.Final Note: Focus on practical coding scenarios (e.g., promise resolution, Vuex mutations, JWT flows) and diagram-based questions (e.g., component hierarchies, lifecycle hooks). The Mermaid graphs above should help you visualize connections between topics. Good luck!