Home / Past papers / MAD2 End Term / this paper

Consider the below JavaScript program.
```javascript
console.log("Start");
setTimeout(function() {
console.log("Inside Timeout");
}, 0);
Promise.resolve().then(function() {
console.log("Inside Promise");
});
console.log("End");
```
What will be the output of the above program?
Consider the below JavaScript program.
```javascript
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log("Hello, " + this.name);
};
const john = new Person("John");
john.greet();
delete john.greet;
john.greet();
```
What will be the output of the above program?
Consider the below Vue app.
```javascript
new Vue({
el: '#app',
data: {
user: {
name: 'Abhi',
age: 30
}
},
watch: {
user: {
handler(newValue, oldValue) {
console.log('User object changed:', newValue);
},
deep: true
}
}
});
```
What will happen if the following code is executed?
app.user.name = "Dev"
Consider the below Vue component.
```html
<template>
<div>
<p v-if="isVisible">This paragraph is visible</p>
<p v-else>This paragraph is hidden</p>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
};
}
};
</script>
```
What will happen when "this.isVisible = false" is executed?
In the following code, which attributes ensure that the cookie will only be sent over HTTPS and restrict it from cross-site requests?
```
response.set_cookie('session_id', 'abc123', secure=option1, samesite=option2)
```
Consider the following JavaScript code.
```javascript
function addItemToCart(item) {
let cart = JSON.parse(localStorage.getItem('cart')) || [];
cart.push(item);
localStorage.setItem('cart', JSON.stringify(cart));
}
function getCartItems() {
return JSON.parse(localStorage.getItem('cart')) || [];
}
addItemToCart({ id: 1, name: 'Laptop' }.name);
console.log(getCartItems());
```
The above code is initially loaded on the browser and then the browser is refreshed two times.
What will be the final output?
What's the issue with this Vuex mutation? Assuming this mutation is part of vuex store.
```javascript
mutations: {
updateUser(state, userData) {
state.user = userData
state.lastUpdated = Date.now()
if (userData.role === 'admin') {
fetchAdminData().then(data => {
state.adminData = data
})
}
}
}
```
Suppose you want the user data to only be accessible by an authenticated user.
What security issue exists in this code?
// Javascript
```javascript
methods: {
async fetchUserData() {
const response = await fetch(`/api/user/${this.userId}`)
const data = await response.json()
this.userData = data
}
}
```
# Flask route
```python
@app.route('/api/user/<user_id>')
def get_user(user_id):
query = f"SELECT * FROM users WHERE id = {user_id}"
result = db.execute(query)
return jsonify(result)
```
Given this Vue component structure:
```javascript
Vue.component('child', {
template: `
<div>
<slot name="header" :info="info"></slot>
<slot :info="info"></slot>
</div>
`,
data() {
return {
info: { title: 'Hello', desc: 'World' }
}
}
})
```
Which slot usage is correct?
```html
<template v-slot:header="data">{{data.title}}</template>
```
```html
<template v-slot:header="{ info }">{{info.title}}</template>
```
```html
<template v-slot:header>{{info.title}}</template>
```
```html
<template v-slot:header=info>{{info.title}}</template>
```
Consider the following JavaScript code snippet.
```javascript
Promise.resolve(1)
.then(x => x + 1)
.then(x => Promise.resolve(x + 1))
.then(x => { throw 'error' })
.catch(e => e + 4)
.then(x => console.log(x))
```
consider the following javascript code snippet.
```javascript
async function test() {
console.log("Start");
const val = await Promise.resolve(5);
console.log(val);
return "End";
}
console.log("Begin");
test().then(data => console.log(data));
console.log("Finish");
```
What will be the output sequence?
``` @cache.memoize() caches function results based on arguments, while @cache.cached() caches entire views. ```

``` @cache.cached() caches function results based on arguments, while @cache.memoize() caches entire views. ```

Both cache entire views, but `@cache.memoize()` uses Redis by default.

Both methods are identical but use different syntax.

Consider the following Script embedded in an HTML document.
```javascript
let x = [100, 'x', num => num + 1];
for (const i = 0; i<x.length; i++) {
console.log(i, x[i], typeof(x[i]))
}
```
Which of the following statement is correct, if the HTML document is rendered using a browser?
Consider the below JavaScript program.
```javascript
const obj = {
name: "Abhi",
greet: function() {
console.log(this.name);
}
};
const greet = obj.greet;
greet();
```
What will be the output of the above program?
Abhi

undefined

null

Reference Error

Garbage Value

