MAD Study Hub

Home / Past papers / MAD2 End Term / this paper

IIT M DIPLOMA FN EXAM QDD2 13 Apr 2025 - 13 Apr 2025

MAD2 End Term32 questions100 marks28 MCQ · 3 MSQ · 1 SADiploma / forenoon / QDD2
Elapsed 00:00
Q1MCQ2 marks
Which of the following statements is true regarding the "this" keyword in JavaScript?
  1. It always refers to the global object.
  2. Arrow functions have their own "this" context.
  3. "this" in an event listener always refers to the window object.
  4. None of these
Q2MCQ2 marks
Which of the following correctly describes the lifecycle of a Vue.js component?
  1. beforeCreate -> created -> beforeMount -> mounted -> beforeUpdate ->updated -> beforeUnmount -> unmounted
  2. beforeCreate -> created -> beforeMount -> beforeUpdate -> mounted ->updated -> beforeUnmount -> unmounted
  3. created -> beforeCreate -> beforeMount -> mounted -> updated ->beforeUnmount -> unmounted
  4. created -> beforeCreate -> beforeMount -> mounted -> beforeUnmount ->updated -> unmounted
Q3MCQ2 marks
question figure
Text of the picture (copyable)
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?
  1. SuccessFailed
  2. Success
  3. Failed
  4. Error
Q4MCQ2 marks
Which of the following is NOT a common performance metric measured by Google Lighthouse?
  1. First Contentful Paint (FCP)
  2. Time to Interactive (TTI)
  3. Total Blocking Time (TBT)
  4. Database Query Time (DQT)
Q5MCQ2 marks
Which of the following is a key difference between Web Sockets and Server-Sent Events (SSE)?
  1. SSE allows bidirectional communication, while WebSockets only allow server-to-client communication.
  2. WebSockets maintain a persistent connection, while SSE creates a newconnection for each message.
  3. SSE works over HTTP and only supports server-to-client communication,whereas WebSockets provide full-duplex communication.
  4. WebSockets require an HTTP request for every message sent.
Q6MCQ2 marks
Which HTTP method is typically used for sending webhook notifications?
  1. GET
  2. POST
  3. DELETE
  4. PATCH
Q7MCQ3 marks
question figure
Text of the picture (copyable)
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?
  1. 6
  2. NaN
  3. undefined
  4. 0
  5. NULL
Q8MCQ3 marks
question figure
Text of the picture (copyable)
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?
  1. 10
  2. undefined
  3. NaN
  4. NULL
  5. Error
Q9MCQ3 marks
question figure
Text of the picture (copyable)
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?
  1. question figure
    text
    The image shows a single vertical bar character.
  2. question figure
    text
    ```
    ['Vue.js', 'Vue.js']
    ```
  3. question figure
    text
    ```
    ['Vue.js']
    ```
  4. question figure
    text
    [object]
Q10MCQ3 marks
question figure
Text of the picture (copyable)
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"?
  1. Browser navigates to /foo and displays "Foo".
  2. Browser navigates to /foo but displays nothing.
  3. Error: No matching route.
  4. None of these
Q11MCQ3 marks
question figure
Text of the picture (copyable)
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?
  1. question figure
    text
    ```html
    <alert-box title="Custom Title">Custom content</alert-box>
    ```
  2. question figure
    text
    ```html
    <alert-box>
        <slot name="title">Custom Title</slot>Custom content
    </alert-box>
    ```
  3. question figure
    text
    ```html
    <alert-box>
        <template v-slot:title>
            Custom Title
        </template>
        Custom content
    </alert-box>
    ```
  4. question figure
    text
    ```html
    <alert-box>Custom Title - Custom content</alert-box>
    ```
Q12MCQ3 marks
Consider the following Vue component. question figure Consider the following Vue component.
Text of the picture (copyable)
```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?
  1. question figure
    text
    ```html
    <user-list v-slot="{ user }">
      <template>{{ user.name }} ({{ user.role }})</template>
    </user-list>
    ```
  2. question figure
    text
    ```html
    <user-list>
      <template v-slot:default="{ user }">
        {{ user.name }} ({{ user.role }})
      </template>
    </user-list>
    ```
  3. question figure
    text
    ```html
    <user-list>
        <template scope="{ user }">
            {{ user.name }} ({{ user.role }})
        </template>
    </user-list>
    ```
  4. question figure
    text
    ```html
    <user-list>
      <template slot-scope="{ user }">
        {{ user.name }} ({{ user.role }})
      </template>
    </user-list>
    ```
Q13MCQ3 marks
question figure
Text of the picture (copyable)
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);
```
  1. 10 30
  2. 10 undefined
  3. 10 20
  4. The program will raise an error
