MAD Study Hub

Home / Past papers / MAD2 Quiz 2 / this paper

IIT M IMPROVEMENT AN EXAM QIV3 03 Aug - 03 Aug 2025

MAD2 Quiz 216 questions50 marks11 MCQ · 5 MSQImprovement / afternoon / QIV3
Elapsed 00:00
Q1MCQ2 marks
question figure
Text of the picture (copyable)
Suppose a client wants to make a **POST** request using the Fetch API to a public endpoint at **/api/submit**, which includes sending a **data** object as JSON in the request body.

```javascript
const data = {
  name: "Aditya",
  score: 95,
};

fetch("/api/submit", {
  method: "POST",
  headers: {
    // CODE
  },
  body: JSON.stringify(data),
});
```

Which headers are necessary for this request to succeed, (inside CODE)?
  1. question figure
    text
    ```
    'Content-Type': 'application/json'
    ```
  2. question figure
    text
    ```
    'Content-Type': 'multipart/form-data'
    ```
  3. question figure
    text
    ```
    'Content-Type': 'application/text'
    ```
  4. question figure
    text
    ```
    'Accept': '*/*'
    ```
Q2MSQ2 marksselect all that apply
Which of the following statements are true?
  1. question figure
    text
    JavaScript can directly import and execute .vue files without any preprocessing
  2. question figure
    text
    .vue files typically contain template, script, and style sections
  3. question figure
    text
    .vue files must be compiled (e.g., via Vue CLI or Vite) before they can run in the browser
  4. question figure
    text
    You can load a .vue file directly in a `<script>` tag in plain HTML
Q3MSQ2 marksselect all that apply
Which of the following statement(s) about Web Storage APIs is/are correct?
  1. question figure
    text
    The `localStorage` object stores data with no expiration date, even after the browser is closed.
  2. question figure
    text
    The `sessionStorage` object keeps data only for the duration of the page session.
  3. question figure
    text
    Both `localStorage` and `sessionStorage` can store data in key-value pair format.
  4. question figure
    text
    Data stored in `sessionStorage` is available across different browser tabs.
Q4MSQ2 marksselect all that apply
Which of the following statement(s) is/are true regarding Single Page Applications (SPA) and Progressive Web Apps (PWA)?
  1. SPAs use client-side routing to dynamically update content without full pagereloads.
  2. PWAs can work offline using service workers.
  3. SPAs always require a server-side language to handle routing.
  4. PWAs can be added to a device’s home screen like native apps.
Q5MCQ3 marks
question figure
Text of the picture (copyable)
Consider the following code snippet.

```javascript
const response = {
  meta: () =>
    Promise.resolve([
      { id: 1, score: 20 },
      { id: 2, score: 40 },
    ]),
  json: () =>
    Promise.resolve([
      { name: "Alpha", score: 40 },
      { name: "Beta", score: 30 },
      { name: "Charlie", score: 50 },
      { name: "Delta" }, // no score
    ]),
};

fetchData();

function fetchData() {
  Promise.resolve(response)
    .then((res) => res.json())
    .then((data) => {
      const total = data
        .map((p) => parseInt(p.score) || 0)
        .filter((score) => score >= 40)
        .reduce((acc, score) => acc + score, 0);
      console.log("Total Score:", total);
    });
}
```

What will be logged to the console?
  1. Total Score: 80
  2. Total Score: 90
  3. Total Score: 120
  4. Total Score: NaN
Q6MCQ3 marks
question figure question figure
Text of the picture (copyable)
The following code is using Vue 2 and Vue router 3 running on
http://127.0.0.1:5500.

Filename: index.html
```html
<body>
    <div id="app"></div>
    <script src="app.js" type="module"></script>
</body>
```