Consider the below JavaScript program.
```javascript
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
const newPerson = person.fullName.bind({
firstName: "Jane",
lastName: "Smith"
});
console.log(newPerson());
```
What will be the output of the above program?
John Doe

Jane Smith

John Smith

Jane Doe

undefined

null

Reference Error

Consider the following JavaScript code.
```javascript
function add(x) {
return function (y) {
return x + y;
};
}
const addFive = add(5);
console.log(addFive(10));
```
What will be the output of the code snippet?
What will happen if a page includes this CSP header and the script attempts to load an external JavaScript file from otherurl.com? **CSP Header:** ``` Content-Security-Policy: default-src 'self'; ``` **HTML :** ```html <script src="https://otherurl.com/code.js"></script> ```

The script from otherurl1.com will load normally.

The script will fail to load, and an error will be logged in the console.

The browser will display a warning and allow the script to load.

Nothing will happen; the CSP only affects inline scripts.

Consider the below HTML document.
```html
<!DOCTYPE html>
<html>
<body>
<div>
<div id="grandparent">GrandParent
<div id="parent">Parent
<div id="child"> Child</div>
</div>
</div>
</div>
<script>
const grandParent = document.getElementById("grandparent");
const parent = document.getElementById("parent");
const child = document.getElementById("child");
grandParent.addEventListener("click", (e) => {
console.log("GrandParent");
}, { capture: true });
parent.addEventListener("click", (e) => {
console.log("Parent");
}, { capture: true });
child.addEventListener("click", (e) => {
console.log("Child");
}, { capture: true });
</script>
</body>
</html>
```
What will be logged on the console, if the user opens the rendered web page in a browser and clicks the text "Child"?
Given the following Vuex store setup.
```javascript
const store = new Vuex.Store({
state: {
counter: 0
},
mutations: {
increment(state) {
state.counter++;
}
},
actions: {
async incrementAsync({
commit
}) {
await new Promise(resolve => setTimeout(resolve, 1000));
commit('increment');
}
}
});
```
Assuming the store is correctly binded with a Vue app, what will be the correct behavior when the following code is executed?
`this.$store.dispatch('incrementAsync');`
Consider the following HTML with Vue CDN included?
```html
<div id="app"></div>
<script>
Vue.component('my-button', {
template: `
<button @click="handleClick">
<slot></slot>
</button>
`,
methods: {
handleClick() {
console.log('Button')
this.$emit('click')
}
}
})
new Vue({
el: '#app',
template: `
<my-button @click="parentClick">
Click me
</my-button>
`,
methods: {
parentClick() {
console.log('Parent')
}
}
})
</script>
```
What will be logged on the console after the button is pressed?
Consider the following HTML with appropriate Vue 2 CDN link attached.
```html
<div id="app"></div>
<script>
new Vue({
el: '#app',
template: `
<div>
<p>Likes: {{ displayLikes }}</p>
<button @click="handleLike">Like</button>
</div>`,
data() {
return {
post: {
likes: 5,
metadata: { lastUpdated: null }
}
}
},
computed: {
displayLikes: {
get() {
return this.post.likes;
},
set(value) {
this.post.likes = value;
}
}
},
methods: {
handleLike() {
Promise.resolve().then(() => {
this.displayLikes++;
});
this.displayLikes += 1;
setTimeout(() => {
this.displayLikes = this.displayLikes + 1;
}, 0);
}
}
})
</script>
```
What will be rendered in the `<p>` tag after the Like button is pressed once?
Consider the following HTML, which includes Vue 2 and Vuex CDN links.
```html
<div id="app">
<p v-if="userData">User: {{ userData.name }}</p>
<p v-else>No user data available</p>
</div>
<script>
const store = new Vuex.Store({
state: {
userData: null
},
mutations: {
setUserData(state, data) {
state.userData = data;
}
},
actions: {
fetchUserData({ commit }) {
return fetch('https://httpstat.us/500')
.then(response => {
if (!response.ok) throw new Error('Network error');
return response.json();
})
.then(data => {
commit('setUserData', data);
},
error => {
commit('setUserData', { name: 'Luke' })
})
.catch(() => {
commit('setUserData', null);
});
}
}
});
new Vue({
el: '#app',
store,
created() {
this.$store.dispatch('fetchUserData');
},
computed: {
userData() {
return this.$store.state.userData;
}
}
});
</script>
```
What will be rendered on the browser, if the fetch request gets back 500 status code?
Consider the following Script embedded in an HTML document.
```javascript
let bsCourses = {
subject: 'MAD II',
stream: 'Programming'
}
let esCourses = bsCourses;
let msCourses = {};
for (let course in bsCourses){
msCourses[key] = bsCourses[key];
}
esCourses.subject = 'Embedded C'
msCourses.stream = 'Electronics'
console.log(msCourses)
```
What will be the output on console, if the HTML document is rendered using a browser?
```
{
subject:'MAD II',
stream:'Programming'
}
```
```
{
subject:'Embedded C',
stream:'Electronics'
}
```
```
{
subject:'MAD II',
stream:'Electronics'
}
```
```
{
subject:'Embedded C',
stream:'Programming'
}
```
Consider the following Script embedded in an HTML document.
```javascript
var var1 = 56;
const exObj = {
var2: 24,
var1: 15,
inObj : {
var1: 75,
inObjFunc: ()=>{
return "Value is " + this.var1;
}
},
exObjFunc: function(){
let var2 = 14;
return "Value is " + this.var2;
}
}
let x = exObj.inObj
console.log(x.inObjFunc())
console.log(exObj.exObjFunc())
```
What will be the output on console, if the HTML document is rendered using a browser?
Value is 75 Value is 24