Q14MCQ3 marks
question figure
Text of the picture (copyable)
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?
  1. 25 seconds
  2. 35 seconds
  3. 0 seconds
  4. 15 seconds
Q15MCQ3 marks
question figure
Text of the picture (copyable)
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?
  1. question figure
    text
    ```
    { status: 'http error' }
    ```
  2. question figure
    text
    ```
    { status: 'network error' }
    ```
  3. question figure
    text
    JSON data
  4. question figure
    text
    The promise will remain pending
Q16MCQ3 marks
question figure
Text of the picture (copyable)
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")
```
  1. question figure
    text
    variable1
    variable2
    variable3
    variable4
  2. question figure
    text
    variable1
    variable4
    variable3
    variable2
  3. question figure
    text
    variable1
    variable4
    variable2
    variable3
  4. question figure
    text
    variable1
    variable3
    variable4
    variable2
Q17MCQ3 marks
Which of the following options is the correct sequence of steps in JWT authentication?
  1. Client sends credentials, server validates and responds with JWT, client storesJWT, client sends JWT with each request.
  2. Client sends credentials, server validates and stores session ID, client sendssession ID with each request.
  3. Client sends JWT, server validates and issues a new JWT for each request.
  4. Client sends JWT, server decrypts JWT and checks credentials again.
Q18MCQ3 marks
question figure
Text of the picture (copyable)
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));
```
  1. The request will be blocked due to CORS policy.
  2. The request will succeed and return { "message": "Hello from Flask" }.
  3. The request will fail because Vue.js does not support CORS.
  4. The server will crash due to incorrect CORS settings.
Q19MCQ4.5 marks
Consider the below Vuex setup. question figure Consider the below Vuex setup. What is logged to the console immediately after dispatching the action?
Text of the picture (copyable)
```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);
```
  1. 0
  2. 42
  3. Undefined behavior
  4. Error: Action did not resolve
Q20MCQ4.5 marks
question figure
Text of the picture (copyable)
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);
```
  1. [27, 125, 343, 729, 1331]
  2. [125, 343, 729]
  3. [27, 125, 343]
  4. None of these
Q21MCQ4.5 marks
question figure
Text of the picture (copyable)
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?
  1. 15 seconds
  2. 25 seconds
  3. 10 seconds
  4. 40 seconds
Q22MCQ4.5 marks
Consider the following Vue apps in script.js and the index.html file. question figure Consider the following Vue apps in script.js and the index.html file. What will be rendered on the browser?
Text of the picture (copyable)
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>
```
  1. Frontend
  2. VueJSFrontend
  3. VueJSJavaScript
  4. FrontendJavaScript
Q23MCQ4.5 marks
Consider the following Vue App and the HTML document given below. question figure Consider the following Vue App and the HTML document given below. What will be the output on the browser?
Text of the picture (copyable)
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')
```
  1. Hello Frontend Hello Frontend
  2. Hello VueJS Hello VueJS
  3. Hello Frontend Hello Vue JS
  4. Hello Frontend Hello Vue JS Hello Frontend Hello Vue JS
Q24MCQ4.5 marks
question figure
Text of the picture (copyable)
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);
```
  1. question figure
    text
    ```json
    { "message": "Hello user!" }
    ```
  2. question figure
    text
    ```json
    { "error": "Token expired" }
    ```
  3. question figure
    text
    ```json
    {
      "error": "Invalid token"
    }
    ```
  4. question figure
    text
    ```json
    {
      "message": "Access granted"
    }
    ```
Q25MSQ2 marksselect all that apply
Which of the following is/are the correct usage of “v-for” directive in VueJS?
  1. item in array
  2. (item, index) of array
  3. (item, index) as array
  4. (item, index) in array
  5. Item of array
Q26MSQ2 marksselect all that apply
Which of the following are advantages of using GraphQL over REST?
  1. It allows clients to fetch only the required fields, reducing over-fetching.
  2. It replaces the need for authentication mechanisms.
  3. It improves database performance automatically.
  4. It enforces a strict API response format.
