Home / Past papers / MAD2 Quiz 1 / this paper

Consider the following HTML, with the correct Vue 2 CDN links included:
Html code.
```html
<div id="app">
<h3>Shopping Cart</h3>
<p>Items: {{itemCount}}</p>
<p>Total Cost: ${{totalCost}}</p>
<button @click="addItem">Add Item ($15)</button>
<button @click="removeItem">Remove Item</button>
<p>Status: {{status}}</p>
</div>
```
script:
```javascript
const app = new Vue({
el: '#app',
data() {
return {
itemCount: 0,
itemPrice: 15,
totalCost: 0
}
},
computed: {
status() {
if (this.itemCount === 0) {
return 'Empty Cart';
} else if (this.itemCount < 3) {
return 'Few Items';
} else {
return 'Full Cart';
}
}
},
methods: {
addItem() {
this.itemCount++;
this.totalCost += this.itemPrice;
},
removeItem() {
if (this.itemCount > 0) {
this.itemCount--;
this.totalCost -= this.itemPrice;
}
}
}
})
```
If the user clicks the "Add Item" button 3 times, then clicks the "Remove Item" button 1 time, what will be displayed for Items, Total Cost, and Status?
Consider the following code.
```javascript
const arr = [1, 2, 3];
const result = arr.map(function(item, index) {
return this[index] * item;
}, [10, 20, 30]);
console.log(result);
```
What will be the output?
In Vue 2, which of the following will NOT trigger reactivity?
```javascript
data() {
return {
items: [1, 2, 3],
obj: { a: 1 }
}
}
```
What will be the output of this code?
```javascript
function createFunctions() {
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(function() {
return i;
});
}
return funcs;
}
const functions = createFunctions();
console.log(functions[0](), functions[1](), functions[2]());
```
```javascript
computed: {
fullName() {
return this.firstName + ' ' + this.lastName;
}
}
```
```javascript
computed: {
fullName: {
get() { return this.firstName + ' ' + this.lastName; },
set(value) {
const names = value.split(' ');
this.firstName = names[0];
this.lastName = names[1];
}
}
}
```
```javascript
computed: {
async fullName() {
return await this.fetchFullName();
}
}
```
```javascript
computed: {
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
}
```
Consider the following JavaScript code:
```javascript
const products = [
{ id: 101, name: "laptop", price: 800 },
{ id: 102, name: "mouse", price: 25 },
{ id: 103, name: "keyboard", price: 60 },
{ id: 104, name: "monitor", price: 300 }
];
const priorities = { "102": 1, "104": 2, "101": 3, "103": 4 };
products
.filter((product) => product.price > 50)
.map((product) => {
return { ...product, priority: priorities[product.id] }
})
.sort((a, b) => a.priority - b.priority)
.forEach((product) => {
console.log(product.name);
});
```
What will be the output of the code?
``` laptop keyboard monitor ```

monitor laptop keyboard

``` mouse monitor laptop keyboard ```

``` laptop mouse keyboard monitor ```

The code will throw an error

Consider the following JavaScript code to answer the below question:
```javascript
const grandParent = {
username: 'GrandParent',
getName: function () {
return this.username;
},
parent: {
username: 'Parent',
getName: function () {
return this.username;
},
child: {
username: 'Child',
getNameArrow: () => {
return this.username;
},
getNameFunc: function () {
return this.username;
}
}
}
};
console.log("A: " + grandParent.getName());
console.log("B: " + grandParent.parent.getName());
console.log("C: " + grandParent.parent.child.getNameFunc());
console.log("D: " + grandParent.parent.child.getNameArrow());
```
What will be the result of all the console.log after execution of the above code?
A: GrandParent B: Parent C: Child D: Reference Error

A: GrandParent B: Parent C: undefined D: Child

A: GrandParent B: GrandParent C: Parent D: GrandParent

``` A: GrandParent B: Parent C: Child D: undefined ```

Consider the following Vue.js (Vue 2) code to answer the following question:
```html
<div id="app">
<my-counter :start="5"></my-counter>
</div>
<script>
Vue.component('my-counter', {
props: ['start'],
data: function () {
return {
count: this.start
};
},
template: `
<div>
<p>{{ count }}</p>
<button @click="increment">Increment</button>
</div>
`,
methods: {
increment() {
this.count++;
}
}
});
new Vue({
el: '#app',
data: { start: 10 }
});
</script>
```
What will be displayed when the page loads, and what happens when you click the button?
The counter starts at 10, and increments by 1 on each button click.

The counter starts at 5, and increments by 1 on each button click.

Nothing is rendered because the Vue component template is invalid when using Vue via CDN.