``` Value is 56 Value is 24 ```

Value is 15 Value is 14

``` Value is 56 Value is 14 ```

Consider the following Script embedded in an HTML document.
```javascript
let myBox = {
tool: "Wrench",
cutter: "Machine Cutter",
get tools(){
return `tool: ${this.tool}, cutter: ${this.cutter}`
},
set tools(q){
let box = q.split(' ');
this.tool = box[0];
this.cutter = box[1];
}
}
```
Which of the following statements will throw an error on the console when the HTML document is rendered using a browser?
```javascript console.log(myBox.tools) ```

```javascript console.log(myBox.tools()) ```

```javascript
console.log(myBox.tools('ScrewDriver Grinder'))
```
```javascript console.log(myBox.tools = 'ScrewDriver Grinder') ```

Consider the following two HTML documents and the Vue app created in script.js file and select the correct option(s).
index1.html
```html
<body>
<div id="app">
<h1 v-if="result">Hello am I visible?</h1>
</div>
<script src="./script.js"></script>
</body>
```
index2.html
```html
<body>
<div id="app">
<h1 v-show="final">Hello am I visible?</h1>
</div>
<script src="./script.js"></script>
</body>
```
script.js
```javascript
var app = new Vue({
el: '#app',
data: {
result: false,
final: false
}
})
```
When the directive v-if is falsy, it removes the entire element from the DOM.

The raw HTML created with index1.html and index2.html will be exactly the same when the values of both "result" and "final" are set to true.

The raw HTML created with index1.html and index2.html will be exactly the same for the current state of data.

When the directive **v-show** is falsy, it removes the entire element from the DOM.

