Home / MAD2 / Week 4 / Real questions
60 questions pulled from past papers whose wording matches this week's topics, newest first, duplicates removed. Pick your answers, then press Check answers. Figures and answer keys are the originals.
and JavaScript
for a Vue application: File: index.html
File: app.js
Suppose the application is running on
, and the user visits the URL:
What will be rendered by the browser? [NOTE:
is divided in two images, consider them as one file content.]

index.html
app.js
```html
<div id="app">
<router-view></router-view>
</div>
```
```javascript
const Flights = {
template: `<h2>{{ result }}</h2>`,
data() {
return {
routes: [
{ city: "Delhi", connectedTo: ["Mumbai", "Pune"] },
{ city: "Indore", connectedTo: ["Bhopal", "Jaipur"] },
{ city: "Raipur", connectedTo: ["Nagpur", "Hyderabad"] },
{ city: "Rewa", connectedTo: ["Delhi", "Indore", "Raipur"] }
],
result: ""
};
},
created() {
const destination = this.$route.params.city.toLowerCase();
for (let i = 0; i < this.routes.length; i++) {
const connections = this.routes[i].connectedTo;
for (let j = 0; j < connections.length; j++) {
if (connections[j].toLowerCase() === destination) {
this.result = this.routes[i].city;
break;
}
}
if (this.result) {
break;
}
}
}
};
```
```
http://localhost:8080
```
```
http://localhost:8080/#/raipur
```
app.js
```javascript
const router = new VueRouter({
routes: [
{
path: "/:city",
component: Flights
}
]
});
new Vue({
el: "#app",
router
});
```
The
getter is used in a Vue component as shown below:
Now suppose the Vuex getter
is removed, while the temperature state continues to be updated through Vuex mutations. Which of the following implementations correctly recreates
in the component so that it automatically reacts whenever the Vuex
changes?```javascript
const store = new Vuex.Store({
state: {
temperature: 30
},
getters: {
weatherStatus(state) {
return state.temperature >= 35 ? "Hot" : "Normal"
}
}
})
```
weatherStatus
```javascript
computed: {
weatherStatus() {
return this.$store.getters.weatherStatus
}
}
```
weatherStatus
weatherStatus
temperature
```javascript
computed: {
weatherStatus() {
return this.$store.state.temperature >= 35
? "Hot"
: "Normal"
}
}
```
```javascript
watch: {
weatherStatus() {
return this.$store.state.temperature >= 35
? "Hot"
: "Normal"
}
}
```
```javascript
methods: {
weatherStatus() {
this.$store.state.temperature >= 35
? "Hot"
: "Normal"
}
}
```
```javascript
watch: {
weatherStatus() {
return this.$store.state.temperature >= 35
}
}
```
| Column I | Column II | | :------- | :-------- | | 1. Unit Testing | A. Testing application behaviour across different browsers | | 2. E2E Testing | B. Commonly used for writing and running tests | | 3. Cross-Browser Testing | C. Testing individual Vue components independently | | 4. Jest / Mocha / Chai | D. Testing a complete application flow including backend interaction |
The developer wants to view the app in the browser locally for development. They run the following command: bash:
Which of the following best describes what happens and what the developer should have run instead?```json
{
"name": "my-vue-app",
"version": "0.1.0",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"vue": "^2.6.14"
},
"devDependencies": {
"@vue/cli-service": "^5.0.0",
"babel-eslint": "^10.1.0"
}
}
```
```
npm run build
```
launches the app on
; the developer should have run npm start to compile for production instead.``` npm run build ``` ``` localhost:8080 ```
and
do the same thing — both launch the app at 
``` npm run build ``` ``` npm run serve ``` ``` localhost:8080 ```
is correct for local development;
is only used for deploying to a server.``` npm run build ``` ``` npm run serve ```
compiles and bundles the app for production into a
folder — it does not start a local server. The developer should have run
instead.``` npm run build ``` /dist ``` npm run serve ```

