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.
The provided questions primarily assess knowledge in Modern Application Development using Vue.js 2 and core JavaScript concepts. The exam focuses heavily on understanding reactivity, component architecture, data flow, event handling in Vue, and fundamental JavaScript features like this binding, closures, array manipulation, and scoping.
Vue Instance Lifecycle and Options
el (Element): Specifies the DOM element that the Vue instance will mount to.data (State Management):
data() { return { property: initialValue } }methods (Logic):
this.propertyName.computed (Derived State):
async/await).get and set methods for writable computed properties.latex computed: { propertyName() { return \text{this.dep1} + \text{this.dep2}; } } ``latex computed: { propertyName: { get() { return \text{this.firstName} + ' ' + \text{this.lastName}; }, set(value) { const names = \text{value.split(' ')}; this.firstName = \text{names[0]}; this.lastName = \text{names[1]}; } } } ``Reactivity System and Virtual DOM
Object.defineProperty to convert data properties into getter/setters.Reactivity Limitations (Vue 2 specific):
Array Direct Index Modification: Directly setting an item with this.items[index] = newValue is not reactive.
push, pop, splice, shift, unshift, sort, reverse) or replace the array entirely this.items = [...newArray].this.items.splice(index, 1, newValue)Adding New Properties to Objects: Adding a new property to an already reactive object (this.obj.newProp = value) is not reactive.
Vue.set(object, key, value) or create a new object: this.obj = { ...this.obj, newProp: value }.Templating and Directives
{{ propertyName }} for displaying reactive data in templates.v-model (Two-way Binding): Used for form inputs to create a two-way binding between input values and data properties.
<input v-model="propertyName"> binds the input's value to propertyName and updates propertyName on input events.v-if (Conditional Rendering): Renders an element conditionally based on a truthy/falsy expression. The element is truly added/removed from the DOM.v-on / @ (Event Handling): Listens for DOM events and runs JavaScript when they are triggered.
<button @click="methodName"> or <button v-on:click="methodName">v-bind / : (Attribute Binding): Dynamically binds one or more attributes, or a component prop to an expression.
Dynamic Class Binding: Can be an array or an object.
:class="[classString1, classVar2, { classObj: isTrue }]":class="{ className1: condition1, className2: condition2 }"Components
Props: Custom attributes passed from a parent component to a child component, used for unidirectional data flow.
props: ['propName'] in child component definition.<my-component :prop-name="parentData">data option must be a function returning an object to ensure each instance has an independent copy of the data.this Keyword Binding
this refers to the global object (window in browsers) when a function is called directly (func()). In strict mode, it's undefined.obj.method()), this refers to the object (obj) itself.Explicit Binding (call, apply, bind):
function.call(thisArg, arg1, arg2, ...): Executes the function immediately with this set to thisArg.function.apply(thisArg, [argsArray]): Similar to call, but takes arguments as an array.function.bind(thisArg): Returns a new function with this permanently bound to thisArg. The returned function can be invoked later.new Binding (Constructor): When a function is called with new (new Constructor()), this refers to the newly created instance of the object.this is lexically scoped. It inherits this from the enclosing scope where the arrow function was defined, not where it was called. Arrow functions cannot be used as constructors with new.Closures
Scoping (var, let, const)
var: Function-scoped. Variables declared with var are hoisted to the top of their function (or global) scope. Can lead to unexpected behavior in loops with closures.let / const: Block-scoped. Variables are limited to the block ({}) in which they are declared. const is for constants and cannot be reassigned. They solve the common closure issues found with var in loops.Array and Object Manipulation Methods
Array.prototype.filter(): Creates a new array with all elements that pass the test implemented by the provided function.
array.filter(item => item.condition)Array.prototype.map(): Creates a new array populated with the results of calling a provided function on every element in the calling array. Can take an optional thisArg for the callback's this context.
array.map((item, index) => transform(item, index))Array.prototype.sort(): Sorts the elements of an array in place and returns the sorted array. Requires a compareFunction for custom sorting logic.
array.sort((a, b) => a.property - b.property)Array.prototype.forEach(): Executes a provided function once for each array element. Does not return a new array.Object Spread Syntax (...): Copies enumerable own properties from one object to another or creates new objects/arrays.
const newObj = { ...oldObj, newProp: value }