Q27MSQ3 marksselect all that apply
Which of the following statements are true regarding event loop in JavaScript?
  1. The event loop runs on a separate thread from the main JavaScript execution.
  2. The event loop allows JavaScript to perform non-blocking operations despitebeing single-threaded.
  3. Callbacks from setTimeout are placed in the task queue and executed after thecall stack is empty.
  4. All of these
Q28SA4.5 marks
question figure
Text of the picture (copyable)
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?
Comprehension passage - the questions below it refer to this
Based on the above data, answer the given subquestions. question figure
Q29MCQ3 marks
question figure
Text of the picture (copyable)
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));
```
  1. question figure
    text
    The request will be processed
    successfully, and "Hello,
    student!" will be returned.
  2. question figure
    text
    The request will fail with a
    401 Unauthorized error.
  3. question figure
    text
    The request will return an
    empty response with a 200
    OK status.
  4. question figure
    text
    The request will fail with a
    403 Forbidden error.
Q30MCQ3 marks
question figure
Text of the picture (copyable)
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));
```
  1. question figure
    text
    The request will be processed
    successfully, and "Hello,
    student!" will be returned.
  2. question figure
    text
    The request will fail with a
    401 Unauthorized error.
  3. question figure
    text
    The request will return an
    empty response with a
    200 OK status.
  4. question figure
    text
    The request will fail with a
    403 Forbidden error.
Comprehension passage - the questions below it refer to this
Consider the following Vue app with the Vue Router shown below and answer the given subquestions. question figure Consider the following Vue app with the Vue Router shown below and answer the given subquestions. question figure Consider the following Vue app with the Vue Router shown below and answer the given subquestions.
Q31MCQ4.5 marks
What will be rendered on the browser if the application is loaded on the browser for the first time?
  1. You are not logged in.
  2. Welcome to profile
  3. You are not authorized.
  4. None of these.
Q32MCQ3 marks
What will be rendered on the browser for the given value of localStorage? question figure What will be rendered on the browser for the given value of localStorage?
Text of the picture (copyable)
```
{
  token: 112,
  userRole: "manager"
}
```
  1. You are not logged in.
  2. Welcome to profile
  3. You are not authorized.
  4. None of these.

Answer key

  1. Q1 (MCQ, 2 marks): D
  2. Q2 (MCQ, 2 marks): A
  3. Q3 (MCQ, 2 marks): B
  4. Q4 (MCQ, 2 marks): D
  5. Q5 (MCQ, 2 marks): C
  6. Q6 (MCQ, 2 marks): B
  7. Q7 (MCQ, 3 marks): B
  8. Q8 (MCQ, 3 marks): C
  9. Q9 (MCQ, 3 marks): B
  10. Q10 (MCQ, 3 marks): A
  11. Q11 (MCQ, 3 marks): C
  12. Q12 (MCQ, 3 marks): A
  13. Q13 (MCQ, 3 marks): C
  14. Q14 (MCQ, 3 marks): A
  15. Q15 (MCQ, 3 marks): D
  16. Q16 (MCQ, 3 marks): C
  17. Q17 (MCQ, 3 marks): A
  18. Q18 (MCQ, 3 marks): A
  19. Q19 (MCQ, 4.5 marks): A
  20. Q20 (MCQ, 4.5 marks): B
  21. Q21 (MCQ, 4.5 marks): D
  22. Q22 (MCQ, 4.5 marks): D
  23. Q23 (MCQ, 4.5 marks): D
  24. Q24 (MCQ, 4.5 marks): B
  25. Q25 (MSQ, 2 marks): A, D
  26. Q26 (MSQ, 2 marks): A
  27. Q27 (MSQ, 3 marks): B, C
  28. Q28 (SA, 4.5 marks): 3
  29. Q29 (MCQ, 3 marks): B
  30. Q30 (MCQ, 3 marks): D
  31. Q31 (MCQ, 4.5 marks): C
  32. Q32 (MCQ, 3 marks): B

Concepts this paper tests

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.



1. Core Topics & Concepts

A. JavaScript Fundamentals