| Directive | Description | |---|---| | 1. v-if | A. Two-way binding between input and data | | 2. v-for | B. Conditionally renders DOM elements | | 3. v-bind | C. Binds HTML attributes dynamically | | 4. v-model | D. Renders a list of items |

is accessed three times in a row in the template without price or discount changing in between, how many times does
get logged?discountedPrice "computing..."
file:index.html
Select all statements that correctly describe the console output:```javascript
new Vue({
el: "#app",
data: {
message: "Hello"
},
beforeCreate() {
console.log("1:", this.message);
},
created() {
console.log("2:", this.message);
},
beforeMount() {
console.log("3:", this.$el.textContent);
},
mounted() {
console.log("4:", this.$el.textContent);
}
});
```
```html
<div id="app">{{ message }}</div>
```
undefined

hello

hello

hello
Assume the API returns:
Complete the missing code so that all course names are rendered correctly. Which of the following code snippets can correctly replace
?```html
<div id="app">
<ul>
<!-- Missing Code -->
</ul>
</div>
<script>
new Vue({
el: '#app',
data: {
courses: []
},
async mounted() {
const response = await fetch('https://example.com/api/courses')
this.courses = await response.json()
}
})
</script>
```
```json
[
{ "id": 1, "name": "MAD-2" },
{ "id": 2, "name": "DBMS" }
]
```
```html
<!-- Missing Code -->
```
```html
<li v-for="course in courses" :key="course.id">
{{ course.name }}
</li>
```
```html
<li v-for="(course, index) in courses" :key="index">
{{ course.name }}
</li>
```
```html
<li v-if="course in courses">
{{ course.name }}
</li>
```
```html
<li v-for="courses in course">
{{ courses.name }}
</li>
```
Note: All three image above are of one html. Based on the above data, answer the given subquestions.

Which of the following statements are correct?```html
<div class="card" data-price="499">
<span id="title">Vue Book</span>
</div>
```
returns
.```javascript
document.querySelector(".card").dataset.price
```
"499"
converts the value to numeric
.```javascript
Number(document.querySelector(".card").dataset.price)
```
499
can read the visible text
.```javascript
document.getElementById("title").innerText
```
"Vue Book"
returns a single element, not a collection.```javascript
document.querySelectorAll(".card")
```
header.``` Authorization: Bearer <token> ```
can read the identity stored in the token.``` get_jwt_identity() ```
for loading initial data.``` created() ```
for starting DOM-related work or timers.``` mounted() ```
for cleanup.``` beforeDestroy() ```
for declaring reactive
.``` destroyed() ``` data
inside a parent route, •
, •
inside a method. Which statements are correct?children
```
{ path: '*', component: NotFound }
```
```javascript
this.$router.go(-1)
```
can be used to organize nested routes under a parent route.children
can act as a fallback for unknown routes.*
tries to go back one step in browser history.```javascript this.$router.go(-1) ```

```javascript
const store = new Vuex.Store({
state: {
discount: 10,
products: [
{name: 'apple',
price: 120
},
{
name: 'banana',
price: 60
}
]
},
mutations: {
reducePrice: state=>{
// Code1
}
}
})
```
```javascript
this.$store.state.products.forEach(product => { product.price -= (state.discount)/100*product.price; })
```
```javascript
state.products.forEach(product => { product.price -= (state.discount)/100*product.price;})
```
```javascript
commit.products.forEach(product => { product.price -= (state.discount)/100*product.price;})
```
```javascript
dispatch.products.forEach(product => { product.price -= (state.discount)/100*product.price;})
```
Component.vue
After triggering all three methods (
,
and
) one by one, which of the following statements is correct?```javascript
const store = new Vuex.Store({
state: {
cart: []
},
mutations: {
ADD_TO_CART(state, product) {
state.cart.push(product)
}
},
actions: {
addToCart({ commit }, product) {
setTimeout(() => {
commit('ADD_TO_CART', product)
}, 500)
}
}
})
```
```javascript
methods: {
addItem_A(product) {
this.$store.commit('ADD_TO_CART', product)
},
addItem_B(product) {
this.$store.dispatch('addToCart', product)
},
addItem_C(product) {
this.$store.state.cart.push(product)
}
}
```
addItem_A
addItem_B
addItem_C
and
will appear in Vue DevTools mutation history, but
will appear with a delay.addItem_A addItem_B addItem_B
will update the cart because mutations cannot be called directly from components.addItem_B
will throw an error because Vuex prevents direct state modification.addItem_C
What will be logged in the console when this component first loads?```html
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: ""
};
},
beforeCreate() {
console.log("A:", this.message);
},
created() {
console.log("B:", this.message);
this.message = "Hello from Vue!";
},
mounted() {
console.log("C:", document.querySelector("p").textContent);
}
};
</script>
```
A: "" → B: Hello from Vue! → C: Hello from Vue!

