Home / Past papers / MAD2 End Term / this paper

Consider the following Script embedded in an HTML document.
```javascript
let langName = 'Python';
function showLanguage() {
let langName = "JavaScript";
let message = 'Learn ' + langName;
console.log(message);
}
let message = 'Learn ' + langName;
console.log(message)
console.log(showLanguage());
```
What will be the output on console, if the HTML document is rendered using a browser?
Learn JavaScript Learn Python

Learn JavaScript Learn JavaScript undefined

Learn Python Learn JavaScript

Learn Python Learn JavaScript undefined

Consider the following Script embedded in an HTML document.
```javascript
let x = [1, 'p', a => a + 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?
Assuming the URL gives a valid json response, what will be the output in the console?
```javascript
fetch('https://study.iitm.ac.in/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
console.log('End of script');
```
Consider the following Script embedded in an HTML document.
```javascript
let myQual = {
degree: "B-tech",
college: "IIT Delhi",
get qualification(){
return `degree: ${this.degree}, college: ${this.college}`
},
set qualification(q){
let components = q.split(' ');
this.degree = components[0];
this.college = components[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(myQual.qualification()) ```

```javascript console.log(myQual.qualification) ```

```javascript console.log(myQual.qualification = 'M-tech IIT-Madras') ```

```javascript
console.log(myQual.qualification('M-tech IIT-Madras'))
```
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
}
})
```
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-if is falsy, it removes the entire element from the DOM.

When the directive v-show 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.

Consider the following Vue application and the rendered HTML output below.
Filename: script.js
```javascript
var app = new Vue({
el: '#app',
data: {
items: [
{id: 1, name:"mad 1"},
{id: 2, name:"mad 2"},
{id: 3, name:"mad 3"}
]
}
})
```
Rendered output:
mad 1
mad 2
mad 3
What should be the content of `<div id = "app"></div>` in index.html that generates the given rendered output?
```html
<h2 v-for="item in items">{{item.name}}</h2>
```
```html
<h2 v-for="item in items">{{item.id}}>{{item.name}}</h2>
```
```html
<h2 v-for="item in items" :id="item.id">{{item.name}}</h2>
```
```html <h2 v-for="items" :id="item.id">item.name</h2> ```

Consider the following Script embedded in an HTML document.
```javascript
class Twowheeler {
constructor(name) {
this.name = name;
this.gear = 4;
this.seating = 2;
}
get description() {
return `${this.name} has ${this.gear} gear and has ${this.engine} engine.`;
}
}
class Moped extends Twowheeler {
constructor(name) {
super(name);
this.engine = '4 stroke';
}
}
let myBike = new Twowheeler("Discover");
let myDrive = new Moped("Activa");
console.log(myDrive.description);
console.log(myBike.description);
```
What will be the output on console, if the HTML document is rendered using a browser?
``` Discover has 4 gear and has 4 stroke engine. Activa has 4 gear and has 4 stroke engine. ```

``` Activa has 4 gear and has undefined engine. Discover has 4 gear and has 4 stroke engine. ```

```text Activa has 4 gear and has 4 stroke engine. Discover has 4 gear and has undefined engine. ```

```text Discover has 4 gear and has undefined engine. Activa has 4 gear and has undefined engine. ```

Consider the following Script embedded in an HTML document.
```javascript
function parentFunc(name) {
return {
sayHello: () => "Hi! " + name,
sayBye: () => "Bye! " + name,
changeName: (newName) => {
name = newName;
},
};
}
const arpan = parentFunc("Arpan");
const beli = parentFunc("Beli");
console.log(arpan.sayHello());
console.log(beli.sayHello());
arpan.changeName("Beli");
console.log(arpan.sayBye());
```
What will be the output on console, if the HTML document is rendered using a browser?
``` Hi! Arpan Bye! Arpan ```

``` Hi! Arpan Hi! Beli Bye! Beli ```

``` Hi! Arpan reference Error ```

Reference Error

What will be the text displayed in a web page if the Vue app given below is running
in a development mode?
Filename: index.html
```html
<div id="app1">
<h1>{{ title }}</h1>
<h4>{{ greetings() }}</h4>
</div>
<div id="app2">
<h1>{{ title }}</h1>
<h4>{{ greetings }}</h4>
</div>
```
Filename: app.js
```javascript
new Vue({
el: "#app1",
data: { title: "App No 1" },
computed: {
greetings() {
return "hello from " + this.title;
},
},
});
new Vue({
el: "#app2",
data: { title: "App No 2" },
computed: {
greetings() {
return "hello from " + this.title;
},
},
});
```
App No 1 hello from App No 1 App No 2 hello from App No 2

App No 2 hello from App No 2

App No 1 App No 2

Blank page

Consider the following Script embedded in an HTML document.
```javascript
var var1 = 25;
var var2 = 35;
const myObj = {
var2: 45,
var1: 35,
ObjFunc: function(var3){
let var4 = var3**2;
return 10 + this.var2 + var4;
}
}
let m = myObj.ObjFunc
console.log(m.bind()(5))
console.log(m.call(myObj,6))
```
What will be the output on console, if the HTML document is rendered using a browser?
``` 70 81 ```

``` 70 91 ```

``` 80 81 ```

``` 80 91 ```

Consider the following Script embedded in an HTML document.
```javascript
let obj1 = {
subject: 'Mechanics',
stream: 'Physics'
}
let obj2 = obj1;
let obj3 = {};
for (let key in obj1){
obj3[key] = obj1[key];
}
obj2.subject = 'Thermodynamics'
obj3.stream = 'Chemistry'
console.log(Obj1)
```
What will be the output on console, if the HTML document is rendered using a browser?
```
{
subject: 'Thermodynamics',
stream: 'Physics'
}
```
```
{
subject:'Mechanics',
stream:'Chemistry'
}
```
```
{
subject: 'Mechanics',
stream: 'Physics'
}
```
```
{
subject:'Thermodynamics',
stream:'Chemistry'
}
```
Consider the following Script embedded in an HTML document.
```javascript
var var1 = 25;
const exObj = {
var2: 45,
var1: 35,
inObj : {
var1: 45,
inObjFunc: ()=>{
return "Value is " + this.var1;
}
},
exObjFunc: function(){
let var2 = 10;
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 35 Value is 10 ```

``` Value is 35 Value is 45 ```

Value is 25 Value is 10

``` Value is 25 Value is 45 ```

Consider the following Script "script.js" embedded in an HTML document, "index.html" and an external script "app.js" given below.
Filename: index.html
```html
<html lang="en">
<head></head>
<body>
<script src="./script.js"></script>
</body>
</html>
```
Filename: script.js
```javascript
function loadScript(src, cbf){
let script = document.createElement('script');
script.src = src;
script.onload = () => cbf();
document.head.append(script);
}
let cbf = function(){
console.log("callback function executed here.");
extFunc()
}
loadScript("./support_m6.js", cbf)
extFunc()
```
Filename: app.js
```javascript
console.log("Now I am loaded, let's support")
function extFunc(){
console.log("loaded and run from external script")
}
```
What will be the output on console, if the HTML document is rendered using a browser?
``` Now I am loaded, let's support callback function executed here. loaded and run from external script loaded and run from external script ```

``` loaded and run from external script Now I am loaded, let's support callback function executed here. loaded and run from external script ```

``` Now I am loaded, let's support callback function executed here. loaded and run from external script Uncaught ReferenceError: extFunc is not defined ```

``` Uncaught ReferenceError: extFunc is not defined Now I am loaded, let's support callback function executed here. loaded and run from external script ```

Consider the below JavaScript program.
```javascript
Array.prototype.double = function (arr) {
const res = [];
for (let i=0; i<placeholder.length; i++)
res.push(placeholder[i] * 2);
return res;
}
const arr = [2, 3, 7, 8];
console.log(arr.double());
```
What of the following can be used in place of "placeholder" in the above program so that the program yields the below output array?
[ 4, 6, 14, 16 ]
Consider the below JavaScript program.
```javascript
const fetchData = (url) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url.includes("success")) {
resolve(`Data fetched successfully from: ${url}`);
} else {
reject(`Error fetching data: ${url}`);
}
}, 1000);
});
};
const processData = (data) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(`Processed data: ${data.toUpperCase()}`);
}, 500);
});
};
const handleError = (error) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(`Handled Error: ${error}`);
}, 300);
});
};
fetchData("https://example.com/success")
.then(processData)
.then(fetchData)
.then(handleError)
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
});
```
What will be the output of the above program, if executed?
Handled Error: Processed data: DATA FETCHED SUCCESSFULLY FROM: HTTPS://EXAMPLE.COM/SUCCESS

Error fetching data: Processed data: DATA FETCHED SUCCESSFULLY FROM: HTTPS://EXAMPLE.COM/SUCCESS

Handled Error: ERROR FETCHING DATA FROM: UNDEFINED

Handled Error: ERROR FETCHING DATA FROM: HTTPS://EXAMPLE.COM/SUCCESS

Error fetching data: Processed data: UNDEFINED

Consider the following Vuex module definition for managing a shopping cart.
```javascript
const cartModule = {
state: {
items: []
},
mutations: {
addItem(state, item) {
state.items.push(item);
},
},
actions: {
async addToCart({ commit }, item) {
// TODO: Implement adding item to cart
},
},
}
```
Which of the following options correctly completes the code for the "addToCart" action function?
```javascript
addToCart({ commit }, item) {
commit('addItem', item);
}
```
```javascript
addToCart({ state, commit }, item) {
const existingItem = state.items.find(i => i.id === item.id);
if (existingItem) {
commit('addItem', existingItem);
} else {
commit('addItem', item);
}
}
```
```javascript
addToCart({ commit }, item) {
commit('addItem', { ...item });
}
```
All of these

Consider the following Vue application with markup "index.html" and JavaScript file "app.js".
index.html:
```html
<div id = "app">
<input v-model = "subject" @input = "compute_marks">
<p> {{marks}} </p>
</div>
<script scr = "app.js"></script>
```
app.js:
```javascript
new Vue({
el : "#app",
data : {
subject : "AppDev",
marks : 50,
},
mounted () {
this.subject = "AppDev";
this.marks = 50;
if (localStorage.marks) {
this.subject += "1";
this.marks = parseInt(localStorage.marks) + 20;
localStorage.marks = this.marks;
localStorage.subject = this.subject;
}
else {
this.subject += "2";
this.marks += 20;
}
},
methods : {
compute_marks() {
localStorage.setItem("subject", this.subject);
localStorage.setItem("marks", this.marks + 10);
}
}
})
```
Suppose you open "index.html" file in a browser, and type the text "EndTermExam" in the text box shown (after removing the previous text, if any), and hard refresh the page thrice, without clicking anywhere. What will be the value shown in the text box, and the "marks" placeholder, respectively?
Consider the following Vue application with markup "index.html" and JavaScript file "app.js".
index.html:
```html
<div id="app">
<router-link :to="{ name: 'user', params: { id: 'Jyoti' }}">User Profile</router-link>
<router-view></router-view>
</div>
<script src="app.js"></script>
```
app.js:
```javascript
const UserProfile = {
template: `
<div>
<h1>User Profile</h1>
<p>User ID: {{ id }}</p>
</div>
`,
props: ['id']
};
const routes = [
{ path: '/user/:id', name: 'user', component: UserProfile, props: true }
];
const router = new VueRouter({
routes
});
new Vue({
el: '#app',
router,
});
```
Based on this setup, what will be displayed in the browser when the user clicks on the "User Profile" link?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 a Mermaid knowledge graph to visualize relationships.
Variable Scoping & Hoisting
var, let, const (block vs. function scope).let/const are hoisted but not initialized).window object in browsers).Closures & this Binding
this in arrow functions (=>) vs. regular functions.call, apply, bind).Asynchronous JavaScript
then, catch, finally), async/await.fetch API and error handling.Object Prototypes & Inheritance
Object.prototype.this in methods vs. arrow functions.Error Handling
try/catch, throw.// Hoisting Example
console.log(a); // undefined (var is hoisted)
var a = 5;
// Closure Example
function outer() {
let x = 10;
return function inner() { console.log(x); };
}
const innerFunc = outer();
innerFunc(); // 10
// `this` Binding
const obj = { val: 42, getVal: function() { return this.val; } };
console.log(obj.getVal.call({ val: 100 })); // 100
// Promise Example
fetch('url')
.then(res => res.json())
.catch(err => console.error(err))
.finally(() => console.log("Done"));
Arrow Functions (=>):
this binding (lexical scoping).Destructuring & Spread/Rest Operators
...) for copying/merging.Classes & Inheritance
class, extends, super.Modules
import/export syntax.Template Literals
${expression}.// Destructuring
const { a, b } = { a: 1, b: 2 };
const arr = [1, 2, 3];
const [x, ...rest] = arr; // x=1, rest=[2,3]
// Class Example
class Parent {
constructor(name) { this.name = name; }
greet() { return `Hello, ${this.name}`; }
}
class Child extends Parent {
constructor(name) { super(name); }
}
// Module Export
export const foo = () => console.log("Foo");
Vue Instance & Lifecycle Hooks
created, mounted, updated, destroyed.Directives
v-if (removes DOM element), v-show (toggles display: none).v-for, v-bind, v-model (two-way binding).Components & Props
props, $emit).<component :is="...">).State Management (Vuex)
state, getters, mutations, actions.Routing (Vue Router)
/user/:id).router-link, router-view.// Vue Instance
new Vue({
el: '#app',
data: { message: 'Hello' },
mounted() { console.log('Mounted!'); }
});
// Vuex Store
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) { state.count++; }
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => commit('increment'), 1000);
}
}
});
// Vue Router
const routes = [
{ path: '/user/:id', component: User, props: true }
];
const router = new VueRouter({ routes });
Fetch API
fetch(url).then(res => res.json()).EventSource (Server-Sent Events)
WebSockets
new WebSocket('ws://url').// Fetch with Error Handling
fetch('https://api.example.com/data')
.then(res => {
if (!res.ok) throw new Error('HTTP error');
return res.json();
})
.catch(err => console.error(err));
// Server-Sent Events
const eventSource = new EventSource('/updates');
eventSource.onmessage = (e) => console.log(e.data);
// WebSocket
const socket = new WebSocket('wss://example.com');
socket.onmessage = (e) => console.log(e.data);
Celery (Task Queue)
Message Brokers
Caching
CORS (Cross-Origin Resource Sharing)
Access-Control-Allow-Origin header.OPTIONS).// Local Storage
localStorage.setItem('key', 'value');
const data = localStorage.getItem('key');
// Session Storage
sessionStorage.removeItem('key');
sessionStorage.clear();
// CORS Headers (Server-Side)
response.setHeader('Access-Control-Allow-Origin', '*');
HTTP Methods
GET (idempotent), POST, PUT (idempotent), DELETE (idempotent).Status Codes
200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Server Error.REST Principles
Authentication
### Successful Response
HTTP/1.1 200 OK
Content-Type: application/json
{ "id": 1, "name": "Example" }
### Error Response
HTTP/1.1 404 Not Found
Content-Type: application/json
{ "error": "Resource not found" }
Console Methods
console.log, console.error, console.table.Source Maps
Vue DevTools
// Debugging Objects
console.table([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);
// Error Boundaries (Vue)
new Vue({
errorCaptured(err, vm, info) {
console.error('Error:', err);
return false; // Prevent propagation
}
});