Key Concepts:

  1. this Keyword

    • Context depends on how a function is called (global, object method, constructor, arrow function).
    • Arrow functions do not have their own this; they inherit from the surrounding scope.
    • Event listeners: this refers to the element that triggered the event (unless arrow functions are used).
  1. Promises & Async/Await

    • A 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();
      }
  1. Closures & Scope

    • Functions retain access to their lexical scope even after execution.
    • Example:

      function outer() {
        let x = 10;
        return function inner() { console.log(x); };
      }
      const innerFunc = outer();
      innerFunc(); // Output: 10
  1. Event Loop & Asynchronous JavaScript

    • JavaScript is single-threaded but uses an event loop to handle async operations.
    • Task Queue (Macrotasks): setTimeout, setInterval, I/O.
    • Microtask Queue: Promise callbacks, queueMicrotask().
    • Execution Order:

      1. Call stack executes synchronous code.
      2. Microtasks are processed.
      3. Macrotasks (from the task queue) are processed.
  1. Array Methods

    • map, filter, reduce, slice, splice.
    • Example (Reduce):

      [1, 2, 3].reduce((acc, val) => acc + val, 0); // Output: 6

B. Vue.js

Key Concepts:

  1. Component Lifecycle Hooks

    • Order: beforeCreate → created → beforeMount → mounted → beforeUpdate → updated → beforeUnmount → unmounted.
  1. Vuex (State Management)

    • State: Single source of truth.
    • Mutations: Synchronous state changes.
    • Actions: Asynchronous operations (commit mutations).
    • Getters: Computed properties for state.
    • Example:

      const store = new Vuex.Store({
        state: { count: 0 },
        mutations: {
          increment(state) { state.count++; }
        },
        actions: {
          asyncIncrement({ commit }) {
            setTimeout(() => commit('increment'), 1000);
          }
        }
      });
  1. Vue Router

    • Dynamic routing with <router-link> and <router-view>.
    • Example:

      const routes = [
        { path: '/foo', component: Foo },
        { path: '/bar', component: Bar }
      ];
      const router = new VueRouter({ routes });
  1. Slots (Content Distribution)

    • Default Slot: <slot></slot>
    • Named Slots: <slot name="header"></slot>
    • Scoped Slots: Pass data to child components.

      <template v-slot:default="{ user }">
        {{ user.name }}
      </template>
  1. Directives

    • v-for, v-if, v-show, v-bind, v-on, v-model.

C. Web Technologies

Key Concepts:

  1. HTTP Methods

    • GET (retrieve), POST (create), PUT (update), DELETE (remove), PATCH (partial update).
    • Webhooks: Typically use POST to send notifications.
  1. WebSockets vs. Server-Sent Events (SSE) | Feature | WebSockets | SSE | |-----------------------|---------------------|----------------------| | Protocol | ws://, wss:// | HTTP | | Direction | Full-duplex | Server → Client | | Connection | Persistent | Persistent | | Binary Data | Yes | No (text-only) |
  1. CORS (Cross-Origin Resource Sharing)

    • Restricts cross-origin requests for security.
    • Headers:

      • Access-Control-Allow-Origin: Specifies allowed origins.
      • Access-Control-Allow-Methods: Allowed HTTP methods.
  1. JWT (JSON Web Tokens)

    • Structure: Header.Payload.Signature
    • Flow:

      1. Client sends credentials.
      2. Server validates and returns a JWT.
      3. Client stores JWT (e.g., localStorage).
      4. JWT is sent with each request (Authorization: Bearer <token>).
  1. Performance Metrics (Lighthouse)

    • First Contentful Paint (FCP): Time until first content is rendered.
    • Time to Interactive (TTI): Time until page is fully interactive.
    • Total Blocking Time (TBT): Measures main thread blocking.
    • Not a metric: Database Query Time (DQT).

D. Backend (Flask)

Key Concepts:

  1. Flask Basics

    • Microframework for Python.
    • Example:

      from flask import Flask
      app = Flask(__name__)
      @app.route('/')
      def home():
          return "Hello, World!"
  1. Flask-Caching (Redis)

    • Caches responses to improve performance.
    • 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"
  1. Flask-JWT

    • Secures APIs with 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"
  1. Concurrency in Flask

    • threaded=True enables multithreading.
    • Without threading, long-running requests block others.

E. Performance & Optimization