A: undefined -> B: Hello from Vue! -> C: Hello from Vue!

A: undefined → B: "" → C: Hello from Vue!

A: undefined → B: undefined → C: Hello from Vue!

A: "" -> B: "" -> C: Hello from Vue!
. The parent first updates a prop passed to the child, and then sets
. After the child has already mounted once, which sequence can occur in the child after initial render?``` v-if="show" ``` ``` show = false ```
->
->
-> 
beforeUpdate updated beforeDestroy destroyed
->
->
-> 
beforeDestroy destroyed beforeUpdate updated
->
->
-> 
created mounted beforeUpdate destroyed
->
->
-> 
updated beforeCreate destroyed mounted
and inside the child:
Which statements are correct?```html
<child-box :message="parentMsg" @reply="handleReply"></child-box>
```
```javascript
this.$emit('reply', 'ok')
```
flows from parent to child through props.message
is a custom event sent from child to parent.reply
to update the parent source of truth.message
changes in the parent, the child can receive the updated prop value.parentMsg
Why does the
value not update correctly when the button is clicked?```html
<div id="app">
<p>{{ message }}</p>
<button @click="changeMessage">Click</button>
</div>
<script>
new Vue({
el: '#app',
data: {
message: "Hello"
},
methods: {
changeMessage: () => {
this.message = "Updated"
}
}
})
</script>
```
message
should be used instead of 
v-on ``` @click ```