Vue throws a warning about compiling templates in the browser and fails to bind the component.

Consider the following JavaScript program:
```javascript
function createMultiplier(base) {
let multiplier = base;
function updateMultiplier(newValue) {
multiplier = newValue;
return multiplier;
}
function multiply(num) {
return num * multiplier;
}
return {
update: updateMultiplier,
calculate: multiply,
getMultiplier: function() { return multiplier; }
};
}
const math1 = createMultiplier(3);
const math2 = createMultiplier(5);
console.log(math1.calculate(4));
console.log(math2.calculate(2));
console.log(math1.update(7));
console.log(math1.calculate(4));
console.log(math2.getMultiplier());
console.log(math1.getMultiplier());
```
What will be the output of the above program?
Consider the following JavaScript code snippet:
```javascript
var globalScore = 25;
const player1 = {
score: 150,
getScore: function() {
return this.score;
},
displayScore: function(bonus) {
return this.score + (bonus || 0);
}
};
const player2 = { score: 200 };
const player3 = { score: 75 };
const method1 = player1.getScore;
const method2 = player1.getScore.bind(player2);
const method3 = player1.displayScore.bind(player3);
console.log(method1());
console.log(method2());
console.log(method3(50));
console.log(method3.call(player1, 25));
```
What will be the output of the above JavaScript code?
Consider the following JavaScript code to answer the below question:
```javascript
function normalFunc() {
console.log(this.constructor.name);
}
const arrowFunc = () => {
console.log(this.constructor.name);
};
const objj = {
name: 'Test',
normalMethod: normalFunc,
arrowMethod: arrowFunc,
outer: function () {
return () => {
console.log(this.name);
};
},
};
const inner = objj.outer();
objj.normalMethod();
objj.arrowMethod();
inner();
new arrowFunc();
```
Which of the following statements is/are TRUE?
``` obj.normalMethod() prints "Object" ```

obj.arrowMethod() prints "Window" or throws an error in strict mode

inner() prints "Test"

new arrowFunc() throws an error because arrow functions cannot be used as constructors


```html <input v-model="username"> should be replaced with <input v-bind="username"> ```

``` @click="loggedIn = true" should be replaced with v-on:click="login()" ```

v-if="loggedIn" should be replaced with v-show="loggedIn"

The code works correctly; no change is required.

If you wanted to make this app more maintainable by moving logic to **methods**, which line would you replace?

Replace `@click="loggedIn = true"` with `@click="login"` and define a method

Replace `<input v-model="username">` with `v-on:input="updateUsername"`

Replace v-if="loggedIn" with v-else="loggedIn"

This code is best, no changes required.


What classes will be applied to the `<div>` initially (before any button clicks)?

What classes will be applied to the `<div>` after clicking the "Toggle State" button once?
Auto-generated summary from the source site. Handy as a checklist; the lessons above explain each idea from scratch.
Reactivity in Vue 2
this.items[0] = 10) do not.Computed Properties
Example:
computed: {
fullName() {
return this.firstName + ' ' + this.lastName;
}
}Methods and Event Handling
Example:
methods: {
increment() {
this.count++;
}
}Component Communication
Example:
props: ['start']Conditional Rendering
v-if and v-show are used to conditionally render elements.Example:
<p v-if="loggedIn">Welcome, {{ username }}!</p>Class and Style Binding
:class and :style.Example:
<div :class="[baseClass, { highlighted: isHighlighted, 'btn-primary': isPrimary }]">Closures and Scope
Example:
function createFunctions() {
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(function() {
return i;
});
}
return funcs;
}Arrow Functions
this context; they inherit this from the surrounding lexical context.Example:
const arrowFunc = () => {
console.log(this.constructor.name);
};Array Methods
map, filter, sort, and forEach.Example:
products
.filter((product) => product.price > 50)
.map((product) => {
return { ...product, priority: priorities[product.id] };
})
.sort((a, b) => a.priority - b.priority)
.forEach((product) => {
console.log(product.name);
});Object Methods and this Context
this behaves in different contexts, especially in object methods and constructors.Example:
const obj = {
name: 'Test',
normalMethod: function() {
console.log(this.name);
},
arrowMethod: () => {
console.log(this.name);
}
};Bind, Call, and Apply
bind, call, and apply to set the this context of functions.Example:
const method2 = player1.getScore.bind(player2);Template Syntax
{{ }} for text interpolation and directives like v-model, v-if, and v-on.Example:
<input v-model="username">
<button @click="loggedIn = true">Login</button>Dynamic Class Binding
:class to dynamically bind classes based on data properties.Example:
<div :class="[baseClass, { highlighted: isHighlighted }]">