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 core topics, concepts, and principles essential for the exam, along with key equations (where applicable) and Mermaid knowledge graphs to visualize relationships.
Closures:
Example:
function outer() {
let x = 10;
return function inner() { console.log(x); };
}
const innerFunc = outer();
innerFunc(); // Output: 10 (x is retained via closure)this Context:
this refers to the object calling the function.this from the surrounding scope (lexical this).bind() permanently sets this for a function.Example:
const obj = { name: "Alice", greet: function() { console.log(this.name); } };
const greet = obj.greet;
greet(); // Output: undefined (this is lost)
const boundGreet = obj.greet.bind(obj);
boundGreet(); // Output: "Alice"Event Loop & Asynchronous JavaScript:
setTimeout, setInterval).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:
async/await is syntactic sugar for Promises..catch() or try/catch with await.Example:
async function fetchData() {
try {
const data = await Promise.reject("Error");
} catch (e) {
console.log(e + " caught"); // Output: "Error caught"
}
}Arrow Functions vs. Regular Functions:
Arrow functions:
this binding (lexical scope).Regular functions:
this (depends on how called).new). InnerFunction.[[Scope]] = OuterFunction.[[Scope]] + OuterFunction.LocalVars `` Promise.resolve(value) .then(x => x + 1) .then(x => Promise.resolve(x + 1)) .catch(e => console.log(e)); `` Sync Code > Microtasks (Promises) > Macrotasks (setTimeout, I/O) ``Reactivity System:
Object.defineProperty or Proxy) to track dependencies.data() must return an object for reactivity.Example:
data() {
return { count: 0 }; // Reactive
}beforeCreate | Before instance initialization. | | created | After instance creation (data/props ready). | | beforeMount | Before DOM insertion. | | mounted | After DOM insertion. | | beforeDestroy | Before teardown. | | destroyed | After teardown. |Directives:
v-if vs. v-show:
v-if: Removes/adds DOM element (expensive for toggling).v-show: Toggles display: none (cheaper for frequent toggles).v-for: Renders a list (requires :key for efficiency).v-model: Two-way data binding (e.g., <input v-model="text">).Slots:
<slot></slot>.<slot name="header"></slot>.<slot :data="item">).Example:
<template>
<slot name="header" :title="title"></slot>
</template>
<child>
<template v-slot:header="{ title }">{{ title }}</template>
</child>Vuex:
Core Concepts:
Example:
actions: {
fetchData({ commit }) {
api.call().then(data => commit("SET_DATA", data));
}
},
mutations: {
SET_DATA(state, data) { state.data = data; }
}Watchers:
watch: React to data changes (e.g., API calls on input).deep: true for nested objects.Example:
watch: {
user: {
handler(newVal) { console.log("User changed:", newVal); },
deep: true
}
}Vue Router:
path: '/user/:id'.this.$route.params.id. Vue.set(object, key, value) // Forces reactivity for new properties `` Action (Async) → Commit Mutation → Update State → Re-render Component `` <slot name="slotName" :propName="data"></slot> <template v-slot:slotName="{ propName }">{{ propName }}</template> ``LocalStorage/SessionStorage:
localStorage: Persists across sessions (5MB limit).sessionStorage: Cleared when tab closes.Methods:
localStorage.setItem("key", JSON.stringify(data));
const data = JSON.parse(localStorage.getItem("key"));Cookies:
Attributes:
secure: HTTPS-only.HttpOnly: Inaccessible to JavaScript.SameSite: Strict/Lax/None (CSRF protection).Example:
response.set_cookie("session", "abc123", secure=True, samesite="Strict")CSP (Content Security Policy):
Example Header:
Content-Security-Policy: default-src 'self';<script src="https://evil.com">).SQL Injection:
Use parameterized queries:
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))CSRF (Cross-Site Request Forgery):
Mitigate with:
SameSite cookies. Set-Cookie: name=value; Secure; HttpOnly; SameSite=Strict `` default-src 'self' → Blocks all external resources. ``Event Propagation:
stopPropagation(): Prevents further propagation.Example:
element.addEventListener("click", e => {
e.stopPropagation(); // Stops bubbling
}, { capture: true }); // Capturing phaseEvent Delegation:
Example:
document.getElementById("parent").addEventListener("click", e => {
if (e.target.matches(".child")) {
console.log("Child clicked!");
}
}); Capturing Phase → Target Phase → Bubbling Phase `` ParentListener → e.target → Child Element ``Modules (ES6):
import/export for modular code.Example:
// math.js
export const add = (a, b) => a + b;
// app.js
import { add } from './math.js';Destructuring:
Example:
const { name, age } = user;
const [first, ...rest] = [1, 2, 3];Spread/Rest Operators:
[...array1, ...array2]).function(...args)).Optional Chaining (?.):
Example:
const name = user?.profile?.name; // undefined if any step fails| Topic | Key Points to Review |
|---|---|
| Closures | Scope retention, data encapsulation. |
this in JS | Arrow vs. regular functions, bind/call. |
| Event Loop | Microtasks vs. macrotasks, setTimeout vs. Promise. |
| Vue Reactivity | data(), computed properties, watchers. |
| Vuex | Mutations (sync) vs. actions (async). |
| Slots | Default, named, scoped slots. |
| DOM Events | Capturing/bubbling, event delegation. |
| Web Security | CSP, SQL injection, CSRF, cookie attributes. |
| Async Patterns | Promises, async/await, error handling. |
| Vue Router | Dynamic routes, route params. |
Focus Areas for Equations:
default-src 'self' blocks external resources.Secure; HttpOnly; SameSite=Strict.