Filename: router.js
```javascript
const Home = { template: "<div>Home Page</div>" };
const Dashboard = {
    template: "<div>Dashboard <router-view></router-view></div>",
};
const Stats = { template: "<p>Stats Component</p>" };
const Settings = { template: "<p>Settings Component</p>" };
const NotFound = { template: "<div>404 Not Found</div>" };

const router = new VueRouter({
    routes: [
        { path: "/", component: Home },
        {
            path: "/dashboard",
            component: Dashboard,
            children: [
                { path: "stats", component: Stats },
                { path: "settings", component: Settings },
            ],
        },
        { path: "**", component: NotFound },
    ],
});

export default router;
```
Filename: app.js

```javascript
import router from "./router.js";

new Vue({
  el: "#app",
  router,
  template: `<div><router-view></router-view></div>`,
});
```

What will be displayed when the user visits
http://127.0.0.1:5500/#/dashboard/stats?
  1. Dashboard only
  2. Stats Component only
  3. DashboardStats Component
  4. 404 Not Found
Q7MCQ3 marks
question figure
Text of the picture (copyable)
Consider the following Vue 2 component defined using the CDN version:
Filename: index.html

```html
<div id="app">
  <p>{{ message }}</p>
</div>
```

Filename: app.js

```javascript
new Vue({
  el: '#app',
  data() {
    return {
      message: 'Initial'
    };
  },
  created() {
    console.log('Created Hook');
    this.message = 'Created Hook Called';
    this.fetchData();
  },
  mounted() {
    console.log('Mounted Hook');
  },
  methods: {
    async fetchData() {
      const res = await new Promise(resolve => {
        setTimeout(() => resolve('Data Loaded'), 1000);
      });
      this.message = res;
      console.log('Data updated after fetch');
    }
  }
});
```

What will be the sequence of console logs and final content shown on the web page after 1 second?
  1. question figure
    text
    Console:
    Mounted Hook
    Created Hook
    Data updated after fetch
    
    Page: Initial
  2. question figure
    text
    Console:
    ```
    Created Hook
    Mounted Hook
    Data updated after fetch
    ```
    Page: Data Loaded
  3. question figure
    text
    Console:
    ```
    Created Hook
    Data updated after fetch
    Mounted Hook
    ```
    Page: Data Loaded
  4. question figure
    text
    Console:
    Mounted Hook
    Data updated after fetch
    Created Hook
    
    Page: Created Hook Called
Q8MCQ3 marks
question figure
Text of the picture (copyable)
Consider the following JavaScript program:

```javascript
const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('The cat sleeps');
  }, 2000);
});

promise1
  .then((result) => {
    console.log(result);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('Rain falls gently');
      }, 1000);
    });
  })
  .then((result) => {
    console.log(result);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('Books gather dust');
      }, 1500);
    });
  })
  .then((result) => {
    console.log(result);
    throw new Error('Coffee grows cold');
  })
  .then((result) => {
    console.log('Stars shine bright');
  })
  .catch((error) => {
    console.log("Caught:", error.message);
  });
```

What will be the output of the above program when executed?
  1. question figure
    text
    The cat sleeps
    Rain falls gently
    Books gather dust
    Stars shine bright
  2. question figure
    text
    The cat sleeps
    Rain falls gently
    Books gather dust
    Caught: Coffee grows cold
  3. question figure
    text
    The cat sleeps
    Rain falls gently
    Caught: Coffee grows cold
  4. question figure
    text
    The program will crash without showing any output
  5. question figure
    text
    The cat sleeps
    Rain falls gently
    Books gather dust
    Caught: Coffee grows cold
    Stars shine bright