this
should be a function in all Vue instancesdata
If the addItemAsync action is dispatched with the item 'React', what will be the state of items after 2 seconds?```javascript
const store = new Vuex.Store({
state: {
items: ['Angular', 'Vue'],
},
mutations: {
addItem(state, item) {
state.items.push(item);
},
},
actions: {
addItemAsync({ commit }, item) {
setTimeout(() => {
commit('addItem', item);
}, 500);
},
},
});
```
What happens when the user navigates to an undefined route like "/random"?```html
<div id="app">
<router-link to="/about">Go to About</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: '/about' }
];
const router = new VueRouter({ routes });
new Vue({
el: '#app',
router
});
</script>
```
| Directive | Description | |---|---| | 1. v-if | A. Two-way data binding between input and data | | 2. v-for | B. Conditionally renders elements in the DOM | | 3. v-bind | C. Binds HTML attributes dynamically | | 4. v-model | D. Renders a list of items |
Suppose the application is running on http://127.0.0.1:8080. What will be rendered by the browser?File: index.html
```html
<div id="app"></div>
<script src="script.js"></script>
```
File: script.js
```javascript
new Vue({
el: '#app',
template: `<div>
Status: {{status}}<br>
Value: {{value}}
</div>`,
data: {
status: "Initial",
value: 10,
},
beforeCreate() {
this.status = this.status + " -> Created"
this.value = this.value + 5
},
beforeMount() {
this.status = this.status + " -> Ready"
this.value = this.value - 2
},
created() {
this.status = this.status + " -> Mounted"
this.value = this.value * 2
},
mounted() {
this.status = this.status + " -> Done"
this.value = this.value / 2
},
})
```
Three requests are made to this application: GET /api/open (no authentication headers)1. GET /api/secure (no authentication headers)2. GET /api/superuser with valid authentication token but user has role 'basic' (not 'superuser')3. What will be the response status codes for these requests, respectively?```python
@app.route('/api/open')
def open_endpoint():
return jsonify({'message': 'Open access', 'status': 'success'})
@app.route('/api/secure')
@auth_required('token')
def secure_endpoint():
return jsonify({'message': 'Secure access', 'status': 'authenticated'})
@app.route('/api/superuser')
@auth_required('token')
@roles_required('superuser')
def superuser_endpoint():
return jsonify({'message': 'Superuser access', 'status': 'authorized'})
```
Which of the following options correctly fills Line X and Line Y so that the application works as expected?```html
<div id="app">
<h3>Trip Essentials</h3>
<ul>
<li v-for="item in packedItems" :key="item">
{{ item }}
</li>
</ul>
<button @click="packItem('Passport')">Pack Passport</button>
</div>
<script>
const store = new Vuex.Store({
state: {
packed: []
},
mutations: {
ADD_ITEM(state, item) {
state.packed.push(item);
}
}
});
new Vue({
el: "#app",
store,
computed: {
/* Line X */
},
methods: {
packItem(item) {
/* Line Y */
}
}
});
</script>
```
```javascript
// Line X
packedItems() {
return this.store.state.packed;
}
// Line Y
this.store.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems() {
return this.$store.state.packed;
}
// Line Y
this.$store.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems() {
return this.$store.packed;
}
// Line Y
this.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems: this.$store.state.packed
// Line Y
this.$store.dispatch("ADD_ITEM", item);
```
Which of the following statements correctly explain why the Assignments page takes time to load?```javascript
export default {
data() {
return {
assignments: []
}
},
created() {
fetch("/api/assignments")
.then(res => res.json())
.then(data => {
this.assignments = data;
});
}
}
```
Based on the above data, answer the given subquestions.
Based on the above data, answer the given subquestions.
method is modified as follows:
What will happen when the button is clicked?```
calculate()
```
```
calculate() {
this.a = this.a + 1;
}
```
will not run again``` bigNumber() ```
will run again because a dependency changed``` bigNumber() ```
Based on the above data, answer the given subquestions.
defined as a computed property instead of a method?``` bigNumber() ```
Assume the Vue application is loaded at the url
. The user then clicks on the Item 2 router link. Based on the above data, answer the given subquestions.
is never called``` updated() ```
is called``` updated() ```
Assume the Vue application is loaded at the url
. The user then clicks on the Item 2 router link. Based on the above data, answer the given subquestions.
lifecycle hook triggered in this scenario?``` updated() ```
What will be printed on the console first?```javascript
const store = new Vuex.Store({
state: { todos: [] },
mutations: {
addTodo(state, todo) { state.todos.push(todo) }
},
actions: {
async addTodoAsync({ commit }, todo) {
commit('addTodo', { text: todo, done: false });
return 'done';
}
}
});
store.dispatch('addTodoAsync', 'Learn Vuex')
.then(msg => console.log(msg));
console.log(store.state.todos.length);
```
If the developer changed the template to use displayedProducts instead of filteredProducts, What would be the most likely issue?```javascript
const ProductList = {
template: `<div>{{ filteredProducts }}</div>`,
data() {
return {
allProducts: [
{ id: 1, name: 'Laptop', category: 'electronics' },
{ id: 2, name: 'Novel', category: 'books' },
{ id: 3, name: 'Phone', category: 'electronics' }
],
displayedProducts: null
}
},
computed: {
filteredProducts() {
return this.allProducts.filter(p => p.category ===
this.$route.params.category);
}
},
watch: {
'$route.params.category': function(newCategory) {
this.displayedProducts = this.filteredProducts;
}
}
}
```
Suppose the following mutation is committed:store.commit("updateUserStatus", { userId: 2, status: "active" });. Which of the following statements is TRUE after this mutation is executed?```javascript
const store = new Vuex.Store({
state: {
users: [
{ id: 1, name: 'Alice', status: 'active', role: 'admin' },
{ id: 2, name: 'Bob', status: 'inactive', role: 'user' },
{ id: 3, name: 'Charlie', status: 'active', role: 'user' }
]
},
getters: {
activeUsers(state) {
return state.users.filter(user => user.status === 'active');
},
activeUserCount(state, getters) {
return getters.activeUsers.length;
},
adminUsers(state) {
return state.users.filter(user => user.role === 'admin');
}
},
mutations: {
updateUserStatus(state, { userId, status }) {
const user = state.users.find(u => u.id === userId);
if (user) {
user.status = status;
}
}
}
});
```
will return 3``` activeUserCount ```
will return two usersadminUsers
will include only Alice and CharlieactiveUsers
index.html:
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?```javascript
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: '/',
})
const app = new Vue({
el: '#app',
router
})
```
```html
<div id="app">
<router-view></router-view>
</div>
<script src="app.js"></script>
```
File : app.js
Suppose the application is running on http://localhost:8080, and the user visits the URL http://localhost:8080/#/b. What will be rendered by the browser?```html
<div id="app">
<router-view></router-view>
</div>
```
```javascript
const Waterfall = {
template: `<p>{{ result }}</p>`,
data() {
return {
districts: [
{ district: "Satara", waterfall: "Vajrai Waterfall" },
{ district: "Shivamogga", waterfall: "Kunchikal Waterfalls" },
{ district: "South Goa", waterfall: "Dudhsagar Falls" },
{ district: "Rewa", waterfall: "Bahuti Falls" }
],
result: ""
};
},
created() {
const letter = this.$route.params.alpha.toLowerCase();
for (let i = 0; i < this.districts.length; i++) {
if (this.districts[i].waterfall[0].toLowerCase() === letter) {
this.result = this.districts[i].district;
break;
}
}
}
};
const router = new VueRouter({
routes: [
{
path: "/:alpha",
component: Waterfall
}
]
});
new Vue({
el: "#app",
router
});
```
Which of the following statements is/are CORRECT about this implementation?```javascript
mounted() {
const storedToken = localStorage.getItem('userToken');
if (storedToken) {
this.validateToken(storedToken)
.then(user => {
this.user = user;
this.isAuthenticated = true;
})
.catch(err => {
localStorage.removeItem('userToken');
this.isAuthenticated = false;
});
}
}
```
File: app.js
The application consists of a parent component and a child component. When the button inside the child component is clicked, the parent’s message should update and display "Hello" in the browser. Two important lines are missing and marked as (Code1) and (Code2). Which of the following options correctly completes the code?```html
<div id="app">
<child-comp (Code1)></child-comp>
<p>{{ message }}</p>
</div>
```
```javascript
Vue.component("child-comp", {
template: `<button @click="send">Click</button>`,
methods: {
send() {
(Code2)
}
}
});
new Vue({
el: "#app",
data: {
message: "Waiting..."
},
methods: {
updateMessage(msg) {
this.message = msg;
}
}
});
```
```
(Code1) @message="updateMessage('Hello')"
(Code2) this.$emit("message")
```
```
(Code1) @message="updateMessage"
(Code2) this.$emit("message", "Hello")
```
```
(Code1) :message="updateMessage"
(Code2) this.emit("message", "Hello")
```
```
(Code1) @updateMessage="message"
(Code2) this.$emit("updateMessage")
```
File: app.js
Which of the following statements is/are TRUE?```html
<div id="app">
<p v-if="isVisible">Hello</p>
<p v-show="isVisible">World</p>
<button @click="toggle">Toggle</button>
</div>
```
```javascript
new Vue({
el: "#app",
data: {
isVisible: false
},
methods: {
toggle() {
this.isVisible = !this.isVisible;
}
}
});
```
app.js:
What will be rendered by the browser after 4 seconds?```html
<div id="app">
<h4>total payable amount is {{totalPayableAmount}}</h4>
</div>
<script src = "app.js"></script>
```
```javascript
const app = new Vue({
el: '#app',
data: {
principal: 0,
annualInterestRate: 0,
duration: 0,
totalPayableAmount: 0,
},
computed: {
simpleInterest() {
return (this.principal * this.annualInterestRate * this.duration) /
100
},
},
})
let appData = [
[2000, 10, 2],
[3000, 20, 3],
[5000, 30, 4],
]
let handler = setInterval(() => {
data = appData.pop()
app.principal = data[0]
app.annualInterestRate = data[1]
app.duration = data[2]
app.totalPayableAmount += app.simpleInterest
}, 1000)
```
File: script.js
What will be rendered on the browser for the code setup given above ?```html
<div id="app">
<my-comp>
<h3>Exploring Vue Js</h3>
<slot v-slot:last>
<h3>Learning App Dev 2</h3>
</slot>
</my-comp>
</div>
```
```javascript
const MyComp = {
name: 'my-comp',
props: ['tech'],
template: `
<div class="container">
<slot name="complete">
<h3>Learned DBMS</h3>
</slot>
<slot>
Exploring Frontend
</slot>
<slot name="last"></slot>
</div>
`
};
const app = new Vue({
el: '#app',
components: {
MyComp
}
});
```
Learned DBMS Exploring Backend

Learned DBMS Exploring Vue Js This is Last Course

Learned DBMS Exploring Vue Js
File: script.js

lifecycle hook is invoked, which of the following statements becomes TRUE?``` beforeMount() ```
element exists in the DOM but still contains {{ message }}```html <p id="text"> ```
hook has already executed``` mounted() ```
File: script.js

element after the component is fully mounted and all statements in the
hook have executed?`<p>` ``` mounted() ```

Start A

Start A B

Start A B DOM

Start A DOM

```
childComponent.$emit('update', 5)
```
Suppose the webpage is served at http://127.0.0.1:5000. A user visits the URL http://127.0.0.1:5000/#/user/10/orders. What will be rendered on the browser?```javascript
const User = {
template: `
<div>
<h2>User {{ $route.params.id }}</h2>
<router-view></router-view>
</div>
`
};
const Overview = {
template: `<p>User Overview</p>`
};
const Orders = {
template: `<p>User Orders</p>`
};
const routes = [
{
path: "/user/:id",
component: User,
children: [
{ path: "", component: Overview },
{ path: "orders", component: Orders }
]
}
];
const router = new VueRouter({ routes });
```
```html
<!-- html -->
<div id="app">
<router-view></router-view>
</div>
```
```javascript
const processString = (str) => {
return new Promise((resolve) => {
setTimeout(() => resolve(str.toUpperCase()), 100);
});
};
Promise.resolve('hello')
.then(processString)
.then(result => result + ' WORLD')
.then(console.log)
.catch(err => console.log('Error:', err));
```
Code:
```javascript
let originalConfig = { apiUrl: 'https://api.example.com', timeout: 5000 };
let configCopy = originalConfig;
configCopy.timeout = 10000;
configCopy = { apiUrl: 'https://api2.example.com', timeout: 3000 };
console.log(originalConfig.timeout);
```
What will be the output on the browser's console?```javascript
class BaseComponent {
constructor(name) {
this.name = name;
}
}
class AdvancedComponent extends BaseComponent {
constructor(name, role) {
super(name);
this.role = role;
}
}
const comp = new AdvancedComponent('Alice', 'admin');
console.log(comp.__proto__ === AdvancedComponent.prototype);
console.log(comp.__proto__.__proto__ === BaseComponent.prototype);
console.log(comp instanceof BaseComponent);
console.log(comp instanceof AdvancedComponent);
```
Based on the above data, answer the given subquestions.
Based on the above data, answer the given subquestions.
Based on the above data, answer the given subquestions.
script:
Based on the above data, answer the given subquestions.
The route changes to /user/2 but the userId in data does not update.

The watcher updates `userId` to "2", and the `<p>` displays it instantly.

The `router-view` still shows User 1 because watchers don't re-render components.

An error occurs because `$route.params.id` cannot be watched.