Consider the below Vue router configuration.
```javascript
const routes = [
{
path: '/user/:id',
component: UserProfile
}
];
const router = new VueRouter({
routes
});
```
Which of the following is a valid way to access the "id" parameter inside the UserProfile component?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.
Closures:
Example:
function outer() {
let x = 10;
return function inner() { console.log(x); };
}
const innerFunc = outer();
innerFunc(); // Logs 10 (closure retains access to `x`)this Binding:
this refers to the execution context (object that owns the function).this; they inherit it from the outer scope.bind(), call(), apply() can explicitly set this.Example:
const obj = { name: "Alice", greet: function() { console.log(this.name); } };
const greet = obj.greet;
greet(); // undefined (lost context)
greet.call(obj); // "Alice" (context set to `obj`)Event Loop & Asynchronous JavaScript:
setTimeout, fetch).Promise.then, queueMicrotask).Example:
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
// Output: Start → End → Promise → TimeoutPromises & Async/Await:
pending → fulfilled/rejected.Promise.chain(): .then() for success, .catch() for errors.Async/Await: Syntactic sugar for promises.
async function fetchData() {
const data = await fetch(url);
return data.json();
}Error Handling: try/catch with await.
try {
const result = await someAsyncFunction();
} catch (error) {
console.error(error);
}Prototypal Inheritance:
__proto__ or Object.getPrototypeOf()).prototype vs __proto__:
prototype: Property of constructor functions (e.g., Person.prototype).__proto__: Internal property of objects (points to their prototype).Example:
function Person(name) { this.name = name; }
Person.prototype.greet = function() { console.log(`Hello, ${this.name}`); };
const alice = new Person("Alice");
alice.greet(); // "Hello, Alice"Vue Instance & Lifecycle Hooks:
beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed.Example:
new Vue({
data: { message: "Hello" },
created() { console.log("Component created!"); }
});Reactivity System:
data properties and updates the DOM.Object.defineProperty (Vue 2) or Proxy (Vue 3) for reactivity.Vue.set or this.$set.fullName) | Event handlers | Async/side effects (e.g., API calls) | | Syntax | computed: { fullName() { ... } } | methods: { greet() { ... } } | watch: { user(newVal) { ... } } |v-if vs v-show): | Directive | Behavior | DOM Impact | |-----------|-----------------------------------|--------------------------| | v-if | Toggles element existence | Removes/adds from DOM | | v-show | Toggles display: none | Always in DOM |Slots (Content Distribution):
<slot></slot><slot name="header"></slot>Scoped Slots: Pass data from child to parent.
<!-- Child Component -->
<slot :user="user">{{ user.name }}</slot><!-- Parent Component --> <child v-slot="slotProps">{{ slotProps.user.name }}</child> ```
Vuex (State Management):
Core Concepts:
commit).dispatch).Rules:
Example:
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) { state.count++; }
},
actions: {
asyncIncrement({ commit }) {
setTimeout(() => commit("increment"), 1000);
}
}
});Vue Router:
Dynamic Routes: :id in paths.
{ path: "/user/:id", component: User }Access Route Params:
this.$route.params.id // or this.$route.params["id"]Lifecycle Hooks:
beforeDestroy: Called before teardown (cleanup event listeners).destroyed: Called after teardown.SQL Injection:
Fix: Use parameterized queries.
# Bad (Flask)
query = f"SELECT * FROM users WHERE id = {user_id}"# Good query = "SELECT * FROM users WHERE id = %s" cursor.execute(query, (user_id,)) ```
Cross-Site Request Forgery (CSRF):
Mitigation:
SameSite=Strict or Lax.Content Security Policy (CSP):
Example Header:
Content-Security-Policy: default-src 'self';<script src="https://evil.com">).Cookies & Secure Attributes:
Secure: Only sent over HTTPS.HttpOnly: Inaccessible to JavaScript (mitigates XSS).SameSite:
Strict: Never sent cross-site.Lax: Sent on top-level navigations (e.g., <a href="...">).None: Sent cross-site (requires Secure).Authentication:
Callbacks:
Promises:
pending → fulfilled/rejected..then() for success, .catch() for errors.Static Methods:
Promise.all(): Wait for all promises.Promise.race(): First settled promise.Promise.resolve()/Promise.reject(): Create resolved/rejected promises.Async/Await:
Syntax:
async function fetchData() {
const data = await fetch(url);
return data.json();
}try/catch.| Storage Type | Persistence | Scope | Size Limit | Accessible via JS? |
|---|---|---|---|---|
localStorage | Persists forever | Per-origin | ~5MB | ✅ Yes |
sessionStorage | Cleared on tab close | Per-tab | ~5MB | ✅ Yes |
| Cookies | Configurable (Expires) | Per-domain | ~4KB | ✅ Yes |
| IndexedDB | Persists forever | Per-origin | ~50MB+ | ✅ Yes (Async API) |
localStorage vs sessionStorage:
localStorage: Shared across tabs/windows.sessionStorage: Isolated per tab.Cookie Attributes:
Secure: HTTPS-only.HttpOnly: No JS access.SameSite: CSRF protection.HTTP Methods:
GET: Retrieve data.POST: Submit data.PUT/PATCH: Update data.DELETE: Remove data.HTTP Status Codes:
200 OK: Success.404 Not Found: Resource missing.500 Internal Server Error: Server-side error.Caching Headers:
Cache-Control:
no-store: Never cache.no-cache: Revalidate before use.max-age=3600: Cache for 1 hour.ETag: Validator for cache freshness.Event Propagation:
stopPropagation(): Prevents further propagation.preventDefault(): Cancels default behavior.Event Delegation:
Example:
document.querySelector("#parent").addEventListener("click", (e) => {
if (e.target.matches(".child")) {
console.log("Child clicked!");
}
});(Not directly applicable to this exam, but included for completeness in DS/Algo contexts.)
Time Complexity:
O(1): Constant time.O(n): Linear time.O(n^2): Quadratic time.O(log n): Logarithmic time (e.g., binary search).Space Complexity:
JavaScript:
this binding, and the event loop.prototype vs __proto__.Vue.js:
v-if and v-show.Web Security:
Secure, HttpOnly, and SameSite.Asynchronous Patterns:
Browser Storage:
localStorage vs sessionStorage vs cookies.Secure, HttpOnly, SameSite).Debugging:
console.log to trace execution.catch vs then).