# JavaScript Coding Practice
*Click
if you like the project. Pull Request are highly appreciated.*
## Q. ***Write a program in javascript. sum(2)(3);***
**Example:** Expected output is 5
```javascript
function sum(x, y) {
if (y !== undefined) {
return x + y;
} else {
return function (y) {
return x + y;
};
}
}
```
Output
```js
console.log(sum(2,3)); // Outputs 5
console.log(sum(2)(3)); // Outputs 5
```
0 : 00 : 000
In this example Date() methods co-operate with timing function setInterval().
``` ## Q. ***Write a program to reverse a string?*** ```javascript function reverseString(str) { let stringRev = ""; for (let i = str.length; i >= 0; i--) { stringRev = stringRev + str.charAt(i); } return stringRev; } alert(reverseString("Pradeep")); // Output: peedarP ``` ## Q. ***How to check if object is empty or not in javaScript?*** ```javascript function isEmpty(obj) { return Object.keys(obj).length === 0; } ``` ## Q. ***JavaScript Regular Expression to validate Email*** ```javascript var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; ``` ## Q. ***Use RegEx to test password strength in JavaScript?*** ```javascript var newPassword = "Pq5*@a{J"; var regularExpression = new RegExp( "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})" ); if (!regularExpression.test(newPassword)) { alert( "Password should contain atleast one number and one special character !" ); } ``` | RegEx | Description | | ---------------- |--------------| | ^ | The password string will start this way | | (?=.\*[a-z]) | The string must contain at least 1 lowercase alphabetical character | | (?=.\*[A-Z]) | The string must contain at least 1 uppercase alphabetical character | | (?=.\*[0-9]) | The string must contain at least 1 numeric character | | (?=.[!@#\$%\^&]) | The string must contain at least one special character, but we are escaping reserved RegEx characters to avoid conflict | | (?=.{8,}) | The string must be eight characters or longer | ## Q. ***How to compare objects ES6?*** Example 01: ```javascript const matches = (obj, source) => Object.keys(source).every( (key) => obj.hasOwnProperty(key) && obj[key] === source[key] ); console.log( matches({ age: 25, hair: "long", beard: true }, { hair: "long", beard: true }) ); // true console.log( matches({ hair: "long", beard: true }, { age: 25, hair: "long", beard: true }) ); // false console.log( matches({ hair: "long", beard: true }, { age: 26, hair: "long", beard: true }) ); // false ``` Example 02: ```javascript const k1 = { fruit: "🥝" }; const k2 = { fruit: "🥝" }; // Using JavaScript JSON.stringify(k1) === JSON.stringify(k2); // true ``` Example 03: ```javascript const one = { fruit: "🥝", energy: "255kJ", }; const two = { energy: "255kJ", fruit: "🥝", }; // Using JavaScript JSON.stringify(one) === JSON.stringify(two); // false ``` ## Q. ***How to remove array element based on object property?*** ```javascript var myArray = [ { field: "id", operator: "eq" }, { field: "cStatus", operator: "eq" }, { field: "money", operator: "eq" }, ]; myArray = myArray.filter(function (obj) { return obj.field !== "money"; }); Console.log(myArray); ``` Output ``` myArray = [ {field: "id", operator: "eq"} {field: "cStatus", operator: "eq"} ] ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log(+"meow"); // Output: NaN ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var result; for (var i = 5; i > 0; i--) { result = result + i; } console.log(result); // Output: NaN ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var a = 1.2; console.log(typeof a); // Output: Number ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var x = 10; if (x) { let x = 4; } console.log(x); // Output: 10 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log(0.1 + 0.2 == 0.3); // Output: false ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log(1 + -"1" + 2); // Output: 2 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript (function (x) { return (function (y) { console.log(x); })(10); })(20); // Output: 20 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var num = 20; var getNumber = function () { console.log(num); var num = 10; }; getNumber(); // Output: undefined ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript function f1() { num = 10; } f1(); console.log("window.num: " + window.num); // output: 10 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log("(null + undefined): " + (null + undefined)); // Output: NaN ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript (function () { var a = (b = 3); })(); console.log("value of a : " + a); // Output: undefined console.log("value of b : " + b); // Output: 3 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var y = 1; if (function f() {}) { y += typeof f; } console.log(y); // Output: 1Object ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var k = 1; if (1) { eval(function foo() {}); k += typeof foo; } console.log(k); // Output: 1undefined ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var k = 1; if (1) { function foo() {} k += typeof foo; } console.log(k); // Output: 1function ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log("(-1 / 0): " + -1 / 0); // Output: -Infinity console.log("(1 / 0): " + 1 / 0); // Output: Infinity console.log("(0 / 0): " + 0 / 0); // Output: NaN console.log("(0 / 1): " + 0 / 1); // Output: 0 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var a = 4; var b = "5"; var c = 6; console.log("(a + b): " + (a + b)); // Output: 45 console.log("(a - b): " + (a - b)); // Output: -1 console.log("(a * b): " + a * b); // Output: 20 console.log("(a / b): " + a / b); // Output: 0.8 console.log("(a % b): " + (a % b)); // Output: 4 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log("MAX : " + Math.max(10, 2, NaN)); // Output: NaN console.log("MAX : " + Math.max()); // Output: -Infinity ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript (function () { var a = (b = 3); })(); console.log("a defined? " + (typeof a !== "undefined")); // Output: true console.log("b defined? " + (typeof b !== "undefined")); // Output: true ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var myObject = { foo: "bar", func: function () { var self = this; console.log("outer func: this.foo = " + this.foo); // Output: this.foo = bar console.log("outer func: self.foo = " + self.foo); // Output: self.foo = bar (function () { console.log("inner func: this.foo = " + this.foo); // Output: this.foo = function foo() {} console.log("inner func: self.foo = " + self.foo); // Output: self.foo = bar })(); }, }; myObject.func(); ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log(0.1 + 0.2); // Output: 0.30000000000000004 console.log(0.1 + 0.2 == 0.3); // Output: false ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript (function () { console.log(1); setTimeout(function () { console.log(2); }, 1000); setTimeout(function () { console.log(3); }, 0); console.log(4); })(); // Output: 1, 4, 3, 2 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var arr1 = "john".split(""); var arr2 = arr1.reverse(); var arr3 = "jones".split(""); arr2.push(arr3); console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1)); //array 1: length=5 last=j,o,n,e,s console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1)); //array 2: length=5 last=j,o,n,e,s ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log(1 + "2" + "2"); // Output: 122 console.log(1 + +"2" + "2"); // Output: 32 console.log(1 + -"1" + "2"); // Output: 02 console.log(+"1" + "1" + "2"); // Output: 112 console.log("A" - "B" + "2"); // Output: NaN2 console.log("A" - "B" + 2); // Output: NaN ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript for (var i = 0; i < 5; i++) { setTimeout(function () { console.log(i); }, i * 1000); } // Output: 145, 5, 5, 5, 5, 5 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript for (var i = 0; i < 5; i++) { (function (x) { setTimeout(function () { console.log(x); }, x * 1000); })(i); } //Output:- 0, 1, 2, 3, 4 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log("0 || 1 = " + (0 || 1)); // Output: 1 console.log("1 || 2 = " + (1 || 2)); // Output: 1 console.log("0 && 1 = " + (0 && 1)); // Output: 0 console.log("1 && 2 = " + (1 && 2)); // Output: 2 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log(false == "0"); // Output: true console.log(false === "0"); // Output: false ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var a = {}, b = { key: "b" }, c = { key: "c" }; a[b] = 123; a[c] = 456; console.log(a[b]); // Output: 456 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log( (function f(n) { return n > 1 ? n * f(n - 1) : n; })(10) ); // Output: 3628800 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript (function (x) { return (function (y) { console.log(x); //1 })(2); })(1); ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var hero = { _name: "John Doe", getSecretIdentity: function () { return this._name; }, }; var stoleSecretIdentity = hero.getSecretIdentity; console.log(stoleSecretIdentity()); // Output: undefined console.log(hero.getSecretIdentity()); // Output: John Doe ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var length = 10; function fn() { console.log(this.length); } var obj = { length: 5, method: function (fn) { fn(); arguments[0](); }, }; obj.method(fn, 1); //Output: 10, 2 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript (function () { try { throw new Error(); } catch (x) { var x = 1, y = 2; console.log(x); } console.log(x); console.log(y); })(); //Output: 1, undefined, 2 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var x = 21; var girl = function () { console.log(x); // Output: undefined var x = 20; }; girl(); ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log(1 < 2 < 3); // Output: true console.log(3 > 2 > 1); // Output: false ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript console.log(typeof typeof 1); // Output: string ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var b = 1; function outer() { var b = 2; function inner() { b++; var b = 3; console.log(b); //3 } inner(); } outer(); ``` ## Q. ***Hoisting example in javascript?*** ```javascript x = 10; console.log(x); var x; // Output: 10 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript const arr = [1, 2]; arr.push(3); // Output: 1, 2, 3 ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var o = new F(); o.constructor === F; ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript let sum = (a, b) => { a + b; }; console.log(sum(10, 20)); // Output: undefined; return keyword is missing ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var arr = ["javascript", "typescript", "es6"]; var searchValue = (value) => { return arr.filter((item) => { return item.indexOf(value) > -1; }); }; console.log(searchValue("script")); ``` ## Q. ***Write the program using fatarrow function?*** ```javascript var a = [1, 2, 3, 4]; function sumUsingFunction(acc, value) { return acc + value; } var sumOfArrayUsingFunc = a.reduce(sumUsingFunc); ``` ## Q. ***Write a program that prints the numbers from 1 to 15. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”?*** ```javascript for (var i = 1; i <= 15; i++) { if (i % 15 == 0) console.log("FizzBuzz"); else if (i % 3 == 0) console.log("Fizz"); else if (i % 5 == 0) console.log("Buzz"); else console.log(i); } ``` Output: ``` 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ``` Solution - 02 ```javascript for (var i = 1; i <= 15; i++) { var f = i % 3 == 0, b = i % 5 == 0; console.log(f ? (b ? "FizzBuzz" : "Fizz") : b ? "Buzz" : i); } ``` ## Q. ***What will be the output of the following code?*** ```javascript var output = (function (x) { delete x; return x; })(0); console.log(output); ``` The code above will output `0` as output. `delete` operator is used to delete a property from an object. Here `x` is not an object it's **local variable**. `delete` operator doesn't affect local variables. ## Q. ***What will be the output of the following code?*** ```javascript var x = 1; var output = (function () { delete x; return x; })(); console.log(output); ``` The code above will output `1` as output. `delete` operator is used to delete a property from an object. Here `x` is not an object it's **global variable** of type `number`. ## Q. ***What will be the output of the following code?*** ```javascript var x = { foo: 1 }; var output = (function () { delete x.foo; return x.foo; })(); console.log(output); ``` The code above will output `undefined` as output. `delete` operator is used to delete a property from an object. Here `x` is an object which has foo as a property and from a self-invoking function, we are deleting the `foo` property of object `x` and after deletion, we are trying to reference deleted property `foo` which result `undefined`. ## Q. ***What will be the output of the following code?*** ```javascript var Employee = { company: "xyz", }; var emp1 = Object.create(Employee); delete emp1.company; console.log(emp1.company); ``` The code above will output `xyz` as output. Here `emp1` object got company as **prototype** property. delete operator doesn't delete prototype property. `emp1` object doesn't have **company** as its own property. you can test it `console.log(emp1.hasOwnProperty('company')); //output : false` However, we can delete company property directly from `Employee` object using `delete Employee.company` or we can also delete from `emp1` object using `__proto__` property `delete emp1.__proto__.company`. ## Q. ***What will be the output of the following code?*** ```javascript var trees = ["xyz", "xxxx", "test", "ryan", "apple"]; delete trees[3]; console.log(trees.length); ``` The code above will output `5` as output. When we used `delete` operator for deleting an array element then, the array length is not affected by this. This holds even if you deleted all elements of an array using `delete` operator. So when delete operator removes an array element that deleted element is no longer present in the array. In place of value at deleted index `undefined x 1` in **chrome** and `undefined` is placed at the index. If you do `console.log(trees)` output `["xyz", "xxxx", "test", undefined × 1, "apple"]` in Chrome and in Firefox `["xyz", "xxxx", "test", undefined, "apple"]`. ## Q. ***What will be the output of the following code?*** ```javascript var bar = true; console.log(bar + 0); console.log(bar + "xyz"); console.log(bar + true); console.log(bar + false); ``` The code above will output `1, "truexyz", 2, 1` as output. Here's a general guideline for the plus operator: - Number + Number -> Addition - Boolean + Number -> Addition - Boolean + Boolean -> Addition - Number + String -> Concatenation - String + Boolean -> Concatenation - String + String -> Concatenation ## Q. ***What will be the output of the following code?*** ```javascript var z = 1, y = (z = typeof y); console.log(y); ``` The code above will print string `"undefined"` as output. According to associativity rule operator with the same precedence are processed based on their associativity property of operator. Here associativity of the assignment operator is `Right to Left` so first `typeof y` will evaluate first which is string `"undefined"` and assigned to `z` and then `y` would be assigned the value of z. The overall sequence will look like that: ```javascript var z; z = 1; var y; z = typeof y; y = z; ``` ## Q. ***What will be the output of the following code?*** ```javascript // NFE (Named Function Expression) var foo = function bar() { return 12; }; typeof bar(); ``` The output will be `Reference Error`. To fix the bug we can try to rewrite the code a little bit: **Sample 1** ```javascript var bar = function () { return 12; }; typeof bar(); ``` or **Sample 2** ```javascript function bar() { return 12; } typeof bar(); ``` The function definition can have only one reference variable as a function name, In **sample 1** `bar` is reference variable which is pointing to `anonymous function` and in **sample 2** we have function statement and `bar` is the function name. ```javascript var foo = function bar() { // foo is visible here // bar is visible here console.log(typeof bar()); // Works here :) }; // foo is visible here // bar is undefined here ``` ## Q. ***What is the output of the following?*** ```javascript bar(); (function abc() { console.log("something"); })(); function bar() { console.log("bar got called"); } ``` The output will be : ``` bar got called something ``` Since the function is called first and defined during parse time the JS engine will try to find any possible parse time definitions and start the execution loop which will mean function is called first even if the definition is post another function. ## Q. ***What will be the output of the following code?*** ```javascript var salary = "1000$"; (function () { console.log("Original salary was " + salary); var salary = "5000$"; console.log("My New Salary " + salary); })(); ``` The code above will output: `undefined, 5000$` because of hoisting. In the code presented above, you might be expecting `salary` to retain it values from outer scope until the point that `salary` was re-declared in the inner scope. But due to `hoisting` salary value was `undefined` instead. To understand it better have a look of the following code, here `salary` variable is hoisted and declared at the top in function scope. When we print its value using `console.log` the result is `undefined`. Afterwards the variable is redeclared and the new value `"5000$"` is assigned to it. ```javascript var salary = "1000$"; (function () { var salary = undefined; console.log("Original salary was " + salary); salary = "5000$"; console.log("My New Salary " + salary); })(); ``` ## Q. ***What would be the output of the following code?*** ```javascript function User(name) { this.name = name || "JsGeeks"; } var person = (new User("xyz")["location"] = "USA"); console.log(person); ``` The output of above code would be `"USA"`. Here `new User("xyz")` creates a brand new object and created property `location` on that and `USA` has been assigned to object property location and that has been referenced by the person. Let say `new User("xyz")` created a object called `foo`. The value `"USA"` will be assigned to `foo["location"]`, but according to [ECMAScript Specification](http://www.ecma-international.org/ecma-262/6.0/#sec-assignment-operators-runtime-semantics-evaluation) , pt 12.14.4 the assignment will itself return the rightmost value: in our case it's `"USA"`. Then it will be assigned to person. To better understand What is going on here, try to execute this code in console, line by line: ```javascript function User(name) { this.name = name || "JsGeeks"; } var person; var foo = new User("xyz"); foo["location"] = "USA"; // the console will show you that the result of this is "USA" ``` ## Q. ***What would be the output of following code?*** ```javascript var strA = "hi there"; var strB = strA; strB = "bye there!"; console.log(strA); ``` The output will `'hi there'` because we're dealing with strings here. Strings are passed by value, that is, copied. ## Q. ***What would be the output of following code?*** ```javascript var objA = { prop1: 42 }; var objB = objA; objB.prop1 = 90; console.log(objA); ``` The output will `{prop1: 90}` because we're dealing with objects here. Objects are passed by reference, that is, `objA` and `objB` point to the same object in memory. ## Q. ***What would be the output of following code?*** ```javascript var objA = { prop1: 42 }; var objB = objA; objB = {}; console.log(objA); ``` The output will `{prop1: 42}`. When we assign `objA` to `objB`, the `objB` variable will point to the same object as the `objB` variable. However, when we reassign `objB` to an empty object, we simply change where `objB` variable references to. This doesn't affect where `objA` variable references to. ## Q. ***What would be the output of following code?*** ```javascript var arrA = [0, 1, 2, 3, 4, 5]; var arrB = arrA; arrB[0] = 42; console.log(arrA); ``` The output will be `[42,1,2,3,4,5]`. Arrays are object in JavaScript and they are passed and assigned by reference. This is why both `arrA` and `arrB` point to the same array `[0,1,2,3,4,5]`. That's why changing the first element of the `arrB` will also modify `arrA`: it's the same array in the memory. ## Q. ***What would be the output of following code?*** ```javascript var arrA = [0, 1, 2, 3, 4, 5]; var arrB = arrA.slice(); arrB[0] = 42; console.log(arrA); ``` The output will be `[0,1,2,3,4,5]`. The `slice` function copies all the elements of the array returning the new array. That's why `arrA` and `arrB` reference two completely different arrays. ## Q. ***What would be the output of following code?*** ```javascript var arrA = [ { prop1: "value of array A!!" }, { someProp: "also value of array A!" }, 3, 4, 5, ]; var arrB = arrA; arrB[0].prop1 = 42; console.log(arrA); ``` The output will be `[{prop1: 42}, {someProp: "also value of array A!"}, 3,4,5]`. Arrays are object in JS, so both varaibles arrA and arrB point to the same array. Changing `arrB[0]` is the same as changing `arrA[0]` ## Q. ***What would be the output of following code?*** ```javascript var arrA = [ { prop1: "value of array A!!" }, { someProp: "also value of array A!" }, 3, 4, 5, ]; var arrB = arrA.slice(); arrB[0].prop1 = 42; arrB[3] = 20; console.log(arrA); ``` The output will be `[{prop1: 42}, {someProp: "also value of array A!"}, 3,4,5]`. The `slice` function copies all the elements of the array returning the new array. However, it doesn't do deep copying. Instead it does shallow copying. You can imagine slice implemented like this: ```javascript function slice(arr) { var result = []; for (i = 0; i < arr.length; i++) { result.push(arr[i]); } return result; } ``` Look at the line with `result.push(arr[i])`. If `arr[i]` happens to be a number or string, it will be passed by value, in other words, copied. If `arr[i]` is an object, it will be passed by reference. In case of our array `arr[0]` is an object `{prop1: "value of array A!!"}`. Only the reference to this object will be copied. This effectively means that arrays arrA and arrB share first two elements. This is why changing the property of `arrB[0]` in `arrB` will also change the `arrA[0]`. ## Q. ***console.log(employeeId);*** 1. Some Value 2. Undefined 3. Type Error 4. ReferenceError: employeeId is not defined _Answer:_ 4) ReferenceError: employeeId is not defined ## Q. ***What would be the output of following code?*** ```javascript console.log(employeeId); var employeeId = "19000"; ``` 1. Some Value 2. undefined 3. Type Error 4. ReferenceError: employeeId is not defined _Answer:_ 2) undefined ## Q. ***What would be the output of following code?*** ```javascript var employeeId = "1234abe"; (function () { console.log(employeeId); var employeeId = "122345"; })(); ``` 1. '122345' 2. undefined 3. Type Error 4. ReferenceError: employeeId is not defined _Answer:_ 2) undefined ## Q. ***What would be the output of following code?*** ```javascript var employeeId = "1234abe"; (function () { console.log(employeeId); var employeeId = "122345"; (function () { var employeeId = "abc1234"; })(); })(); ``` 1. '122345' 2. undefined 3. '1234abe' 4. ReferenceError: employeeId is not defined _Answer:_ 2) undefined ## Q. ***What would be the output of following code?*** ```javascript (function () { console.log(typeof displayFunc); var displayFunc = function () { console.log("Hi I am inside displayFunc"); }; })(); ``` 1. undefined 2. function 3. 'Hi I am inside displayFunc' 4. ReferenceError: displayFunc is not defined _Answer:_ 1) undefined ## Q. ***What would be the output of following code?*** ```javascript var employeeId = "abc123"; function foo() { employeeId = "123bcd"; return; } foo(); console.log(employeeId); ``` 1. undefined 2. '123bcd' 3. 'abc123' 4. ReferenceError: employeeId is not defined _Answer:_ 2) '123bcd' ## Q. ***What would be the output of following code?*** ```javascript var employeeId = "abc123"; function foo() { employeeId = "123bcd"; return; function employeeId() {} } foo(); console.log(employeeId); ``` 1. undefined 2. '123bcd' 3. 'abc123' 4. ReferenceError: employeeId is not defined _Answer:_ 3) 'abc123' ## Q. ***What would be the output of following code?*** ```javascript var employeeId = "abc123"; function foo() { employeeId(); return; function employeeId() { console.log(typeof employeeId); } } foo(); ``` 1. undefined 2. function 3. string 4. ReferenceError: employeeId is not defined _Answer:_ 2) 'function' ## Q. ***What would be the output of following code?*** ```javascript function foo() { employeeId(); var product = "Car"; return; function employeeId() { console.log(product); } } foo(); ``` 1. undefined 2. Type Error 3. 'Car' 4. ReferenceError: product is not defined _Answer:_ 1) undefined ## Q. ***What would be the output of following code?*** ```javascript (function foo() { bar(); function bar() { abc(); console.log(typeof abc); } function abc() { console.log(typeof bar); } })(); ``` 1. undefined undefined 2. Type Error 3. function function 4. ReferenceError: bar is not defined _Answer:_ 3) function function ## Q. ***What would be the output of following code?*** ```javascript (function () { "use strict"; var person = { name: "John", }; person.salary = "10000$"; person["country"] = "USA"; Object.defineProperty(person, "phoneNo", { value: "8888888888", enumerable: true, }); console.log(Object.keys(person)); })(); ``` 1. Type Error 2. undefined 3. ["name", "salary", "country", "phoneNo"] 4. ["name", "salary", "country"] _Answer:_ 3) ["name", "salary", "country", "phoneNo"] ## Q. ***What would be the output of following code?*** ```javascript (function () { "use strict"; var person = { name: "John", }; person.salary = "10000$"; person["country"] = "USA"; Object.defineProperty(person, "phoneNo", { value: "8888888888", enumerable: false, }); console.log(Object.keys(person)); })(); ``` 1. Type Error 2. undefined 3. ["name", "salary", "country", "phoneNo"] 4. ["name", "salary", "country"] _Answer:_ 4) ["name", "salary", "country"] ## Q. ***What would be the output of following code?*** ```javascript (function () { var objA = { foo: "foo", bar: "bar", }; var objB = { foo: "foo", bar: "bar", }; console.log(objA == objB); console.log(objA === objB); })(); ``` 1. false true 2. false false 3. true false 4. true true _Answer:_ 2) false false ## Q. ***What would be the output of following code?*** ```javascript (function () { var objA = new Object({ foo: "foo" }); var objB = new Object({ foo: "foo" }); console.log(objA == objB); console.log(objA === objB); })(); ``` 1. false true 2. false false 3. true false 4. true true _Answer:_ 2) false false ## Q. ***What would be the output of following code?*** ```javascript (function () { var objA = Object.create({ foo: "foo", }); var objB = Object.create({ foo: "foo", }); console.log(objA == objB); console.log(objA === objB); })(); ``` 1. false true 2. false false 3. true false 4. true true _Answer:_ 2) false false ## Q. ***What would be the output of following code?*** ```javascript (function () { var objA = Object.create({ foo: "foo", }); var objB = Object.create(objA); console.log(objA == objB); console.log(objA === objB); })(); ``` 1. false true 2. false false 3. true false 4. true true _Answer:_ 2) false false ## Q. ***What would be the output of following code?*** ```javascript (function () { var objA = Object.create({ foo: "foo", }); var objB = Object.create(objA); console.log(objA.toString() == objB.toString()); console.log(objA.toString() === objB.toString()); })(); ``` 1. false true 2. false false 3. true false 4. true true _Answer:_ 4) true true ## Q. ***What would be the output of following code?*** ```javascript (function () { var objA = Object.create({ foo: "foo", }); var objB = objA; console.log(objA == objB); console.log(objA === objB); console.log(objA.toString() == objB.toString()); console.log(objA.toString() === objB.toString()); })(); ``` 1. true true true false 2. true false true true 3. true true true true 4. true true false false _Answer:_ 3) true true true true ## Q. ***What would be the output of following code?*** ```javascript (function () { var objA = Object.create({ foo: "foo", }); var objB = objA; objB.foo = "bar"; console.log(objA.foo); console.log(objB.foo); })(); ``` 1. foo bar 2. bar bar 3. foo foo 4. bar foo _Answer:_ 2) bar bar ## Q. ***What would be the output of following code?*** ```javascript (function () { var objA = Object.create({ foo: "foo", }); var objB = objA; objB.foo = "bar"; delete objA.foo; console.log(objA.foo); console.log(objB.foo); })(); ``` 1. foo bar 2. bar bar 3. foo foo 4. bar foo _Answer:_ 3) foo foo ## Q. ***What would be the output of following code?*** ```javascript (function () { var objA = { foo: "foo", }; var objB = objA; objB.foo = "bar"; delete objA.foo; console.log(objA.foo); console.log(objB.foo); })(); ``` 1. foo bar 2. undefined undefined 3. foo foo 4. undefined bar _Answer:_ 2) undefined undefined ## Q. ***What would be the output of following code?*** ```javascript (function () { var array = new Array("100"); console.log(array); console.log(array.length); })(); ``` 1. undefined undefined 2. [undefined × 100] 100 3. ["100"] 1 4. ReferenceError: array is not defined _Answer:_ 3) ["100"] 1 ## Q. ***What would be the output of following code?*** ```javascript (function () { var array1 = []; var array2 = new Array(100); var array3 = new Array(["1", 2, "3", 4, 5.6]); console.log(array1); console.log(array2); console.log(array3); console.log(array3.length); })(); ``` 1. [] [] [Array[5]] 1 2. [] [undefined × 100] Array[5] 1 3. [] [] ['1',2,'3',4,5.6] 5 4. [] [] [Array[5]] 5 _Answer:_ 1) [] [] [Array[5]] 1 ## Q. ***What would be the output of following code?*** ```javascript (function () { var array = new Array("a", "b", "c", "d", "e"); array[10] = "f"; delete array[10]; console.log(array.length); })(); ``` 1. 11 2. 5 3. 6 4. undefined _Answer:_ 1) 11 ## Q. ***What would be the output of following code?*** ```javascript (function () { var animal = ["cow", "horse"]; animal.push("cat"); animal.push("dog", "rat", "goat"); console.log(animal.length); })(); ``` 1. 4 2. 5 3. 6 4. undefined _Answer:_ 3) 6 ## Q. ***What would be the output of following code?*** ```javascript (function () { var animal = ["cow", "horse"]; animal.push("cat"); animal.unshift("dog", "rat", "goat"); console.log(animal); })(); ``` 1. [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ] 2. [ 'cow', 'horse', 'cat', 'dog', 'rat', 'goat' ] 3. Type Error 4. undefined _Answer:_ 1) [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ] ## Q. ***What would be the output of following code?*** ```javascript (function () { var array = [1, 2, 3, 4, 5]; console.log(array.indexOf(2)); console.log([{ name: "John" }, { name: "John" }].indexOf({ name: "John" })); console.log([[1], [2], [3], [4]].indexOf([3])); console.log("abcdefgh".indexOf("e")); })(); ``` 1. 1 -1 -1 4 2. 1 0 -1 4 3. 1 -1 -1 -1 4. 1 undefined -1 4 _Answer:_ 1) 1 -1 -1 4 ## Q. ***What would be the output of following code?*** ```javascript (function () { var array = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]; console.log(array.indexOf(2)); console.log(array.indexOf(2, 3)); console.log(array.indexOf(2, 10)); })(); ``` 1. 1 -1 -1 2. 1 6 -1 3. 1 1 -1 4. 1 undefined undefined _Answer:_ 2) 1 6 -1 ## Q. ***What would be the output of following code?*** ```javascript (function () { var numbers = [2, 3, 4, 8, 9, 11, 13, 12, 16]; var even = numbers.filter(function (element, index) { return element % 2 === 0; }); console.log(even); var containsDivisibleby3 = numbers.some(function (element, index) { return element % 3 === 0; }); console.log(containsDivisibleby3); })(); ``` 1. [ 2, 4, 8, 12, 16 ] [ 0, 3, 0, 0, 9, 0, 12] 2. [ 2, 4, 8, 12, 16 ] [ 3, 9, 12] 3. [ 2, 4, 8, 12, 16 ] true 4. [ 2, 4, 8, 12, 16 ] false _Answer:_ 3) [ 2, 4, 8, 12, 16 ] true ## Q. ***What would be the output of following code?*** ```javascript (function () { var containers = [2, 0, false, "", "12", true]; var containers = containers.filter(Boolean); console.log(containers); var containers = containers.filter(Number); console.log(containers); var containers = containers.filter(String); console.log(containers); var containers = containers.filter(Object); console.log(containers); })(); ``` 1. [ 2, '12', true ] [ 2, '12', true ] [ 2, '12', true ] [ 2, '12', true ] 2. [false, true] [ 2 ] ['12'] [ ] 3. [2,0,false,"", '12', true] [2,0,false,"", '12', true] [2,0,false,"", '12', true] [2,0,false,"", '12', true] 4. [ 2, '12', true ] [ 2, '12', true, false ] [ 2, '12', true,false ] [ 2, '12', true,false] _Answer:_ 1) [ 2, '12', true ] [ 2, '12', true ] [ 2, '12', true ] [ 2, '12', true ] ## Q. ***What would be the output of following code?*** ```javascript (function () { var list = ["foo", "bar", "john", "ritz"]; console.log(list.slice(1)); console.log(list.slice(1, 3)); console.log(list.slice()); console.log(list.slice(2, 2)); console.log(list); })(); ``` 1. [ 'bar', 'john', 'ritz' ] [ 'bar', 'john' ] [ 'foo', 'bar', 'john', 'ritz' ] [] [ 'foo', 'bar', 'john', 'ritz' ] 2. [ 'bar', 'john', 'ritz' ] [ 'bar', 'john','ritz ] [ 'foo', 'bar', 'john', 'ritz' ] [] [ 'foo', 'bar', 'john', 'ritz' ] 3. [ 'john', 'ritz' ] [ 'bar', 'john' ] [ 'foo', 'bar', 'john', 'ritz' ] [] [ 'foo', 'bar', 'john', 'ritz' ] 4. [ 'foo' ] [ 'bar', 'john' ] [ 'foo', 'bar', 'john', 'ritz' ] [] [ 'foo', 'bar', 'john', 'ritz' ] _Answer:_ 1) [ 'bar', 'john', 'ritz' ] [ 'bar', 'john' ] [ 'foo', 'bar', 'john', 'ritz' ] [] [ 'foo', 'bar', 'john', 'ritz' ] ## Q. ***What would be the output of following code?*** ```javascript (function () { var list = ["foo", "bar", "john"]; console.log(list.splice(1)); console.log(list.splice(1, 2)); console.log(list); })(); ``` 1. [ 'bar', 'john' ] [] [ 'foo' ] 2. [ 'bar', 'john' ] [] [ 'bar', 'john' ] 3. [ 'bar', 'john' ] [ 'bar', 'john' ] [ 'bar', 'john' ] 4. [ 'bar', 'john' ] [] [] _Answer:_ 1. [ 'bar', 'john' ] [] [ 'foo' ] ## Q. ***What would be the output of following code?*** ```javascript (function () { var arrayNumb = [2, 8, 15, 16, 23, 42]; arrayNumb.sort(); console.log(arrayNumb); })(); ``` 1. [2, 8, 15, 16, 23, 42] 2. [42, 23, 26, 15, 8, 2] 3. [ 15, 16, 2, 23, 42, 8 ] 4. [ 2, 8, 15, 16, 23, 42 ] _Answer:_ 3. [ 15, 16, 2, 23, 42, 8 ] ## Q. ***What would be the output of following code?*** ```javascript function funcA() { console.log("funcA ", this); (function innerFuncA1() { console.log("innerFunc1", this); (function innerFunA11() { console.log("innerFunA11", this); })(); })(); } console.log(funcA()); ``` 1. funcA Window {...} innerFunc1 Window {...} innerFunA11 Window {...} 2. undefined 3. Type Error 4. ReferenceError: this is not defined _Answer:_ 1) ## Q. ***What would be the output of following code?*** ```javascript var obj = { message: "Hello", innerMessage: !(function () { console.log(this.message); })(), }; console.log(obj.innerMessage); ``` 1. ReferenceError: this.message is not defined 2. undefined 3. Type Error 4. undefined true _Answer:_ 4) undefined true ## Q. ***What would be the output of following code?*** ```javascript var obj = { message: "Hello", innerMessage: function () { return this.message; }, }; console.log(obj.innerMessage()); ``` 1. Hello 2. undefined 3. Type Error 4. ReferenceError: this.message is not defined _Answer:_ 1) Hello ## Q. ***What would be the output of following code?*** ```javascript var obj = { message: "Hello", innerMessage: function () { (function () { console.log(this.message); })(); }, }; console.log(obj.innerMessage()); ``` 1. Type Error 2. Hello 3. undefined 4. ReferenceError: this.message is not defined _Answer:_ 3) undefined ## Q. ***What would be the output of following code?*** ```javascript var obj = { message: "Hello", innerMessage: function () { var self = this; (function () { console.log(self.message); })(); }, }; console.log(obj.innerMessage()); ``` 1. Type Error 2. 'Hello' 3. undefined 4. ReferenceError: self.message is not defined _Answer:_ 2) 'Hello' ## Q. ***What would be the output of following code?*** ```javascript function myFunc() { console.log(this.message); } myFunc.message = "Hi John"; console.log(myFunc()); ``` 1. Type Error 2. 'Hi John' 3. undefined 4. ReferenceError: this.message is not defined _Answer:_ 3) undefined ## Q. ***What would be the output of following code?*** ```javascript function myFunc() { console.log(myFunc.message); } myFunc.message = "Hi John"; console.log(myFunc()); ``` 1. Type Error 2. 'Hi John' 3. undefined 4. ReferenceError: this.message is not defined _Answer:_ 2) 'Hi John' ## Q. ***What would be the output of following code?*** ```javascript function myFunc() { myFunc.message = "Hi John"; console.log(myFunc.message); } console.log(myFunc()); ``` 1. Type Error 2. 'Hi John' 3. undefined 4. ReferenceError: this.message is not defined _Answer:_ 2) 'Hi John' ## Q. ***What would be the output of following code?*** ```javascript function myFunc(param1, param2) { console.log(myFunc.length); } console.log(myFunc()); console.log(myFunc("a", "b")); console.log(myFunc("a", "b", "c", "d")); ``` 1. 2 2 2 2. 0 2 4 3. undefined 4. ReferenceError _Answer:_ a) 2 2 2 ## Q. ***What would be the output of following code?*** ```javascript function myFunc() { console.log(arguments.length); } console.log(myFunc()); console.log(myFunc("a", "b")); console.log(myFunc("a", "b", "c", "d")); ``` 1. 2 2 2 2. 0 2 4 3. undefined 4. ReferenceError _Answer:_ 2) 0 2 4 ## Q. ***What would be the output of following code?*** ```javascript function Person(name, age) { this.name = name || "John"; this.age = age || 24; this.displayName = function () { console.log(this.name); }; } Person.name = "John"; Person.displayName = function () { console.log(this.name); }; var person1 = new Person("John"); person1.displayName(); Person.displayName(); ``` 1. John Person 2. John John 3. John undefined 4. John John _Answer:_ 1) John Person ## Q. ***What would be the output of following code?*** ```javascript function passWordMngr() { var password = "12345678"; this.userName = "John"; return { pwd: password, }; } // Block End var userInfo = passWordMngr(); console.log(userInfo.pwd); console.log(userInfo.userName); ``` 1. 12345678 Window 2. 12345678 John 3. 12345678 undefined 4. undefined undefined _Answer:_ 3) 12345678 undefined ## Q. ***What would be the output of following code?*** ```javascript var employeeId = "aq123"; function Employee() { this.employeeId = "bq1uy"; } console.log(Employee.employeeId); ``` 1. Reference Error 2. aq123 3. bq1uy 4. undefined _Answer:_ 4) undefined ## Q. ***What would be the output of following code?*** ```javascript var employeeId = "aq123"; function Employee() { this.employeeId = "bq1uy"; } console.log(new Employee().employeeId); Employee.prototype.employeeId = "kj182"; Employee.prototype.JobId = "1BJKSJ"; console.log(new Employee().JobId); console.log(new Employee().employeeId); ``` 1. bq1uy 1BJKSJ bq1uy undefined 2. bq1uy 1BJKSJ bq1uy 3. bq1uy 1BJKSJ kj182 4. undefined 1BJKSJ kj182 _Answer:_ 2) bq1uy 1BJKSJ bq1uy ## Q. ***What would be the output of following code?*** ```javascript var employeeId = "aq123"; (function Employee() { try { throw "foo123"; } catch (employeeId) { console.log(employeeId); } console.log(employeeId); })(); ``` 1. foo123 aq123 2. foo123 foo123 3. aq123 aq123 4. foo123 undefined _Answer:_ 1) foo123 aq123 ## Q. ***What would be the output of following code?*** ```javascript (function () { var greet = "Hello World"; var toGreet = [].filter.call(greet, function (element, index) { return index > 5; }); console.log(toGreet); })(); ``` 1. Hello World 2. undefined 3. World 4. [ 'W', 'o', 'r', 'l', 'd' ] _Answer:_ 4) [ 'W', 'o', 'r', 'l', 'd' ] ## Q. ***What would be the output of following code?*** ```javascript (function () { var fooAccount = { name: "John", amount: 4000, deductAmount: function (amount) { this.amount -= amount; return "Total amount left in account: " + this.amount; }, }; var barAccount = { name: "John", amount: 6000, }; var withdrawAmountBy = function (totalAmount) { return fooAccount.deductAmount.bind(barAccount, totalAmount); }; console.log(withdrawAmountBy(400)()); console.log(withdrawAmountBy(300)()); })(); ``` 1. Total amount left in account: 5600 Total amount left in account: 5300 2. undefined undefined 3. Total amount left in account: 3600 Total amount left in account: 3300 4. Total amount left in account: 5600 Total amount left in account: 5600 _Answer:_ 1) Total amount left in account: 5600 Total amount left in account: 5300 ## Q. ***What would be the output of following code?*** ```javascript (function () { var fooAccount = { name: "John", amount: 4000, deductAmount: function (amount) { this.amount -= amount; return this.amount; }, }; var barAccount = { name: "John", amount: 6000, }; var withdrawAmountBy = function (totalAmount) { return fooAccount.deductAmount.apply(barAccount, [totalAmount]); }; console.log(withdrawAmountBy(400)); console.log(withdrawAmountBy(300)); console.log(withdrawAmountBy(200)); })(); ``` 1. 5600 5300 5100 2. 3600 3300 3100 3. 5600 3300 5100 4. undefined undefined undefined _Answer:_ 1) 5600 5300 5100 ## Q. ***What would be the output of following code?*** ```javascript (function () { var fooAccount = { name: "John", amount: 6000, deductAmount: function (amount) { this.amount -= amount; return this.amount; }, }; var barAccount = { name: "John", amount: 4000, }; var withdrawAmountBy = function (totalAmount) { return fooAccount.deductAmount.call(barAccount, totalAmount); }; console.log(withdrawAmountBy(400)); console.log(withdrawAmountBy(300)); console.log(withdrawAmountBy(200)); })(); ``` 1. 5600 5300 5100 2. 3600 3300 3100 3. 5600 3300 5100 4. undefined undefined undefined _Answer:_ 2) 3600 3300 3100 ## Q. ***What would be the output of following code?*** ```javascript (function greetNewCustomer() { console.log("Hello " + this.name); }.bind({ name: "John", })()); ``` 1. Hello John 2. Reference Error 3. Window 4. undefined _Answer:_ 1) Hello John ## Q. ***What would be the output of following code?*** ```javascript function getDataFromServer(apiUrl) { var name = "John"; return { then: function (fn) { fn(name); }, }; } getDataFromServer("www.google.com").then(function (name) { console.log(name); }); ``` 1. John 2. undefined 3. Reference Error 4. fn is not defined _Answer:_ 1) John ## Q. ***What would be the output of following code?*** ```javascript (function () { var arrayNumb = [2, 8, 15, 16, 23, 42]; Array.prototype.sort = function (a, b) { return a - b; }; arrayNumb.sort(); console.log(arrayNumb); })(); (function () { var numberArray = [2, 8, 15, 16, 23, 42]; numberArray.sort(function (a, b) { if (a == b) { return 0; } else { return a < b ? -1 : 1; } }); console.log(numberArray); })(); (function () { var numberArray = [2, 8, 15, 16, 23, 42]; numberArray.sort(function (a, b) { return a - b; }); console.log(numberArray); })(); ``` 1. [ 2, 8, 15, 16, 23, 42 ] [ 2, 8, 15, 16, 23, 42 ] [ 2, 8, 15, 16, 23, 42 ] 2. undefined undefined undefined 3. [42, 23, 16, 15, 8, 2] [42, 23, 16, 15, 8, 2] [42, 23, 16, 15, 8, 2] 4. Reference Error _Answer:_ 1) [ 2, 8, 15, 16, 23, 42 ] [ 2, 8, 15, 16, 23, 42 ] [ 2, 8, 15, 16, 23, 42 ] ## Q. ***What would be the output of following code?*** ```javascript (function () { function sayHello() { var name = "Hi John"; return; { fullName: name; } } console.log(sayHello().fullName); })(); ``` 1. Hi John 2. undefined 3. Reference Error 4. Uncaught TypeError: Cannot read property 'fullName' of undefined _Answer:_ 4) Uncaught TypeError: Cannot read property 'fullName' of undefined ## Q. ***What would be the output of following code?*** ```javascript function getNumber() { return 2, 4, 5; } var numb = getNumber(); console.log(numb); ``` 1. 5 2. undefined 3. 2 4. (2,4,5) _Answer:_ 1) 5 ## Q. ***What would be the output of following code?*** ```javascript function getNumber() { return; } var numb = getNumber(); console.log(numb); ``` 1. null 2. undefined 3. "" 4. 0 _Answer:_ 2) undefined ## Q. ***What would be the output of following code?*** ```javascript function mul(x) { return function (y) { return [ x * y, function (z) { return x * y + z; }, ]; }; } console.log(mul(2)(3)[0]); console.log(mul(2)(3)[1](4)); ``` 1. 6, 10 2. undefined undefined 3. Reference Error 4. 10, 6 _Answer:_ 1) 6, 10 ## Q. ***What would be the output of following code?*** ```javascript function mul(x) { return function (y) { return { result: x * y, sum: function (z) { return x * y + z; }, }; }; } console.log(mul(2)(3).result); console.log(mul(2)(3).sum(4)); ``` 1. 6, 10 2. undefined undefined 3. Reference Error 4. 10, 6 _Answer:_ 1) 6, 10 ## Q. ***What would be the output of following code?*** ```javascript function mul(x) { return function (y) { return function (z) { return function (w) { return function (p) { return x * y * z * w * p; }; }; }; }; } console.log(mul(2)(3)(4)(5)(6)); ``` 1. 720 2. undefined 3. Reference Error 4. Type Error _Answer:_ 1) 720 ## Q. ***What is the value of `foo`?*** ```javascript var foo = 10 + "20"; ``` _Answer:_ `'1020'`, because of type coercion from Number to String ## Q. ***How would you make this work?*** ```javascript add(2, 5); // 7 add(2)(5); // 7 ``` _Answer:_ A general solution for any number of parameters ```javascript "use strict"; let sum = (arr) => arr.reduce((a, b) => a + b); let addGenerator = (numArgs, prevArgs) => { return function () { let totalArgs = prevArgs.concat(Array.from(arguments)); if (totalArgs.length === numArgs) { return sum(totalArgs); } return addGenerator(numArgs, totalArgs); }; }; let add = addGenerator(2, []); add(2, 5); // 7 add(2)(5); // 7 add()(2, 5); // 7 add()(2)(5); // 7 add()()(2)(5); // 7 ``` ## Q. ***What value is returned from the following statement?*** ```javascript "i'm a lasagna hog".split("").reverse().join(""); ``` _Answer:_ It's actually a reverse method for a string - `'goh angasal a m\'i'` ## Q. ***What is the value of `window.foo`?*** ```javascript window.foo || (window.foo = "bar"); ``` _Answer:_ Always `'bar'` ## Q. ***What is the outcome of the two alerts below?*** ```javascript var foo = "Hello"; (function () { var bar = " World"; alert(foo + bar); })(); alert(foo + bar); ``` _Answer:_ - First: `Hello World` - Second: Throws an exception, `ReferenceError: bar is not defined` ## Q. ***What is the value of `foo.length`?*** ```javascript var foo = []; foo.push(1); foo.push(2); ``` _Answer:_ `.push` is mutable - `2` ## Q. ***What is the value of `foo.x`?*** ```javascript var foo = { n: 1 }; var bar = foo; foo.x = foo = { n: 2 }; ``` _Answer:_ `undefined`. Rather, `bar.x` is `{n: 2}`. `foo.x = foo = {n: 2}` is the same as `foo.x = (foo = {n: 2})`. It is because a left term is first referenced and then a right term is evaluated when an assignment is performed in JavaScript. When `foo.x` is referenced, it refers to an original object, `{n: 1}`. So, when the result of the right term, `{n: 2}`, is evaluated, it will assigned to the original object, which is at the moment referenced by `bar`. ## Q. ***What does the following code print?*** ```javascript console.log("one"); setTimeout(function () { console.log("two"); }, 0); console.log("three"); ``` _Answer:_ `one`, `three` and `two`. It's because `console.log('two');` will be invoked in the next event loop. ## Q. ***What would be the result of 1+2+'3'?*** The output is going to be `33`. Since `1` and `2` are numeric values, the result of first two digits is going to be a numeric value `3`. The next digit is a string type value because of that the addition of numeric value `3` and string type value `3` is just going to be a concatenation value `33`. ## Q. ***Write a script that returns the number of occurrences of character given a string as input?*** ```javascript function countCharacters(str) { return str .replace(/ /g, "") .toLowerCase() .split("") .reduce((arr, character) => { if (character in arr) { arr[character]++; } else { arr[character] = 1; } return arr; }, {}); } console.log(countCharacters("the brown fox jumps over the lazy dog")); ``` ## Q. ***What is the value of `foo`?*** ```javascript var foo = 10 + "20"; ``` _Answer:_ `'1020'`, because of type coercion from Number to String ## Q. ***How would you make this work?*** ```javascript add(2, 5); // 7 add(2)(5); // 7 ``` _Answer:_ A general solution for any number of parameters ```js "use strict"; let sum = (arr) => arr.reduce((a, b) => a + b); let addGenerator = (numArgs, prevArgs) => { return function () { let totalArgs = prevArgs.concat(Array.from(arguments)); if (totalArgs.length === numArgs) { return sum(totalArgs); } return addGenerator(numArgs, totalArgs); }; }; let add = addGenerator(2, []); add(2, 5); // 7 add(2)(5); // 7 add()(2, 5); // 7 add()(2)(5); // 7 add()()(2)(5); // 7 ``` ## Q. ***What value is returned from the following statement?*** ```javascript "i'm a lasagna hog".split("").reverse().join(""); ``` _Answer:_ It's actually a reverse method for a string - `'goh angasal a m\'i'` ## Q. ***What is the value of `window.foo`?*** ```javascript window.foo || (window.foo = "bar"); ``` _Answer:_ Always `'bar'` ## Q. ***What is the outcome of the two alerts below?*** ```javascript var foo = "Hello"; (function () { var bar = " World"; alert(foo + bar); })(); alert(foo + bar); ``` _Answer:_ - First: `Hello World` - Second: Throws an exception, `ReferenceError: bar is not defined` ## Q. ***What is the value of `foo.length`?*** ```javascript var foo = []; foo.push(1); foo.push(2); ``` _Answer:_ `.push` is mutable - `2` ## Q. ***What is the value of `foo.x`?*** ```javascript var foo = { n: 1 }; var bar = foo; foo.x = foo = { n: 2 }; ``` _Answer:_ `undefined`. Rather, `bar.x` is `{n: 2}`. `foo.x = foo = {n: 2}` is the same as `foo.x = (foo = {n: 2})`. It is because a left term is first referenced and then a right term is evaluated when an assignment is performed in JavaScript. When `foo.x` is referenced, it refers to an original object, `{n: 1}`. So, when the result of the right term, `{n: 2}`, is evaluated, it will assigned to the original object, which is at the moment referenced by `bar`. ## Q. ***What does the following code print?*** ```javascript console.log("one"); setTimeout(function () { console.log("two"); }, 0); console.log("three"); ``` _Answer:_ `one`, `three` and `two`. It's because `console.log('two');` will be invoked in the next event loop. ## Q. ***For which value of x the results of the following statements are not the same?*** ```javascript // if( x <= 100 ) {...} if( !(x > 100) ) {...} ``` _Answer:_ `NaN <= 100` is `false` and `NaN > 100` is also false, so if the value of `x` is `NaN`, the statements are not the same. The same holds true for any value of x that being converted to Number, returns NaN, e.g.: `undefined`, `[1,2,5]`, `{a:22}`, etc. ## Q. ***What is g value?*** ```javascript f = g = 0; (function () { try { f = function () { return f(); } && f(); } catch (e) { return g++ && f(); } finally { return ++g; } function f() { g += 5; return 0; } })(); ``` ## Q. ***What will be the output?*** ```javascript function b(b) { return this.b && b(b); } b(b.bind(b)); ``` ## Q. ***What will be the output?*** ```javascript c = (c) => { return this.c && c(c); }; c(c.bind(c)); ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var g = 0; g = 1 && g++; console.log(g); ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript !function(){}() function(){}() true && function(){}() (function(){})() function(){} !function(){} ``` ## Q. ***What will expression return? ```javascript var a = (b = true), c = (a) => a; (function a(a = (c(b).a = c = () => a)) { return a(); })(); ``` ## Q. ***Predict the output of the following JavaScript code?*** ```javascript var a = true; (a = function () { return a; })(); ``` ## Q. ***What will be the output?*** ```javascript var v = 0; try { throw (v = (function (c) { throw (v = function (a) { return v; }); })()); } catch (e) { console.log(e()()); } ``` ## Q. ***What will the following code output?*** ```javascript const arr = [10, 12, 15, 21]; for (var i = 0; i < arr.length; i++) { setTimeout(function () { console.log("Index: " + i + ", element: " + arr[i]); }, 3000); } ``` ## Q. ***What will be the output of the following code?*** ```javascript var output = (function (x) { delete x; return x; })(0); console.log(output); ``` ## Q. ***What will be the output of the following code?*** ```javascript var Employee = { company: "xyz", }; var emp1 = Object.create(Employee); delete emp1.company; console.log(emp1.company); ``` ## Q. ***Make this work: ```javascript duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5] ``` ```javascript function duplicate(arr) { return arr.concat(arr); } duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5] ``` ## Q. ***Fix the bug using ES5 only?*** ```javascript var arr = [10, 32, 65, 2]; for (var i = 0; i < arr.length; i++) { setTimeout(function () { console.log("The index of this number is: " + i); }, 3000); } ``` For ES6, you can just replace `var i` with `let i`. For ES5, you need to create a function scope like here: ```javascript var arr = [10, 32, 65, 2]; for (var i = 0; i < arr.length; i++) { setTimeout( (function (j) { return function () { console.log("The index of this number is: " + j); }; })(i), 3000 ); } ``` ## Q. ***What will be the output of the following code?*** ```javascript console.log(eval("10 + 10")); // 20 console.log(eval("5 + 5" + 10)); // 515 console.log(eval("5 + 5 + 5" + 10)); // 520 console.log(eval(10 + "5 + 5")); // 110 console.log(eval(10 + "5 + 5 + 5")); // 115 ``` ## Q. ***What will be the output of the following code?*** ```javascript var x = 10; var y = 20; var a = eval("x * y") + "
When you change one object, you change all of them.
## Q. ***What is the output?***
```javascript
let a = 3;
let b = new Number(3);
let c = 3;
console.log(a == b);
console.log(a === b);
console.log(b === c);
```
- A: `true` `false` `true`
- B: `false` `false` `true`
- C: `true` `false` `false`
- D: `false` `true` `true`
**Answer: C**
`new Number()` is a built-in function constructor. Although it looks like a number, it's not really a number: it has a bunch of extra features and is an object.
When we use the `==` operator, it only checks whether it has the same _value_. They both have the value of `3`, so it returns `true`.
However, when we use the `===` operator, both value _and_ type should be the same. It's not: `new Number()` is not a number, it's an **object**. Both return `false.`
## Q. ***What is the output?***
```javascript
class Chameleon {
static colorChange(newColor) {
this.newColor = newColor;
return this.newColor;
}
constructor({ newColor = "green" } = {}) {
this.newColor = newColor;
}
}
const freddie = new Chameleon({ newColor: "purple" });
console.log(freddie.colorChange("orange"));
```
- A: `orange`
- B: `purple`
- C: `green`
- D: `TypeError`
**Answer: D**
The `colorChange` function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be passed down to any children. Since `freddie` is a child, the function is not passed down, and not available on the `freddie` instance: a `TypeError` is thrown.
## Q. ***What is the output?***
```javascript
let greeting;
greetign = {}; // Typo!
console.log(greetign);
```
- A: `{}`
- B: `ReferenceError: greetign is not defined`
- C: `undefined`
**Answer: A**
It logs the object, because we just created an empty object on the global object! When we mistyped `greeting` as `greetign`, the JS interpreter actually saw this as `global.greetign = {}` (or `window.greetign = {}` in a browser).
In order to avoid this, we can use `"use strict"`. This makes sure that you have declared a variable before setting it equal to anything.
## Q. ***What happens when we do this?***
```javascript
function bark() {
console.log("Woof!");
}
bark.animal = "dog";
```
- A: Nothing, this is totally fine!
- B: `SyntaxError`. You cannot add properties to a function this way.
- C: `"Woof"` gets logged.
- D: `ReferenceError`
**Answer: A**
This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects)
A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable.
## Q. ***What is the output?***
```javascript
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const member = new Person("Lydia", "Hallie");
Person.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
};
console.log(member.getFullName());
```
- A: `TypeError`
- B: `SyntaxError`
- C: `Lydia Hallie`
- D: `undefined` `undefined`
**Answer: A**
You can't add properties to a constructor like you can with regular objects. If you want to add a feature to all objects at once, you have to use the prototype instead. So in this case,
```js
Person.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
};
```
would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it!
## Q. ***What is the output?***
```javascript
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const lydia = new Person("Lydia", "Hallie");
const sarah = Person("Sarah", "Smith");
console.log(lydia);
console.log(sarah);
```
- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined`
- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}`
- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}`
- D:`Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError`
**Answer: A**
For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**!
We said that `this.firstName` equals `"Sarah"` and `this.lastName` equals `"Smith"`. What we actually did, is defining `global.firstName = 'Sarah'` and `global.lastName = 'Smith'`. `sarah` itself is left `undefined`, since we don't return a value from the `Person` function.
## Q. ***What are the three phases of event propagation?***
- A: Target > Capturing > Bubbling
- B: Bubbling > Target > Capturing
- C: Target > Bubbling > Capturing
- D: Capturing > Target > Bubbling
**Answer: D**
During the **capturing** phase, the event goes through the ancestor elements down to the target element. It then reaches the **target** element, and **bubbling** begins.
## Q. ***All object have prototypes.***
- A: true
- B: false
**Answer: B**
All objects have prototypes, except for the **base object**. The base object is the object created by the user, or an object that is created using the `new` keyword. The base object has access to some methods and properties, such as `.toString`. This is the reason why you can use built-in JavaScript methods! All of such methods are available on the prototype. Although JavaScript can't find it directly on your object, it goes down the prototype chain and finds it there, which makes it accessible for you.
## Q. ***What is the output?***
```javascript
function sum(a, b) {
return a + b;
}
sum(1, "2");
```
- A: `NaN`
- B: `TypeError`
- C: `"12"`
- D: `3`
**Answer: C**
JavaScript is a **dynamically typed language**: we don't specify what types certain variables are. Values can automatically be converted into another type without you knowing, which is called _implicit type coercion_. **Coercion** is converting from one type into another.
In this example, JavaScript converts the number `1` into a string, in order for the function to make sense and return a value. During the addition of a numeric type (`1`) and a string type (`'2'`), the number is treated as a string. We can concatenate strings like `"Hello" + "World"`, so What is happening here is `"1" + "2"` which returns `"12"`.
## Q. ***What is the output?***
```javascript
let number = 0;
console.log(number++);
console.log(++number);
console.log(number);
```
- A: `1` `1` `2`
- B: `1` `2` `2`
- C: `0` `2` `2`
- D: `0` `1` `2`
**Answer: C**
The **postfix** unary operator `++`:
1. Returns the value (this returns `0`)
2. Increments the value (number is now `1`)
The **prefix** unary operator `++`:
1. Increments the value (number is now `2`)
2. Returns the value (this returns `2`)
This returns `0 2 2`.
## Q. ***What is the output?***
```javascript
function getPersonInfo(one, two, three) {
console.log(one);
console.log(two);
console.log(three);
}
const person = "Lydia";
const age = 21;
getPersonInfo`${person} is ${age} years old`;
```
- A: `"Lydia"` `21` `["", " is ", " years old"]`
- B: `["", " is ", " years old"]` `"Lydia"` `21`
- C: `"Lydia"` `["", " is ", " years old"]` `21`
**Answer: B**
If you use tagged template literals, the value of the first argument is always an array of the string values. The remaining arguments get the values of the passed expressions!
## Q. ***What is the output?***
```javascript
function checkAge(data) {
if (data === { age: 18 }) {
console.log("You are an adult!");
} else if (data == { age: 18 }) {
console.log("You are still an adult.");
} else {
console.log(`Hmm.. You don't have an age I guess`);
}
}
checkAge({ age: 18 });
```
- A: `You are an adult!`
- B: `You are still an adult.`
- C: `Hmm.. You don't have an age I guess`
**Answer: C**
When testing equality, primitives are compared by their _value_, while objects are compared by their _reference_. JavaScript checks if the objects have a reference to the same location in memory.
The two objects that we are comparing don't have that: the object we passed as a parameter refers to a different location in memory than the object we used in order to check equality.
This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`.
## Q. ***What is the output?***
```javascript
function getAge(...args) {
console.log(typeof args);
}
getAge(21);
```
- A: `"number"`
- B: `"array"`
- C: `"object"`
- D: `"NaN"`
**Answer: C**
The rest parameter (`...args`.) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"`
## Q. ***What is the output?***
```javascript
function getAge() {
"use strict";
age = 21;
console.log(age);
}
getAge();
```
- A: `21`
- B: `undefined`
- C: `ReferenceError`
- D: `TypeError`
**Answer: C**
With `"use strict"`, you can make sure that you don't accidentally declare global variables. We never declared the variable `age`, and since we use `"use strict"`, it will throw a reference error. If we didn't use `"use strict"`, it would have worked, since the property `age` would have gotten added to the global object.
## Q. ***What is value of `sum`?***
```javascript
const sum = eval("10*10+5");
```
- A: `105`
- B: `"105"`
- C: `TypeError`
- D: `"10*10+5"`
**Answer: A**
`eval` evaluates codes that's passed as a string. If it's an expression, like in this case, it evaluates the expression. The expression is `10 * 10 + 5`. This returns the number `105`.
## Q. ***How long is cool_secret accessible?***
```javascript
sessionStorage.setItem("cool_secret", 123);
```
- A: Forever, the data doesn't get lost.
- B: When the user closes the tab.
- C: When the user closes the entire browser, not only the tab.
- D: When the user shuts off their computer.
**Answer: B**
The data stored in `sessionStorage` is removed after closing the _tab_.
If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked.
## Q. ***What is the output?***
```javascript
var num = 8;
var num = 10;
console.log(num);
```
- A: `8`
- B: `10`
- C: `SyntaxError`
- D: `ReferenceError`
**Answer: B**
With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value.
You cannot do this with `let` or `const` since they're block-scoped.
## Q. ***What is the output?***
```javascript
const obj = { 1: "a", 2: "b", 3: "c" };
const set = new Set([1, 2, 3, 4, 5]);
obj.hasOwnProperty("1");
obj.hasOwnProperty(1);
set.has("1");
set.has(1);
```
- A: `false` `true` `false` `true`
- B: `false` `true` `true` `true`
- C: `true` `true` `false` `true`
- D: `true` `true` `true` `true`
**Answer: C**
All object keys (excluding Symbols) are strings under the hood, even if you don't type it yourself as a string. This is why `obj.hasOwnProperty('1')` also returns true.
It doesn't work that way for a set. There is no `'1'` in our set: `set.has('1')` returns `false`. It has the numeric type `1`, `set.has(1)` returns `true`.
## Q. ***What is the output?***
```javascript
const obj = { a: "one", b: "two", a: "three" };
console.log(obj);
```
- A: `{ a: "one", b: "two" }`
- B: `{ b: "two", a: "three" }`
- C: `{ a: "three", b: "two" }`
- D: `SyntaxError`
**Answer: C**
If you have two keys with the same name, the key will be replaced. It will still be in its first position, but with the last specified value.
## Q. ***The JavaScript global execution context creates two things for you: the global object, and the "this" keyword.***
- A: true
- B: false
- C: it depends
**Answer: A**
The base execution context is the global execution context: it's What is accessible everywhere in your code.
## Q. ***What is the output?***
```javascript
for (let i = 1; i < 5; i++) {
if (i === 3) continue;
console.log(i);
}
```
- A: `1` `2`
- B: `1` `2` `3`
- C: `1` `2` `4`
- D: `1` `3` `4`
**Answer: C**
The `continue` statement skips an iteration if a certain condition returns `true`.
## Q. ***What is the output?***
```javascript
String.prototype.giveLydiaPizza = () => {
return "Just give Lydia pizza already!";
};
const name = "Lydia";
name.giveLydiaPizza();
```
- A: `"Just give Lydia pizza already!"`
- B: `TypeError: not a function`
- C: `SyntaxError`
- D: `undefined`
**Answer: A**
`String` is a built-in constructor, which we can add properties to. I just added a method to its prototype. Primitive strings are automatically converted into a string object, generated by the string prototype function. So, all strings (string objects) have access to that method!
## Q. ***What is the output?***
```javascript
const a = {};
const b = { key: "b" };
const c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]);
```
- A: `123`
- B: `456`
- C: `undefined`
- D: `ReferenceError`
**Answer: B**
Object keys are automatically converted into strings. We are trying to set an object as a key to object `a`, with the value of `123`.
However, when we stringify an object, it becomes `"[Object object]"`. So what we are saying here, is that `a["Object object"] = 123`. Then, we can try to do the same again. `c` is another object that we are implicitly stringifying. So then, `a["Object object"] = 456`.
Then, we log `a[b]`, which is actually `a["Object object"]`. We just set that to `456`, so it returns `456`.
## Q. ***What is the output?***
```javascript
const foo = () => console.log("First");
const bar = () => setTimeout(() => console.log("Second"));
const baz = () => console.log("Third");
bar();
foo();
baz();
```
- A: `First` `Second` `Third`
- B: `First` `Third` `Second`
- C: `Second` `First` `Third`
- D: `Second` `Third` `First`
**Answer: B**
We have a `setTimeout` function and invoked it first. Yet, it was logged last.
This is because in browsers, we don't just have the runtime engine, we also have something called a `WebAPI`. The `WebAPI` gives us the `setTimeout` function to start with, and for example the DOM.
After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack.
Now, `foo` gets invoked, and `"First"` is being logged.
`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged.
The WebAPI can't just add stuff to the stack whenever it's ready. Instead, it pushes the callback function to something called the _queue_.
This is where an event loop starts to work. An **event loop** looks at the stack and task queue. If the stack is empty, it takes the first thing on the queue and pushes it onto the stack.
`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack.
## Q. ***What is the event.target when clicking the button?***
```html
Click here!
Then, we declare a variable called `members`. We set the first element of that array equal to the value of the `person` variable. Objects interact by _reference_ when setting them equal to each other. When you assign a reference from one variable to another, you make a _copy_ of that reference. (note that they don't have the _same_ reference!)
Then, we set the variable `person` equal to `null`.
We are only modifying the value of the `person` variable, and not the first element in the array, since that element has a different (copied) reference to the object. The first element in `members` still holds its reference to the original object. When we log the `members` array, the first element still holds the value of the object, which gets logged.
## Q. ***What is the output?***
```javascript
const person = {
name: "Lydia",
age: 21,
};
for (const item in person) {
console.log(item);
}
```
- A: `{ name: "Lydia" }, { age: 21 }`
- B: `"name", "age"`
- C: `"Lydia", 21`
- D: `["name", "Lydia"], ["age", 21]`
**Answer: B**
With a `for-in` loop, we can iterate through object keys, in this case `name` and `age`. Under the hood, object keys are strings (if they're not a Symbol). On every loop, we set the value of `item` equal to the current key it’s iterating over. First, `item` is equal to `name`, and gets logged. Then, `item` is equal to `age`, which gets logged.
## Q. ***What is the output?***
```javascript
console.log(3 + 4 + "5");
```
- A: `"345"`
- B: `"75"`
- C: `12`
- D: `"12"`
**Answer: B**
Operator associativity is the order in which the compiler evaluates the expressions, either left-to-right or right-to-left. This only happens if all operators have the _same_ precedence. We only have one type of operator: `+`. For addition, the associativity is left-to-right.
`3 + 4` gets evaluated first. This results in the number `7`.
`7 + '5'` results in `"75"` because of coercion. JavaScript converts the number `7` into a string, see question 15. We can concatenate two strings using the `+`operator. `"7" + "5"` results in `"75"`.
## Q. ***What is the value of `num`?***
```javascript
const num = parseInt("7*6", 10);
```
- A: `42`
- B: `"42"`
- C: `7`
- D: `NaN`
**Answer: C**
Only the first numbers in the string is returned. Based on the _radix_ (the second argument in order to specify what type of number we want to parse it to: base 10, hexadecimal, octal, binary, etc.), the `parseInt` checks whether the characters in the string are valid. Once it encounters a character that isn't a valid number in the radix, it stops parsing and ignores the following characters.
`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`.
## Q. ***What is the output`?***
```javascript
[1, 2, 3].map((num) => {
if (typeof num === "number") return;
return num * 2;
});
```
- A: `[]`
- B: `[null, null, null]`
- C: `[undefined, undefined, undefined]`
- D: `[ 3 x empty ]`
**Answer: C**
When mapping over the array, the value of `num` is equal to the element it’s currently looping over. In this case, the elements are numbers, so the condition of the if statement `typeof num === "number"` returns `true`. The map function creates a new array and inserts the values returned from the function.
However, we don’t return a value. When we don’t return a value from the function, the function returns `undefined`. For every element in the array, the function block gets called, so for each element we return `undefined`.
## Q. ***What is the output?***
```javascript
function getInfo(member, year) {
member.name = "Lydia";
year = "1998";
}
const person = { name: "Sarah" };
const birthYear = "1997";
getInfo(person, birthYear);
console.log(person, birthYear);
```
- A: `{ name: "Lydia" }, "1997"`
- B: `{ name: "Sarah" }, "1998"`
- C: `{ name: "Lydia" }, "1998"`
- D: `{ name: "Sarah" }, "1997"`
**Answer: A**
Arguments are passed by _value_, unless their value is an object, then they're passed by _reference_. `birthYear` is passed by value, since it's a string, not an object. When we pass arguments by value, a _copy_ of that value is created (see question 46).
The variable `birthYear` has a reference to the value `"1997"`. The argument `year` also has a reference to the value `"1997"`, but it's not the same value as `birthYear` has a reference to. When we update the value of `year` by setting `year` equal to `"1998"`, we are only updating the value of `year`. `birthYear` is still equal to `"1997"`.
The value of `person` is an object. The argument `member` has a (copied) reference to the _same_ object. When we modify a property of the object `member` has a reference to, the value of `person` will also be modified, since they both have a reference to the same object. `person`'s `name` property is now equal to the value `"Lydia"`
## Q. ***What is the output?***
```javascript
function greeting() {
throw "Hello world!";
}
function sayHi() {
try {
const data = greeting();
console.log("It worked!", data);
} catch (e) {
console.log("Oh no an error:", e);
}
}
sayHi();
```
- A: `It worked! Hello world!`
- B: `Oh no an error: undefined`
- C: `SyntaxError: can only throw Error objects`
- D: `Oh no an error: Hello world!`
**Answer: D**
With the `throw` statement, we can create custom errors. With this statement, you can throw exceptions. An exception can be a string, a number, a boolean or an object. In this case, our exception is the string `'Hello world'`.
With the `catch` statement, we can specify what to do if an exception is thrown in the `try` block. An exception is thrown: the string `'Hello world'`. `e` is now equal to that string, which we log. This results in `'Oh an error: Hello world'`.
## Q. ***What is the output?***
```javascript
function Car() {
this.make = "Lamborghini";
return { make: "Maserati" };
}
const myCar = new Car();
console.log(myCar.make);
```
- A: `"Lamborghini"`
- B: `"Maserati"`
- C: `ReferenceError`
- D: `TypeError`
**Answer: B**
When you return a property, the value of the property is equal to the _returned_ value, not the value set in the constructor function. We return the string `"Maserati"`, so `myCar.make` is equal to `"Maserati"`.
## Q. ***What is the output?***
```javascript
(() => {
let x = (y = 10);
})();
console.log(typeof x);
console.log(typeof y);
```
- A: `"undefined", "number"`
- B: `"number", "number"`
- C: `"object", "number"`
- D: `"number", "undefined"`
**Answer: A**
`let x = y = 10;` is actually shorthand for:
```javascript
y = 10;
let x = y;
```
When we set `y` equal to `10`, we actually add a property `y` to the global object (`window` in browser, `global` in Node). In a browser, `window.y` is now equal to `10`.
Then, we declare a variable `x` with the value of `y`, which is `10`. Variables declared with the `let` keyword are _block scoped_, they are only defined within the block they're declared in; the immediately-invoked function (IIFE) in this case. When we use the `typeof` operator, the operand `x` is not defined: we are trying to access `x` outside of the block it's declared in. This means that `x` is not defined. Values who haven't been assigned a value or declared are of type `"undefined"`. `console.log(typeof x)` returns `"undefined"`.
However, we created a global variable `y` when setting `y` equal to `10`. This value is accessible anywhere in our code. `y` is defined, and holds a value of type `"number"`. `console.log(typeof y)` returns `"number"`.
## Q. ***What is the output?***
```javascript
class Dog {
constructor(name) {
this.name = name;
}
}
Dog.prototype.bark = function () {
console.log(`Woof I am ${this.name}`);
};
const pet = new Dog("Mara");
pet.bark();
delete Dog.prototype.bark;
pet.bark();
```
- A: `"Woof I am Mara"`, `TypeError`
- B: `"Woof I am Mara"`, `"Woof I am Mara"`
- C: `"Woof I am Mara"`, `undefined`
- D: `TypeError`, `TypeError`
**Answer: A**
We can delete properties from objects using the `delete` keyword, also on the prototype. By deleting a property on the prototype, it is not available anymore in the prototype chain. In this case, the `bark` function is not available anymore on the prototype after `delete Dog.prototype.bark`, yet we still try to access it.
When we try to invoke something that is not a function, a `TypeError` is thrown. In this case `TypeError: pet.bark is not a function`, since `pet.bark` is `undefined`.
## Q. ***What is the output?***
```javascript
const set = new Set([1, 1, 2, 3, 4]);
console.log(set);
```
- A: `[1, 1, 2, 3, 4]`
- B: `[1, 2, 3, 4]`
- C: `{1, 1, 2, 3, 4}`
- D: `{1, 2, 3, 4}`
**Answer: D**
The `Set` object is a collection of _unique_ values: a value can only occur once in a set.
We passed the iterable `[1, 1, 2, 3, 4]` with a duplicate value `1`. Since we cannot have two of the same values in a set, one of them is removed. This results in `{1, 2, 3, 4}`.
## Q. ***What is the output?***
```javascript
// counter.js
let counter = 10;
export default counter;
```
```javascript
// index.js
import myCounter from "./counter";
myCounter += 1;
console.log(myCounter);
```
- A: `10`
- B: `11`
- C: `Error`
- D: `NaN`
**Answer: C**
An imported module is _read-only_: you cannot modify the imported module. Only the module that exports them can change its value.
When we try to increment the value of `myCounter`, it throws an error: `myCounter` is read-only and cannot be modified.
## Q. ***What is the output?***
```javascript
const name = "Lydia";
age = 21;
console.log(delete name);
console.log(delete age);
```
- A: `false`, `true`
- B: `"Lydia"`, `21`
- C: `true`, `true`
- D: `undefined`, `undefined`
**Answer: A**
The `delete` operator returns a boolean value: `true` on a successful deletion, else it'll return `false`. However, variables declared with the `var`, `const` or `let` keyword cannot be deleted using the `delete` operator.
The `name` variable was declared with a `const` keyword, so its deletion is not successful: `false` is returned. When we set `age` equal to `21`, we actually added a property called `age` to the global object. You can successfully delete properties from objects this way, also the global object, so `delete age` returns `true`.
## Q. ***What is the output?***
```javascript
const numbers = [1, 2, 3, 4, 5];
const [y] = numbers;
console.log(y);
```
- A: `[[1, 2, 3, 4, 5]]`
- B: `[1, 2, 3, 4, 5]`
- C: `1`
- D: `[1]`
**Answer: C**
We can unpack values from arrays or properties from objects through destructuring. For example:
```javascript
[a, b] = [1, 2];
```
The value of `a` is now `1`, and the value of `b` is now `2`. What we actually did in the question, is:
```javascript
[y] = [1, 2, 3, 4, 5];
```
This means that the value of `y` is equal to the first value in the array, which is the number `1`. When we log `y`, `1` is returned.
## Q. ***What is the output?***
```javascript
const user = { name: "Lydia", age: 21 };
const admin = { admin: true, ...user };
console.log(admin);
```
- A: `{ admin: true, user: { name: "Lydia", age: 21 } }`
- B: `{ admin: true, name: "Lydia", age: 21 }`
- C: `{ admin: true, user: ["Lydia", 21] }`
- D: `{ admin: true }`
**Answer: B**
It's possible to combine objects using the spread operator `...`. It lets you create copies of the key/value pairs of one object, and add them to another object. In this case, we create copies of the `user` object, and add them to the `admin` object. The `admin` object now contains the copied key/value pairs, which results in `{ admin: true, name: "Lydia", age: 21 }`.
## Q. ***What is the output?***
```javascript
const person = { name: "Lydia" };
Object.defineProperty(person, "age", { value: 21 });
console.log(person);
console.log(Object.keys(person));
```
- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]`
- B: `{ name: "Lydia", age: 21 }`, `["name"]`
- C: `{ name: "Lydia"}`, `["name", "age"]`
- D: `{ name: "Lydia"}`, `["age"]`
**Answer: B**
With the `defineProperty` method, we can add new properties to an object, or modify existing ones. When we add a property to an object using the `defineProperty` method, they are by default _not enumerable_. The `Object.keys` method returns all _enumerable_ property names from an object, in this case only `"name"`.
Properties added using the `defineProperty` method are immutable by default. You can override this behavior using the `writable`, `configurable` and `enumerable` properties. This way, the `defineProperty` method gives you a lot more control over the properties you're adding to an object.
## Q. ***What is the output?***
```javascript
const settings = {
username: "lydiahallie",
level: 19,
health: 90,
};
const data = JSON.stringify(settings, ["level", "health"]);
console.log(data);
```
- A: `"{"level":19, "health":90}"`
- B: `"{"username": "lydiahallie"}"`
- C: `"["level", "health"]"`
- D: `"{"username": "lydiahallie", "level":19, "health":90}"`
**Answer: A**
The second argument of `JSON.stringify` is the _replacer_. The replacer can either be a function or an array, and lets you control what and how the values should be stringified.
If the replacer is an _array_, only the property names included in the array will be added to the JSON string. In this case, only the properties with the names `"level"` and `"health"` are included, `"username"` is excluded. `data` is now equal to `"{"level":19, "health":90}"`.
If the replacer is a _function_, this function gets called on every property in the object you're stringifying. The value returned from this function will be the value of the property when it's added to the JSON string. If the value is `undefined`, this property is excluded from the JSON string.
## Q. ***What is the output?***
```javascript
let num = 10;
const increaseNumber = () => num++;
const increasePassedNumber = (number) => number++;
const num1 = increaseNumber();
const num2 = increasePassedNumber(num1);
console.log(num1);
console.log(num2);
```
- A: `10`, `10`
- B: `10`, `11`
- C: `11`, `11`
- D: `11`, `12`
**Answer: A**
The unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `num1` is `10`, since the `increaseNumber` function first returns the value of `num`, which is `10`, and only increments the value of `num` afterwards.
`num2` is `10`, since we passed `num1` to the `increasePassedNumber`. `number` is equal to `10`(the value of `num1`. Again, the unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `number` is `10`, so `num2` is equal to `10`.
## Q. ***What is the output?***
```javascript
const value = { number: 10 };
const multiply = (x = { ...value }) => {
console.log((x.number *= 2));
};
multiply();
multiply();
multiply(value);
multiply(value);
```
- A: `20`, `40`, `80`, `160`
- B: `20`, `40`, `20`, `40`
- C: `20`, `20`, `20`, `40`
- D: `NaN`, `NaN`, `20`, `40`
**Answer: C**
In ES6, we can initialize parameters with a default value. The value of the parameter will be the default value, if no other value has been passed to the function, or if the value of the parameter is `"undefined"`. In this case, we spread the properties of the `value` object into a new object, so `x` has the default value of `{ number: 10 }`.
The default argument is evaluated at _call time_! Every time we call the function, a _new_ object is created. We invoke the `multiply` function the first two times without passing a value: `x` has the default value of `{ number: 10 }`. We then log the multiplied value of that number, which is `20`.
The third time we invoke multiply, we do pass an argument: the object called `value`. The `*=` operator is actually shorthand for `x.number = x.number * 2`: we modify the value of `x.number`, and log the multiplied value `20`.
The fourth time, we pass the `value` object again. `x.number` was previously modified to `20`, so `x.number *= 2` logs `40`.
## Q. ***What is the output?***
```javascript
[1, 2, 3, 4].reduce((x, y) => console.log(x, y));
```
- A: `1` `2` and `3` `3` and `6` `4`
- B: `1` `2` and `2` `3` and `3` `4`
- C: `1` `undefined` and `2` `undefined` and `3` `undefined` and `4` `undefined`
- D: `1` `2` and `undefined` `3` and `undefined` `4`
**Answer: D**
The first argument that the `reduce` method receives is the _accumulator_, `x` in this case. The second argument is the _current value_, `y`. With the reduce method, we execute a callback function on every element in the array, which could ultimately result in one single value.
In this example, we are not returning any values, we are simply logging the values of the accumulator and the current value.
The value of the accumulator is equal to the previously returned value of the callback function. If you don't pass the optional `initialValue` argument to the `reduce` method, the accumulator is equal to the first element on the first call.
On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator and current value: `1` and `2` get logged.
If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, and the current value is `3`. `undefined` and `3` get logged.
On the fourth call, we again don't return from the callback function. The accumulator is again `undefined`, and the current value is `4`. `undefined` and `4` get logged.
---
## Q. ***With which constructor can we successfully extend the `Dog` class?***
```javascript
class Dog {
constructor(name) {
this.name = name;
}
}
class Labrador extends Dog {
// 1
constructor(name, size) {
this.size = size;
}
// 2
constructor(name, size) {
super(name);
this.size = size;
}
// 3
constructor(size) {
super(name);
this.size = size;
}
// 4
constructor(name, size) {
this.name = name;
this.size = size;
}
}
```
- A: 1
- B: 2
- C: 3
- D: 4
**Answer: B**
In a derived class, you cannot access the `this` keyword before calling `super`. If you try to do that, it will throw a ReferenceError: 1 and 4 would throw a reference error.
With the `super` keyword, we call that parent class's constructor with the given arguments. The parent's constructor receives the `name` argument, so we need to pass `name` to `super`.
The `Labrador` class receives two arguments, `name` since it extends `Dog`, and `size` as an extra property on the `Labrador` class. They both need to be passed to the constructor function on `Labrador`, which is done correctly using constructor 2.
## Q. ***What is the output?***
```javascript
// index.js
console.log("running index.js");
import { sum } from "./sum.js";
console.log(sum(1, 2));
// sum.js
console.log("running sum.js");
export const sum = (a, b) => a + b;
```
- A: `running index.js`, `running sum.js`, `3`
- B: `running sum.js`, `running index.js`, `3`
- C: `running sum.js`, `3`, `running index.js`
- D: `running index.js`, `undefined`, `running sum.js`
**Answer: B**
With the `import` keyword, all imported modules are _pre-parsed_. This means that the imported modules get run _first_, the code in the file which imports the module gets executed _after_.
This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we would have used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console.
## Q. ***What is the output?***
```javascript
console.log(Number(2) === Number(2));
console.log(Boolean(false) === Boolean(false));
console.log(Symbol("foo") === Symbol("foo"));
```
- A: `true`, `true`, `false`
- B: `false`, `true`, `false`
- C: `true`, `false`, `true`
- D: `true`, `true`, `true`
**Answer: A**
Every Symbol is entirely unique. The purpose of the argument passed to the Symbol is to give the Symbol a description. The value of the Symbol is not dependent on the passed argument. As we test equality, we are creating two entirely new symbols: the first `Symbol('foo')`, and the second `Symbol('foo')`. These two values are unique and not equal to each other, `Symbol('foo') === Symbol('foo')` returns `false`.
## Q. ***What is the output?***
```javascript
const name = "Lydia Hallie";
console.log(name.padStart(13));
console.log(name.padStart(2));
```
- A: `"Lydia Hallie"`, `"Lydia Hallie"`
- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`)
- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`)
- D: `"Lydia Hallie"`, `"Lyd"`,
**Answer: C**
With the `padStart` method, we can add padding to the beginning of a string. The value passed to this method is the _total_ length of the string together with the padding. The string `"Lydia Hallie"` has a length of `12`. `name.padStart(13)` inserts 1 space at the start of the string, because 12 + 1 is 13.
If the argument passed to the `padStart` method is smaller than the length of the array, no padding will be added.
## Q. ***What is the output?***
```javascript
console.log("🥑" + "💻");
```
- A: `"🥑💻"`
- B: `257548`
- C: A string containing their code points
- D: Error
**Answer: A**
With the `+` operator, you can concatenate strings. In this case, we are concatenating the string `"🥑"` with the string `"💻"`, resulting in `"🥑💻"`.
## Q. ***How can we log the values that are commented out after the console.log statement?***
```javascript
function* startGame() {
const answer = yield "Do you love JavaScript?";
if (answer !== "Yes") {
return "Oh wow... Guess we're gone here";
}
return "JavaScript loves you back ❤️";
}
const game = startGame();
console.log(/* 1 */); // Do you love JavaScript?
console.log(/* 2 */); // JavaScript loves you back ❤️
```
- A: `game.next("Yes").value` and `game.next().value`
- B: `game.next.value("Yes")` and `game.next.value()`
- C: `game.next().value` and `game.next("Yes").value`
- D: `game.next.value()` and `game.next.value("Yes")`
**Answer: C**
A generator function "pauses" its execution when it sees the `yield` keyword. First, we have to let the function yield the string "Do you love JavaScript?", which can be done by calling `game.next().value`.
Every line is executed, until it finds the first `yield` keyword. There is a `yield` keyword on the first line within the function: the execution stops with the first yield! _This means that the variable `answer` is not defined yet!_
When we call `game.next("Yes").value`, the previous `yield` is replaced with the value of the parameters passed to the `next()` function, `"Yes"` in this case. The value of the variable `answer` is now equal to `"Yes"`. The condition of the if-statement returns `false`, and `JavaScript loves you back ❤️` gets logged.
## Q. ***What is the output?***
```javascript
console.log(String.raw`Hello\nworld`);
```
- A: `Hello world!`
- B: `Hello`