Q9MCQ3 marks
question figure
Text of the picture (copyable)
Consider the following Vue application with markup "index.html" and JavaScript file "app.js".
Filename: index.html
```html
<div id="app"></div>
<script src="app.js"></script>
```
Filename: app.js
```javascript
new Vue({
  el: '#app',
  template: `<div>
    Phase: {{phase}}<br>
    Counter: {{counter}}<br>
    Items: {{items.length}}
  </div>`,

  data: {
    phase: "",
    counter: 0,
    items: []
  },

  beforeCreate() {
    this.phase += "Init-"
    this.counter += 5
    this.items.push("A")
  },

  created() {
    this.phase += "Ready-"
    this.counter += 3
    this.items.push("B")
  },

  beforeMount() {
    this.phase += "Prep-"
    this.counter -= 2
    this.items.push("C")
  },

  mounted() {
    this.phase += "Live"
    this.counter *= 2
    this.items.push("D")
  }
})
```
What will be displayed in the browser when the application loads?
  1. question figure
    text
    Phase: Init-Ready-Prep-Live
    Counter: 12
    Items: 4
  2. question figure
    text
    Phase: Ready-Prep-Live
    Counter: 2
    Items: 3
  3. question figure
    text
    Phase: Prep-Live
    Counter: -4
    Items: 2
  4. question figure
    text
    Phase: Live
    Counter: 0
    Items: 1
  5. question figure
    text
    Phase: Ready-Prep-Live
    Counter: 12
    Items: 3
Q10MSQ3 marksselect all that apply
question figure
Text of the picture (copyable)
Consider the following Vue 2 code with Vuex 3 used via CDN, assume the Vuex
store is correctly injected into the Vue instance.
Filename: store.js
```javascript
export default store = new Vuex.Store({
  state: {
    score: 10,
  },
  mutations: {
    increaseScore(state) {
      state.score += 5;
    },
  },
  actions: {
    increaseScoreAsync({ commit }) {
      setTimeout(() => {
        commit("increaseScore");
      }, 1000);
    },
  },
});
```
Filename: score-display.js
```javascript
export default Vue.component('score-display', {
  template: `
    <div>
      <p>Current Score: {{ score }}</p>
      <button @click="boostNow">Boost Now</button>
      <button @click="boostLater">Boost After 1s</button>
    </div>
  `,
  computed: {
    score() {
      // CODE 1
    }
  },
  methods: {
    boostNow() {
      // CODE 2
    },
    boostLater() {
      // CODE 3
    }
  }
});
```
Which of the following correctly fills in CODE 1, CODE 2, and CODE 3 for the score to be
displayed and for the **boostNow()** and **boostLater()** methods to work correctly?
  1. question figure
    text
    CODE 1:
    ```
    return this.$store.state.score;
    ```
  2. question figure
    text
    CODE 2:
    ```
    this.$store.commit('increaseScore');
    ```
  3. question figure
    text
    ```
    CODE 2: this.increaseScore() ;
    ```
  4. question figure
    text
    CODE 3:
    ```
    this.$store.dispatch('increaseScoreAsync');
    ```
  5. question figure
    text
    CODE 3:
    ```
    this.$store.increaseScoreAsync();
    ```
Q11MSQ3 marksselect all that apply
question figure question figure
Text of the picture (copyable)
Consider the below application with markup "index.html" and JavaScript file
"app.js".
Filename: index.html

```html
<div id="app"></div>
<script src="app.js"></script>
```
Filename: app.js

```javascript
const inventory = {
  101: {product: "Canvas", quantity: 15, warehouse: 3},
  102: {product: "Brushes", quantity: 8, warehouse: 2}
}

const errorPage = {
  template: `<h1>Item not found in inventory!</h1>`
}

const productDetails = {
  template: `<h1>{{item.product}} - {{item.quantity}} units stored
  in
  {{item.warehouse}} locations.</h1>`,

  data() {
    return {item: inventory[this.$route.params.productId]}
  },
  watch: {
    '$route'(to, from) {
      this.item = inventory[to.params.productId]
    }
  }
}

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/inventory/:productId', component: productDetails },
    { path: '*', component: errorPage },
  ],
})

new Vue({
  el: '#app',

  template: '<div><router-view /></router-view></div>',
  router,
})
```