Key Concepts:

  1. Lighthouse Metrics

    • FCP (First Contentful Paint): Time to first render.
    • TTI (Time to Interactive): Time until fully interactive.
    • TBT (Total Blocking Time): Main thread blocking duration.
  1. Caching Strategies

    • Client-side: localStorage, sessionStorage.
    • Server-side: Redis, CDN caching.
  1. Asynchronous Loading

    • Use async/defer for scripts.
    • Code splitting in Vue.js (import()).
  1. Debouncing & Throttling

    • Debounce: Delay execution until after a pause (e.g., search input).
    • Throttle: Limit execution frequency (e.g., scroll events).

2. Key Equations (Mathematics/Algorithms)

(Not directly tested in this exam, but useful for array manipulations.)

  1. Array Reduce ``javascript [a1, a2, ..., an].reduce((acc, val) => acc + val, initialValue); ``

    • Example: [1, 2, 3].reduce((acc, x) => acc + x, 0) = 6
  1. Filtering Arrays ``javascript array.filter(x => condition); ``

    • Example: [1, 2, 3].filter(x => x % 2 === 0) = [2]
  1. Modulo Operations

    • x % n gives the remainder of x / n.
    • Used in questions like Q21 (filtering based on modulo conditions).

3. Common Pitfalls & Exam Tips

  1. this in JavaScript

    • Arrow functions do not bind their own this.
    • Event listeners: this refers to the element (unless arrow functions are used).
  1. Promises

    • Once resolved/rejected, further calls to resolve()/reject() are ignored.
    • Example (Q4):

      const promise = new Promise((resolve, reject) => {
        resolve("Success!");
        reject("Failed!"); // Ignored
      });
  1. Vue.js Reactivity

    • Directly modifying arrays (e.g., array[0] = x) does not trigger reactivity.
    • Use Vue.set or array methods like push, splice.
  1. 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 → B
  1. CORS

    • Always check Access-Control-Allow-Origin in responses.
    • Example (Q19, Q30, Q31): A missing or incorrect header causes 403 or 401 errors.
  1. JWT Expiry

    • Tokens expire based on the exp claim.
    • Example (Q25, Q30, Q31): A token with exp: 10s fails after 15s.
  1. Vuex State Updates

    • Mutations must be synchronous.
    • Actions can be async and commit mutations.
  1. Slots in Vue.js

    • Default slot: <slot></slot>
    • Named slots: <slot name="header"></slot>
    • Scoped slots: Pass data to parent.

      <template v-slot:default="{ user }">
        {{ user.name }}
      </template>

4. Summary of Key Questions

QuestionTopicKey Takeaway
Q2this in JavaScriptArrow functions inherit this; others depend on call context.
Q3Vue.js LifecycleOrder: beforeCreate → created → beforeMount → mounted → ...
Q4PromisesFirst resolve/reject wins; others are ignored.
Q6WebSockets vs. SSEWebSockets: full-duplex; SSE: server→client only.
Q7WebhooksTypically use POST.
Q8Array reduceWatch for undefined in edge cases.
Q9this in extracted methodsLoses context unless bound.
Q10Vuex Async Actionsdispatch is async; state updates after commit.
Q14this in Arrow FunctionsLexical scoping: this refers to the surrounding context.
Q15Flask CachingFirst request: slow; subsequent requests: cached (faster).
Q16Async/AwaitMissing return in fetch leaves the promise pending.
Q17Event LoopsetTimeout callbacks run after the call stack is empty.
Q18JWT AuthenticationFlow: Credentials → JWT → Store → Send with requests.
Q19, Q30, Q31CORS & JWTCheck Access-Control-Allow-Origin and token expiry.
Q21Array Methods (map, filter)Chaining operations: map → filter → slice.
Q22Flask ThreadingWithout threaded=True, requests block each other.
Q24Vue SlotsDefault slots fall back to content; named slots require v-slot.
Q25JWT ExpiryTokens expire based on exp; 403 if expired.
Q26Vue v-forSyntax: item in array or (item, index) in array.
Q27GraphQL vs. RESTGraphQL reduces over-fetching; REST returns fixed structures.
Q28Event LoopSingle-threaded but non-blocking via event loop.
Q29Vuex MutationsMust be synchronous; use actions for async.
Q32, Q33Vue Router & AuthRedirects based on isAuthenticated and userRole.