Suppose the application is running on "http://localhost:3000", select the correct option(s)?
  1. question figure
    text
    For the endpoint, http://localhost:3000/inventory/101, The browser will render:
    Canvas - 15 units stored in 3 locations.
  2. question figure
    text
    For the endpoint, http://localhost:3000/#/inventory/102, The browser will render:
    Brushes - 8 units stored in 2 locations.
  3. question figure
    text
    For the endpoint, http://localhost:3000/inventory. The browser will render:
    item not found in inventory!
  4. question figure
    text
    For the endpoint, http://localhost:3000/inventory/103, The browser will render:
    Item not found in inventory!
  5. question figure
    text
    For the endpoint, http://localhost:3000/products/101, The browser will render:
    Item not found in inventory!
Q12MCQ4.5 marks
question figure
Text of the picture (copyable)
The following code is using Vue 2 and Vue router 3 running on
http://127.0.0.1:5500.

Filename: index.html
```html
<body>
    <div id="app"></div>
    <script src="app.js" type="module"></script>
</body>
```

Filename: router.js
```javascript
const Home = { template: "<div>Home Page</div>" };
const Dashboard = {
    template: "<div>Dashboard <router-view></router-view></div>",
};
const Stats = { template: "<p>Stats Component</p>" };
const Settings = { template: "<p>Settings Component</p>" };
const NotFound = { template: "<div>404 Not Found</div>" };

const router = new VueRouter({
    routes: [
        { path: "/", component: Home },
        {
            path: "/dashboard",
            component: Dashboard,
            children: [
                { path: "stats", component: Stats },
                { path: "settings", component: Settings },
            ],
        },
        { path: "*", component: NotFound },
    ],
});
export default router;
```

Filename: app.js
```javascript
import router from "./router.js";

new Vue({
    el: "#app",
    router,
    template: `<div><router-view></router-view></div>`,
});
```

What will be displayed when the user visits the following URLs?

1. http://127.0.0.1:5500/#/dashboard/unknown
2. http://127.0.0.1:5500/#/dashboards/stats
  1. Both will show Dashboard
  2. 1: Dashboard, 2: 404 Not Found
  3. 1: Dashboard, 2: Stats Component
  4. Both will show 404 Not Found
Q13MCQ4.5 marks
question figure
Text of the picture (copyable)
Consider the following Vue application with markup "index.html" and JavaScript file "app.js".

Filename: index.html

```html
<div id="app">
  <data-panel>
    <template #sidebar>
      <span>Navigation Menu</span>
    </template>
    <template #actions>
      <button>Save Changes</button>
      <button>Cancel</button>
    </template>
    <template #default>
      <h3>Main Dashboard</h3>
      <p>Welcome to the control panel</p>
    </template>
    <template #footer>
      <small>Last updated: Today</small>
    </template>
    <div>Extra content outside templates</div>
  </data-panel>
</div>
```

Filename: app.js

```javascript
Vue.component("data-panel", {
  template: `<div class="panel">
    <header>
      <slot name="sidebar"></slot>
    </header>
    <main>
      <slot></slot>
    </main>
    <section>
      <slot name="actions"></slot>
    </section>
    <footer>
      <slot name="summary"></slot>
    </footer>
  </div>`,
});
const app = new Vue({
  el: "#app",
});
```

What will be the visual output displayed in the browser?
  1. question figure
    text
    Navigation Menu
    
    Main Dashboard
    Welcome to the control panel
    Extra content outside templates
    
    Save Changes Cancel
    
    Last updated: Today
  2. question figure
    text
    Navigation Menu
    
    Main Dashboard
    Welcome to the control panel
    Extra content outside templates
    
    Save Changes Cancel
  3. question figure
    text
    Navigation Menu
    Extra content outside templates
    Save Changes Cancel
  4. question figure
    text
    Navigation Menu
    
    Main Dashboard
    Welcome to the control panel
    
    Save Changes Cancel
    Last updated: Today
Q14MCQ4.5 marks
question figure question figure
Text of the picture (copyable)
Consider the following Vuex store setup for a user management system:

```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;
      }
    }
  }
});
```
```javascript
addUser(state, user) {
  state.users.push({ ...user, id: Date.now() });
},
actions: {
  toggleUserStatus({ commit, state }, userId) {
    const user = state.users.find(u => u.id === userId);
    if (user) {
      const newStatus = user.status === 'active' ? 'inactive' : 'active';
      commit('updateUserStatus', { userId, status: newStatus });
    }
  },
  async createUser({ commit }, userData) {
    await new Promise(resolve => setTimeout(resolve, 100));
    commit('addUser', userData);
  }
}
```

What will happen when the following sequence of operations is executed?

```javascript
store.dispatch('toggleUserStatus', 1); // Toggle Alice's status
store.dispatch('createUser', { name: 'David', status: 'active', role: 'user' });
```
  1. question figure
    text
    The activeUserCount will become 1 immediately after the first dispatch, and remain 1 after the second dispatch completes.
  2. question figure
    text
    The activeUserCount will become 1 after the first dispatch, and become 2 after the second dispatch completes.
  3. question figure
    text
    The activeUserCount will remain 2 after the first dispatch, and become 3 after the second dispatch completes.
  4. question figure
    text
    The activeUserCount will become 3 immediately after both dispatches, since both operations run synchronously.
Comprehension passage - the questions below it refer to this
You are given the following HTML and JavaScript code that uses Vue 2 via CDN along with Vue Router. Read the code carefully and answer the given subquestions. question figure You are given the following HTML and JavaScript code that uses Vue 2 via CDN along with Vue Router. Read the code carefully and answer the given subquestions. question figure You are given the following HTML and JavaScript code that uses Vue 2 via CDN along with Vue Router. Read the code carefully and answer the given subquestions.
Q15MCQ4.5 marks
question figure
Text of the picture (copyable)
What will be the output when the
"Fetch" button is clicked on the
/home route?
  1. question figure
    text
    The page immediately shows "Fetched Data from API!" with no delay.
  2. question figure
    text
    The message "**Loading data...**" is
    shown for ~1 second, then replaced
    with "**Fetched Data from API!!**".
  3. question figure
    text
    Both "Loading data..." and "Fetched
    Data from API!" appear together.
  4. question figure
    text
    Nothing happens because v-show and
    v-if cannot work together.
Q16MCQ3 marks
Suppose the button is clicked multiple times quickly, the message area flickers unexpectedly. How can you improve the code to ensure proper async behavior and prevent overlapping fetches?
  1. question figure
    text
    Add v-else after v-if instead of v-show.
  2. question figure
    text
    Replace
    ```javascript
    await this.simulateApiCall().then(...);
    ```
    with
    ```javascript
    const res = await this.simulateApiCall(); this.message = res;
    ```
  3. question figure
    text
    Add a check to disable the button while loading;
    ```html
    <button @click="fetchData" :disabled="loading">Fetch</button>
    ```
  4. question figure
    text
    Use v-html instead of v-show for message rendering.

Answer key

  1. Q1 (MCQ, 2 marks): A
  2. Q2 (MSQ, 2 marks): B, C
  3. Q3 (MSQ, 2 marks): A, B, C
  4. Q4 (MSQ, 2 marks): A, B, D
  5. Q5 (MCQ, 3 marks): B
  6. Q6 (MCQ, 3 marks): C
  7. Q7 (MCQ, 3 marks): B
  8. Q8 (MCQ, 3 marks): B
  9. Q9 (MCQ, 3 marks): B
  10. Q10 (MSQ, 3 marks): A, C, D
  11. Q11 (MSQ, 3 marks): A, C, E
  12. Q12 (MCQ, 4.5 marks): D
  13. Q13 (MCQ, 4.5 marks): B
  14. Q14 (MCQ, 4.5 marks): B
  15. Q15 (MCQ, 4.5 marks): B
  16. Q16 (MCQ, 3 marks): C

Concepts this paper tests

Auto-generated summary from the source site. Handy as a checklist; the lessons above explain each idea from scratch.

Summary of Core Topics, Concepts, Principles, and Equations

Core Topics and Concepts

  1. Fetch API and HTTP Requests

    • POST Requests: Sending data to a server using the Fetch API.
    • Headers: Setting appropriate headers for JSON data.
    • Content-Type: application/json for JSON data.
  1. Vue.js and Single File Components

    • .vue Files: Structure and compilation of Vue single-file components.
    • Template, Script, and Style Sections: Components of a .vue file.
    • Compilation: Need for compiling .vue files before browser execution.
  1. Web Storage APIs

    • localStorage: Persistent storage with no expiration.
    • sessionStorage: Storage limited to the duration of the page session.
    • Key-Value Pairs: Storage format for both localStorage and sessionStorage.
  1. Single Page Applications (SPA) and Progressive Web Apps (PWA)

    • Client-Side Routing: Dynamic content updates without full page reloads.
    • Service Workers: Enabling offline functionality in PWAs.
    • Home Screen Installation: Adding PWAs to a device's home screen.
  1. Data Processing and Asynchronous Operations

    • Fetching and Processing Data: Handling JSON data and metadata.
    • Filtering and Reducing Data: Processing data arrays.
    • Asynchronous Operations: Using async/await and Promises.
  1. Vue Router and Dynamic Components

    • Routing Configuration: Setting up routes and nested routes.
    • Dynamic Components: Rendering components based on routes.
    • Lifecycle Hooks: created, mounted, and other lifecycle hooks in Vue.
  1. Error Handling and Debugging

    • Error Handling in Promises: Using .catch() for error handling.
    • Debugging Asynchronous Code: Understanding the sequence of asynchronous operations.
  1. Vuex for State Management

    • State, Getters, Mutations, and Actions: Managing state in Vue applications.
    • Asynchronous State Updates: Handling async operations in Vuex.
  1. Slots and Component Composition

    • Named Slots: Using slots for component composition.
    • Scoped Slots: Advanced usage of slots for dynamic content.
  1. Vue Lifecycle Hooks

    • beforeCreate, created, beforeMount, mounted: Understanding the lifecycle of Vue components.
    • Data Initialization and DOM Manipulation: Using lifecycle hooks for initialization and DOM updates.

Important Equations and Code Snippets

  1. Fetch API POST Request ``javascript fetch("/api/submit", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }); ``
  1. Vue Component Lifecycle Hooks ``javascript new Vue({ el: '#app', data() { return { message: 'Initial' }; }, created() { console.log('Created Hook'); this.message = 'Created Hook Called'; }, mounted() { console.log('Mounted Hook'); } }); ``
  1. Vuex Store Configuration ``javascript const store = new Vuex.Store({ state: { users: [ { id: 1, name: 'Alice', status: 'active', role: 'admin' }, { id: 2, name: 'Bob', status: 'inactive', role: 'user' } ] }, getters: { activeUsers(state) { return state.users.filter(user => user.status === 'active'); } }, mutations: { updateUserStatus(state, { userId, status }) { const user = state.users.find(u => u.id === userId); if (user) { user.status = status; } } }, actions: { toggleUserStatus({ commit, state }, userId) { const user = state.users.find(u => u.id === userId); if (user) { const newStatus = user.status === 'active' ? 'inactive' : 'active'; commit('updateUserStatus', { userId, status: newStatus }); } } } }); ``
  1. Vue Router Configuration ``javascript const router = new VueRouter({ routes: [ { path: '/', component: Home }, { path: '/dashboard', component: Dashboard, children: [ { path: 'stats', component: Stats }, { path: 'settings', component: Settings } ] }, { path: '*', component: NotFound } ] }); ``
  1. Asynchronous Data Fetching ``javascript async fetchData() { this.loading = true; const res = await this.simulateApiCall(); this.message = res; this.loading = false; }, simulateApiCall() { return new Promise((resolve) => { setTimeout(() => resolve("Fetched Data from API!"), 1000); }); } ``