diff --git a/README.md b/README.md index 9ea5671..0ebc105 100644 --- a/README.md +++ b/README.md @@ -18,17 +18,15 @@ function sum(x, y) { }; } } -``` - -Output -```js console.log(sum(2,3)); // Outputs 5 console.log(sum(2)(3)); // Outputs 5 ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-1-ypmjhl?file=/src/index.js)** +
- ↥ back to top + ↥ back to top
## Q. ***How to validate file size and extension before upload?*** @@ -36,71 +34,43 @@ console.log(sum(2)(3)); // Outputs 5 ```html - - - Show File Data - - - -
- - -
- + console.log("File Name: " + file.name); + console.log("File Size: " + file.size + " bytes"); + console.log("File Extension: " + extension); + } + + + + +
+ + +
+ + + + +File Name: pic.jpg +File Size: 1159168 bytes +File Extension: jpg ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-file-upload-fj17kh?file=/index.html)** +
- ↥ back to top + ↥ back to top
## Q. ***Create captcha using javascript?*** @@ -115,36 +85,22 @@ console.log(sum(2)(3)); // Outputs 5 var captcha; function generateCaptcha() { - var a = Math.floor(Math.random() * 10); - var b = Math.floor(Math.random() * 10); - var c = Math.floor(Math.random() * 10); - var d = Math.floor(Math.random() * 10); - - captcha = a.toString() + b.toString() + c.toString() + d.toString(); + captcha = Math.floor(Math.random() * 1000000); document.getElementById("captcha").value = captcha; } - - function check() { - var input = document.getElementById("inputText").value; - - if (input == captcha) { - alert("Valid Captcha"); - } else { - alert("Invalid Captcha"); - } - } +

-

- ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-captcha-mzyi2n?file=/index.html)** +
- ↥ back to top + ↥ back to top
## Q. ***Create a Stopwatch program in javascript?*** @@ -155,109 +111,76 @@ console.log(sum(2)(3)); // Outputs 5 Stopwatch Example + -
-

Simple stopwatch made in JavaScript

- - - -
-

- 0 : 00 : - 000 -

-

- In this example Date() methods co-operate with timing function - setInterval(). -

+

Time: 00:00:00



+ + + ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-stopwatch-j6in1i?file=/index.html)** +
- ↥ back to top + ↥ back to top
## Q. ***Write a program to reverse a string?*** @@ -270,11 +193,15 @@ function reverseString(str) { } return stringRev; } -alert(reverseString("Pradeep")); // Output: peedarP +console.log(reverseString("Hello")); + +// Output: olleH ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-reversestring-sgm1ip?file=/src/index.js)** +
- ↥ back to top + ↥ back to top
## Q. ***How to check if object is empty or not in javaScript?*** @@ -283,19 +210,39 @@ alert(reverseString("Pradeep")); // Output: peedarP function isEmpty(obj) { return Object.keys(obj).length === 0; } + +const obj = {}; +console.log(isEmpty(obj)); // true ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-isempty-b7n04b?file=/src/index.js)** + +
+ ↥ back to top +
+ ## Q. ***JavaScript Regular Expression to validate Email*** ```javascript -var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; +function validateEmail(email) { + const re = /\S+@\S+\.\S+/; + return re.test(email); +} + +console.log(validateEmail("pradeep.vwa@gmail.com")); // true ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-validateemail-wfopym?file=/src/index.js)** + +
+ ↥ back to top +
+ ## Q. ***Use RegEx to test password strength in JavaScript?*** ```javascript -var newPassword = "Pq5*@a{J"; -var regularExpression = new RegExp( +let newPassword = "Pq5*@a{J"; +const regularExpression = new RegExp( "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})" ); @@ -303,7 +250,12 @@ if (!regularExpression.test(newPassword)) { alert( "Password should contain atleast one number and one special character !" ); +} else { + console.log("PASS"); } + +// Output +PASS ``` | RegEx | Description | @@ -315,8 +267,10 @@ if (!regularExpression.test(newPassword)) { | (?=.[!@#\$%\^&]) | 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 | +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-password-strength-cxl8xy)** +
- ↥ back to top + ↥ back to top
## Q. ***How to compare objects ES6?*** @@ -368,7 +322,7 @@ JSON.stringify(one) === JSON.stringify(two); // false ```
- ↥ back to top + ↥ back to top
## Q. ***How to remove array element based on object property?*** @@ -397,7 +351,7 @@ myArray = [ ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -434,7 +388,7 @@ console.log(x); // Output: 10 ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -460,7 +414,7 @@ console.log(1 + -"1" + 2); // Output: 2 ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -475,7 +429,7 @@ getNumber(); // Output: undefined ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -527,7 +481,7 @@ console.log(k); // Output: 1undefined ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -565,7 +519,7 @@ console.log("(a % b): " + (a % b)); // Output: 4 ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -605,7 +559,7 @@ myObject.func(); ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -654,7 +608,7 @@ console.log("A" - "B" + 2); // Output: NaN ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -691,7 +645,7 @@ console.log("1 && 2 = " + (1 && 2)); // Output: 2 ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -734,7 +688,7 @@ console.log( ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -773,7 +727,7 @@ obj.method(fn, 1); ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -834,7 +788,7 @@ outer(); ```
- ↥ back to top + ↥ back to top
## Q. ***Hoisting example in javascript?*** @@ -860,7 +814,7 @@ o.constructor === F; ```
- ↥ back to top + ↥ back to top
## Q. ***Predict the output of the following JavaScript code?*** @@ -936,7 +890,7 @@ for (var i = 1; i <= 15; i++) { ```
- ↥ back to top + ↥ back to top
## Q. ***What will be the output of the following code?*** @@ -967,7 +921,7 @@ 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`.
- ↥ back to top + ↥ back to top
## Q. ***What will be the output of the following code?*** @@ -1000,7 +954,7 @@ The code above will output `xyz` as output. Here `emp1` object got company as ** `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`.
- ↥ back to top + ↥ back to top
## Q. ***What will be the output of the following code?*** @@ -1035,7 +989,7 @@ The code above will output `1, "truexyz", 2, 1` as output. Here's a general guid - String + String -> Concatenation
- ↥ back to top + ↥ back to top
## Q. ***What will be the output of the following code?*** @@ -1101,7 +1055,7 @@ var foo = function bar() { ```
- ↥ back to top + ↥ back to top
## Q. ***What is the output of the following?*** @@ -1155,7 +1109,7 @@ var salary = "1000$"; ```
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of the following code?*** @@ -1188,7 +1142,7 @@ foo["location"] = "USA"; ```
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1204,7 +1158,7 @@ The output will `'hi there'` because we're dealing with strings here. Strings ar passed by value, that is, copied.
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1237,7 +1191,7 @@ However, when we reassign `objB` to an empty object, we simply change where `obj This doesn't affect where `objA` variable references to.
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1270,7 +1224,7 @@ The `slice` function copies all the elements of the array returning the new arra `arrA` and `arrB` reference two completely different arrays.
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1334,7 +1288,7 @@ two elements. This is why changing the property of `arrB[0]` in `arrB` will also change the `arrA[0]`.
- ↥ back to top + ↥ back to top
## Q. ***console.log(employeeId);*** @@ -1378,7 +1332,7 @@ var employeeId = "1234abe"; _Answer:_ 2) undefined
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1420,7 +1374,7 @@ _Answer:_ 2) undefined _Answer:_ 1) undefined
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1465,7 +1419,7 @@ console.log(employeeId); _Answer:_ 3) 'abc123'
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1514,7 +1468,7 @@ foo(); _Answer:_ 1) undefined
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1542,7 +1496,7 @@ _Answer:_ 1) undefined _Answer:_ 3) function function
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1574,7 +1528,7 @@ _Answer:_ 3) function function _Answer:_ 3) ["name", "salary", "country", "phoneNo"]
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1606,7 +1560,7 @@ _Answer:_ 3) ["name", "salary", "country", "phoneNo"] _Answer:_ 4) ["name", "salary", "country"]
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1652,7 +1606,7 @@ _Answer:_ 2) false false _Answer:_ 2) false false
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1698,7 +1652,7 @@ _Answer:_ 2) false false _Answer:_ 2) false false
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1744,7 +1698,7 @@ _Answer:_ 4) true true _Answer:_ 3) true true true true
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1792,7 +1746,7 @@ _Answer:_ 2) bar bar _Answer:_ 3) foo foo
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1836,7 +1790,7 @@ _Answer:_ 2) undefined undefined _Answer:_ 3) ["100"] 1
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1879,7 +1833,7 @@ _Answer:_ 1) [] [] [Array[5]] 1 _Answer:_ 1) 11
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1919,7 +1873,7 @@ _Answer:_ 3) 6 _Answer:_ 1) [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ]
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -1960,7 +1914,7 @@ _Answer:_ 1) 1 -1 -1 4 _Answer:_ 2) 1 6 -1
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2027,7 +1981,7 @@ _Answer:_ 1) [ 2, '12', true ] [ 2, '12', true ]
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2089,7 +2043,7 @@ _Answer:_ 1) [ 'bar', 'john', 'ritz' ] _Answer:_ 1. [ 'bar', 'john' ] [] [ 'foo' ]
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2135,7 +2089,7 @@ console.log(funcA()); _Answer:_ 1)
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2179,7 +2133,7 @@ console.log(obj.innerMessage()); _Answer:_ 1) Hello
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2226,7 +2180,7 @@ console.log(obj.innerMessage()); _Answer:_ 2) 'Hello'
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2266,7 +2220,7 @@ console.log(myFunc()); _Answer:_ 2) 'Hi John'
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2305,7 +2259,7 @@ console.log(myFunc("a", "b", "c", "d")); _Answer:_ a) 2 2 2
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2355,7 +2309,7 @@ Person.displayName(); _Answer:_ 1) John Person
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2399,7 +2353,7 @@ console.log(Employee.employeeId); _Answer:_ 4) undefined
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2446,7 +2400,7 @@ var employeeId = "aq123"; _Answer:_ 1) foo123 aq123
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2500,7 +2454,7 @@ _Answer:_ 4) [ 'W', 'o', 'r', 'l', 'd' ] _Answer:_ 1) Total amount left in account: 5600 Total amount left in account: 5300
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2536,7 +2490,7 @@ _Answer:_ 1) Total amount left in account: 5600 Total amount left in account: 53 _Answer:_ 1) 5600 5300 5100
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2572,7 +2526,7 @@ _Answer:_ 1) 5600 5300 5100 _Answer:_ 2) 3600 3300 3100
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2617,7 +2571,7 @@ getDataFromServer("www.google.com").then(function (name) { _Answer:_ 1) John
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2667,7 +2621,7 @@ _Answer:_ 1) [ 2, 8, 15, 16, 23, 42 ] [ 2, 8, 15, 16, 23, 42 ]
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2711,7 +2665,7 @@ console.log(numb); _Answer:_ 1) 5
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2758,7 +2712,7 @@ console.log(mul(2)(3)[1](4)); _Answer:_ 1) 6, 10
- ↥ back to top + ↥ back to top
## Q. ***What would be the output of following code?*** @@ -2810,7 +2764,7 @@ console.log(mul(2)(3)(4)(5)(6)); _Answer:_ 1) 720
- ↥ back to top + ↥ back to top
## Q. ***What is the value of `foo`?*** @@ -2854,7 +2808,7 @@ add()()(2)(5); // 7 ```
- ↥ back to top + ↥ back to top
## Q. ***What value is returned from the following statement?*** @@ -2890,7 +2844,7 @@ _Answer:_ - Second: Throws an exception, `ReferenceError: bar is not defined`
- ↥ back to top + ↥ back to top
## Q. ***What is the value of `foo.length`?*** @@ -2920,7 +2874,7 @@ to an original object, `{n: 1}`. So, when the result of the right term, `{n: 2}` moment referenced by `bar`.
- ↥ back to top + ↥ back to top
## Q. ***What does the following code print?*** @@ -2961,7 +2915,7 @@ console.log(countCharacters("the brown fox jumps over the lazy dog")); ```
- ↥ back to top + ↥ back to top
## Q. ***What is the value of `foo`?*** @@ -3005,7 +2959,7 @@ add()()(2)(5); // 7 ```
- ↥ back to top + ↥ back to top
## Q. ***What value is returned from the following statement?*** @@ -3051,7 +3005,7 @@ foo.push(2); _Answer:_ `.push` is mutable - `2`
- ↥ back to top + ↥ back to top
## Q. ***What is the value of `foo.x`?*** @@ -3071,7 +3025,7 @@ to an original object, `{n: 1}`. So, when the result of the right term, `{n: 2}` moment referenced by `bar`.
- ↥ back to top + ↥ back to top
## Q. ***What does the following code print?*** @@ -3121,7 +3075,7 @@ f = g = 0; ```
- ↥ back to top + ↥ back to top
## Q. ***What will be the output?*** @@ -3196,7 +3150,7 @@ try { ```
- ↥ back to top + ↥ back to top
## Q. ***What will the following code output?*** @@ -3233,7 +3187,7 @@ console.log(emp1.company); ```
- ↥ back to top + ↥ back to top
## Q. ***Make this work: @@ -3251,7 +3205,7 @@ duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5] ```
- ↥ back to top + ↥ back to top
## Q. ***Fix the bug using ES5 only?*** @@ -3284,7 +3238,7 @@ for (var i = 0; i < arr.length; i++) { ```
- ↥ back to top + ↥ back to top
## Q. ***What will be the output of the following code?*** @@ -3315,7 +3269,7 @@ console.log(result); // 200
4
40
```
- ↥ back to top + ↥ back to top
## Q. ***What will be the output of the following code?*** @@ -3352,7 +3306,7 @@ console.log([...country]); ```
- ↥ back to top + ↥ back to top
## Q. ***Given and object and property path. Get value from property path*** @@ -3388,7 +3342,7 @@ path = "system.database.1.port"; ```
- ↥ back to top + ↥ back to top
## Q. ***How to filter object from Arrays of Objects*** @@ -3406,7 +3360,7 @@ str = str.replace(/test/g, ""); ```
- ↥ back to top + ↥ back to top
## Q. ***Write a script that returns the number of occurrences of character given a string as input*** @@ -3430,7 +3384,7 @@ console.log(countCharacters("the brown fox jumps over the lazy dog")); ```
- ↥ back to top + ↥ back to top
## Q. ***write a script that return the number of occurrences of a character in paragraph*** @@ -3452,7 +3406,7 @@ console.log(charCount("the brown fox jumps over the lazy dog", "o")); ```
- ↥ back to top + ↥ back to top
## Q. ***Recursive and non-recursive Factorial function*** @@ -3489,7 +3443,7 @@ console.log(factorial(5)); ```
- ↥ back to top + ↥ back to top
## Q. ***Recursive and non recursive fibonacci-sequence*** @@ -3547,7 +3501,7 @@ console.log(min + Math.floor(Math.random() * (max - min + 1))); ```
- ↥ back to top + ↥ back to top
## Q. ***Get HTML form values as JSON object*** @@ -3572,7 +3526,7 @@ document.querySelector("HTML_FORM_CLASS").elements; ```
- ↥ back to top + ↥ back to top
## Q. ***Reverse the number*** @@ -3592,7 +3546,7 @@ console.log(reverse(12345)); ```
- ↥ back to top + ↥ back to top
## Q. ***Remove Duplicate elements from Array*** @@ -3628,7 +3582,7 @@ console.log([...new Set(arr)]); ```
- ↥ back to top + ↥ back to top
## Q. ***Deep copy of object or clone of object*** @@ -3667,7 +3621,7 @@ console.log(deepExtend({}, { a: 1, b: { c: 2, d: 3 } }, { e: 4, b: { f: 1 } })); ```
- ↥ back to top + ↥ back to top
## Q. ***Sort ticket based on flying order.*** @@ -3718,7 +3672,7 @@ new SortTickets({ ```
- ↥ back to top + ↥ back to top
## Q. ***Cuncurrent execute function based on input number*** @@ -3768,7 +3722,7 @@ c.start(); ```
- ↥ back to top + ↥ back to top
## Q. ***Reversing an array*** @@ -3828,7 +3782,7 @@ console.log(topN([1, 8, 3, 4, 5], 2)); // [5,8] ```
- ↥ back to top + ↥ back to top
## Q. ***Get query params from Object*** @@ -3857,7 +3811,7 @@ console.log( ```
- ↥ back to top + ↥ back to top
## Q. ***Consecutive 1's in binary*** @@ -3884,7 +3838,7 @@ console.log(consecutiveOne(5)); //1 ```
- ↥ back to top + ↥ back to top
## Q. ***Spiral travesal of matrix*** @@ -3931,7 +3885,7 @@ console.log(spiralTraversal(input)); // [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5 ```
- ↥ back to top + ↥ back to top
## Q. ***Merge Sorted array and sort it.*** @@ -3945,7 +3899,7 @@ console.log(mergeSortedArray([1, 2, 3, 4, 5, 6], [0, 3, 4, 7])); // [0, 1, 2, 3, ```
- ↥ back to top + ↥ back to top
## Q. ***Anagram of words*** @@ -3977,7 +3931,7 @@ console.log( ```
- ↥ back to top + ↥ back to top
## Q. ***Print the largest (maximum) hourglass sum found in 2d array.*** @@ -4007,7 +3961,7 @@ function main(arr) { ```
- ↥ back to top + ↥ back to top
## Q. ***Transform array of object to array*** @@ -4041,7 +3995,7 @@ console.log(Object.keys(newData).map((key) => newData[key])); ```
- ↥ back to top + ↥ back to top
## Q. ***Create a private variable or private method in object*** @@ -4066,7 +4020,7 @@ obj.callPrivateFunction(); // this is private function ```
- ↥ back to top + ↥ back to top
## Q. ***Flatten only Array not objects*** @@ -4121,7 +4075,7 @@ console.log(flattenIterative1(list2)); // [0, 1, 2, 3, 4, 5] ```
- ↥ back to top + ↥ back to top
## Q. ***Find max difference between two number in Array*** @@ -4151,7 +4105,7 @@ let a = 10, ```
- ↥ back to top + ↥ back to top
## Q. ***Panagram ? it means all the 26 letters of alphabet are there*** @@ -4181,7 +4135,7 @@ processData("We promptly judged antique ivory buckles for the prize"); // Not Pa ```
- ↥ back to top + ↥ back to top
## Q. ***Given two identical DOM trees (not the same one), and a node from one of them find the node in the other one.*** @@ -4216,7 +4170,7 @@ console.log(locateNodeFromPath(rootB, getPath(rootA, target))); ```
- ↥ back to top + ↥ back to top
## Q. ***Convert a number into a Roman Numeral*** @@ -4252,7 +4206,7 @@ console.log(romanize(3)); // III ```
- ↥ back to top + ↥ back to top
## Q. ***check if parenthesis is malformed or not*** @@ -4284,7 +4238,7 @@ console.log(matchParenthesis("}{{}}"), matchParenthesis("{{[]}}")); // false - t ```
- ↥ back to top + ↥ back to top
## Q. ***Create Custom Event Emitter class*** @@ -4322,7 +4276,7 @@ e.emit("callme", ["a", "b"], { firstName: "umesh", lastName: "gohil" }); ```
- ↥ back to top + ↥ back to top
## Q. ***Max value from an array*** @@ -4335,7 +4289,7 @@ Math.max.apply(Math, arr); // Slow ```
- ↥ back to top + ↥ back to top
## Q. ***DOM methods*** @@ -4374,7 +4328,7 @@ el.style // get the style of el ```
- ↥ back to top + ↥ back to top
## Q. ***search function called after 500 ms*** @@ -4397,7 +4351,7 @@ search.addEventListener("keyup", function () { ```
- ↥ back to top + ↥ back to top
## Q. ***Move all zero's to end*** @@ -4419,7 +4373,7 @@ console.log(moveZeroToEnd([1, 8, 2, 0, 0, 0, 3, 4, 0, 5, 0])); // [1, 8, 2, 3, 4 ```
- ↥ back to top + ↥ back to top
## Q. ***Decode message in matrix [diagional down right, diagional up right]*** @@ -4468,7 +4422,7 @@ console.log(decodeMessage(mat)); //IROELEA ```
- ↥ back to top + ↥ back to top
## Q. ***find a pair in array, whose sum is equal to given number.*** @@ -4519,7 +4473,7 @@ console.log(hasPairSum([6, 4, 3, 8], 8)); ```
- ↥ back to top + ↥ back to top
## Q. ***Binary Search [Array should be sorted]*** @@ -4547,7 +4501,7 @@ console.log(binarySearch([-1, 10, 22, 35, 48, 56, 67], 27)); ```
- ↥ back to top + ↥ back to top
## Q. ***Pascal triangle.*** @@ -4569,7 +4523,7 @@ console.log(pascalTriangle(2)); ```
- ↥ back to top + ↥ back to top
## Q. ***Explain the code below. How many times the createVal function is called?*** @@ -4597,7 +4551,7 @@ VM298:6 5 ```
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -4625,7 +4579,7 @@ Within the function, we first declare the `name` variable with the `var` keyword Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, don't get initialized. They are not accessible before the line we declare (initialize) them. This is called the "temporal dead zone". When we try to access the variables before they are declared, JavaScript throws a `ReferenceError`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -4651,7 +4605,7 @@ Because of the event queue in JavaScript, the `setTimeout` callback function is In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -4683,7 +4637,7 @@ With arrow functions, the `this` keyword refers to its current surrounding scope There is no value `radius` on that object, which returns `undefined`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -4704,7 +4658,7 @@ The unary plus tries to convert an operand to a number. `true` is `1`, and `fals The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`.
- ↥ back to top + ↥ back to top
## Q. ***Which one is true?*** @@ -4736,7 +4690,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -4767,7 +4721,7 @@ First, variable `c` holds a value to an object. Later, we assign `d` with the sa When you change one object, you change all of them.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -4796,7 +4750,7 @@ When we use the `==` operator, it only checks whether it has the same _value_. T 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.`
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -4827,7 +4781,7 @@ console.log(freddie.colorChange("orange")); 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -4849,7 +4803,7 @@ It logs the object, because we just created an empty object on the global object 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.
- ↥ back to top + ↥ back to top
## Q. ***What happens when we do this?*** @@ -4874,7 +4828,7 @@ This is possible in JavaScript, because functions are objects! (Everything besid 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -4911,7 +4865,7 @@ Person.prototype.getFullName = function () { 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!
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -4941,7 +4895,7 @@ For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the 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.
- ↥ back to top + ↥ back to top
## Q. ***What are the three phases of event propagation?*** @@ -4958,7 +4912,7 @@ During the **capturing** phase, the event goes through the ancestor elements dow
- ↥ back to top + ↥ back to top
## Q. ***All object have prototypes.*** @@ -4971,7 +4925,7 @@ During the **capturing** phase, the event goes through the ancestor elements dow 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -4996,7 +4950,7 @@ JavaScript is a **dynamically typed language**: we don't specify what types cert 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"`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5028,7 +4982,7 @@ The **prefix** unary operator `++`: This returns `0 2 2`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5055,7 +5009,7 @@ getPersonInfo`${person} is ${age} years old`; 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!
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5087,7 +5041,7 @@ The two objects that we are comparing don't have that: the object we passed as a This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5110,7 +5064,7 @@ getAge(21); The rest parameter (`...args`.) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"`
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5135,7 +5089,7 @@ getAge(); 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.
- ↥ back to top + ↥ back to top
## Q. ***What is value of `sum`?*** @@ -5154,7 +5108,7 @@ const sum = eval("10*10+5"); `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`.
- ↥ back to top + ↥ back to top
## Q. ***How long is cool_secret accessible?*** @@ -5175,7 +5129,7 @@ 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5198,7 +5152,7 @@ With the `var` keyword, you can declare multiple variables with the same name. T You cannot do this with `let` or `const` since they're block-scoped.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5225,7 +5179,7 @@ All object keys (excluding Symbols) are strings under the hood, even if you don' 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`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5245,7 +5199,7 @@ console.log(obj); 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.
- ↥ back to top + ↥ back to top
## Q. ***The JavaScript global execution context creates two things for you: the global object, and the "this" keyword.*** @@ -5259,7 +5213,7 @@ If you have two keys with the same name, the key will be replaced. It will still The base execution context is the global execution context: it's What is accessible everywhere in your code.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5281,7 +5235,7 @@ for (let i = 1; i < 5; i++) { The `continue` statement skips an iteration if a certain condition returns `true`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5306,7 +5260,7 @@ name.giveLydiaPizza(); `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!
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5336,7 +5290,7 @@ However, when we stringify an object, it becomes `"[Object object]"`. So what we Then, we log `a[b]`, which is actually `a["Object object"]`. We just set that to `456`, so it returns `456`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5385,7 +5339,7 @@ This is where an event loop starts to work. An **event loop** looks at the stack `bar` gets invoked, `"Second"` gets logged, and it's popped off the stack.
- ↥ back to top + ↥ back to top
## Q. ***What is the event.target when clicking the button?*** @@ -5408,7 +5362,7 @@ This is where an event loop starts to work. An **event loop** looks at the stack The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation`
- ↥ back to top + ↥ back to top
## Q. ***When you click the paragraph, What is the logged output?*** @@ -5429,7 +5383,7 @@ The deepest nested element that caused the event is the target of the event. You If we click `p`, we see two logs: `p` and `div`. During event propagation, there are 3 phases: capturing, target, and bubbling. By default, event handlers are executed in the bubbling phase (unless you set `useCapture` to `true`). It goes from the deepest nested element outwards.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5457,7 +5411,7 @@ With both, we can pass the object to which we want the `this` keyword to refer t `.bind.` returns a _copy_ of the function, but with a bound context! It is not executed immediately.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5482,7 +5436,7 @@ The `sayHi` function returns the returned value of the immediately invoked funct FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`.
- ↥ back to top + ↥ back to top
## Q. ***Which of these values are falsy?*** @@ -5515,7 +5469,7 @@ There are only six falsy values: Function constructors, like `new Number` and `new Boolean` are truthy.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5535,7 +5489,7 @@ console.log(typeof typeof 1); `typeof "number"` returns `"string"`
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5560,7 +5514,7 @@ When you set a value to an element in an array that exceeds the length of the ar depending on where you run it (it's different for every browser, node, etc.)
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5593,7 +5547,7 @@ Later, we set this block-scoped variable equal to `1`, and set the value of the Outside of the `catch` block, `x` is still `undefined`, and `y` is `2`. When we want to `console.log(x)` outside of the `catch` block, it returns `undefined`, and `y` returns `2`.
- ↥ back to top + ↥ back to top
## Q. ***Everything in JavaScript is either a...*** @@ -5612,7 +5566,7 @@ Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string` What differentiates a primitive from an object is that primitives do not have any properties or methods; however, you'll note that `'foo'.toUpperCase()` evaluates to `'FOO'` and does not result in a `TypeError`. This is because when you try to access a property or method on a primitive like a string, JavaScript will implicitly wrap the object using one of the wrapper classes, i.e. `String`, and then immediately discard the wrapper after the expression evaluates. All primitives except for `null` and `undefined` exhibit this behaviour.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5641,7 +5595,7 @@ What differentiates a primitive from an object is that primitives do not have an Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and get `[1, 2, 0, 1, 2, 3]`
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5666,7 +5620,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge `1` is truthy. `!1` returns `false`. `!false` returns `true`.
- ↥ back to top + ↥ back to top
## Q. ***What does the `setInterval` method return in the browser?*** @@ -5685,7 +5639,7 @@ setInterval(() => console.log("Hi"), 1000); It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function.
- ↥ back to top + ↥ back to top
## Q. ***What does this return?*** @@ -5704,7 +5658,7 @@ It returns a unique id. This id can be used to clear that interval with the `cle A string is an iterable. The spread operator maps every character of an iterable to one element.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5735,7 +5689,7 @@ First, we initialize the generator function with `i` equal to `10`. We invoke th Then, we invoke the function again with the `next()` method. It starts to continue where it stopped previously, still with `i` equal to `10`. Now, it encounters the next `yield` keyword, and yields `i * 2`. `i` is equal to `10`, so it returns `10 * 2`, which is `20`. This results in `10, 20`.
- ↥ back to top + ↥ back to top
## Q. ***What does this return?*** @@ -5762,7 +5716,7 @@ Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); When we pass multiple promises to the `Promise.race` method, it resolves/rejects the _first_ promise that resolves/rejects. To the `setTimeout` method, we pass a timer: 500ms for the first promise (`firstPromise`), and 100ms for the second promise (`secondPromise`). This means that the `secondPromise` resolves first with the value of `'two'`. `res` now holds the value of `'two'`, which gets logged.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5797,7 +5751,7 @@ 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5823,7 +5777,7 @@ for (const item in person) { 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5846,7 +5800,7 @@ Operator associativity is the order in which the compiler evaluates the expressi `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"`.
- ↥ back to top + ↥ back to top
## Q. ***What is the value of `num`?*** @@ -5867,7 +5821,7 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco `*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output`?*** @@ -5891,7 +5845,7 @@ When mapping over the array, the value of `num` is equal to the element it’s c 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`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5924,7 +5878,7 @@ The variable `birthYear` has a reference to the value `"1997"`. The argument `ye 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"`
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5958,7 +5912,7 @@ With the `throw` statement, we can create custom errors. With this statement, yo 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'`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -5983,7 +5937,7 @@ console.log(myCar.make); 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"`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6018,7 +5972,7 @@ Then, we declare a variable `x` with the value of `y`, which is `10`. Variables 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"`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6055,7 +6009,7 @@ We can delete properties from objects using the `delete` keyword, also on the pr 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`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6078,7 +6032,7 @@ The `Set` object is a collection of _unique_ values: a value can only occur once 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}`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6110,7 +6064,7 @@ An imported module is _read-only_: you cannot modify the imported module. Only t When we try to increment the value of `myCounter`, it throws an error: `myCounter` is read-only and cannot be modified.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6135,7 +6089,7 @@ The `delete` operator returns a boolean value: `true` on a successful deletion, 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`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6173,7 +6127,7 @@ The value of `a` is now `1`, and the value of `b` is now `2`. What we actually d 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6195,7 +6149,7 @@ console.log(admin); 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 }`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6221,7 +6175,7 @@ With the `defineProperty` method, we can add new properties to an object, or mod 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6251,7 +6205,7 @@ If the replacer is an _array_, only the property names included in the array wil 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6281,7 +6235,7 @@ The unary operator `++` _first returns_ the value of the operand, _then incremen `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`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6315,7 +6269,7 @@ The third time we invoke multiply, we do pass an argument: the object called `va The fourth time, we pass the `value` object again. `x.number` was previously modified to `20`, so `x.number *= 2` logs `40`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6348,7 +6302,7 @@ On the fourth call, we again don't return from the callback function. The accumu ---
- ↥ back to top + ↥ back to top
## Q. ***With which constructor can we successfully extend the `Dog` class?*** @@ -6397,7 +6351,7 @@ With the `super` keyword, we call that parent class's constructor with the given 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6425,7 +6379,7 @@ With the `import` keyword, all imported modules are _pre-parsed_. This means tha 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6446,7 +6400,7 @@ console.log(Symbol("foo") === Symbol("foo")); 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`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6469,7 +6423,7 @@ With the `padStart` method, we can add padding to the beginning of a string. The If the argument passed to the `padStart` method is smaller than the length of the array, no padding will be added.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6488,7 +6442,7 @@ console.log("🥑" + "💻"); With the `+` operator, you can concatenate strings. In this case, we are concatenating the string `"🥑"` with the string `"💻"`, resulting in `"🥑💻"`.
- ↥ back to top + ↥ back to top
## Q. ***How can we log the values that are commented out after the console.log statement?*** @@ -6521,7 +6475,7 @@ Every line is executed, until it finds the first `yield` keyword. There is a `yi 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.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6552,7 +6506,7 @@ With `String.raw`, it would simply ignore the escape and print: In this case, the string is `Hello\nworld`, which gets logged.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6582,7 +6536,7 @@ If we wanted to get access to the resolved value `"I made it"`, we could have us This would've logged `"I made it!"`
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6608,7 +6562,7 @@ The `.push()` method returns the _length_ of the new array! Previously, the arra The `push` method modifies the original array. If you wanted to return the _array_ from the function rather than the _length of the array_, you should have returned `list` after pushing `item` to it.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6638,7 +6592,7 @@ When we create the variable `shape` and set it equal to the frozen object `box`, Since `shape` is frozen, and since the value of `x` is not an object, we cannot modify the property `x`. `x` is still equal to `10`, and `{ x: 10, y: 20 }` gets logged.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6663,7 +6617,7 @@ With `{ name: myName }`, we tell JavaScript that we want to create a new variabl Since we try to log `name`, a variable that is not defined, a ReferenceError gets thrown.
- ↥ back to top + ↥ back to top
## Q. ***Is this a pure function?*** @@ -6684,7 +6638,7 @@ A pure function is a function that _always_ returns the same result, if the same The `sum` function always returns the same result. If we pass `1` and `2`, it will _always_ return `3` without side effects. If we pass `5` and `10`, it will _always_ return `15`, and so on. This is the definition of a pure function.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6727,7 +6681,7 @@ The second time, the `cache` object contains the value that gets returned for `1 The third time, we pass `5 * 2` to the function which gets evaluated to `10`. The `cache` object contains the value that gets returned for `10`. The condition of the if-statement `num in cache` returns `true`, and `'From cache! 20'` gets logged.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6760,7 +6714,7 @@ Where the keys are the enumerable properties. `0` `1` `2` `3` get logged. With a _for-of_ loop, we can iterate over **iterables**. An array is an iterable. When we iterate over the array, the variable "item" is equal to the element it's currently iterating over, `"☕"` ` "💻"` `"🍷"` `"🍫"` get logged.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6782,7 +6736,7 @@ Array elements can hold any value. Numbers, strings, objects, other arrays, null The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, and `1 / 2` returns `0.5`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6811,7 +6765,7 @@ In ES6, we can overwrite this default `undefined` value with default parameters. In this case, if we didn't pass a value or if we passed `undefined`, `name` would always be equal to the string `Lydia`
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6846,7 +6800,7 @@ The value of the `this` keyword is dependent on where you use it. In a **method* With the `call` method, we can change the object to which the `this` keyword refers. In **functions**, the `this` keyword refers to the _the object that the function belongs to_. We declared the `setTimeout` function on the _global object_, so within the `setTimeout` function, the `this` keyword refers to the _global object_. On the global object, there is a variable called _status_ with the value of `"😎"`. When logging `this.status`, `"😎"` gets logged.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6879,7 +6833,7 @@ Then, we set `city` equal to the string `"Amsterdam"`. This doesn't change the p When logging the `person` object, the unmodified object gets returned.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6908,7 +6862,7 @@ console.log(checkAge(21)); Variables with the `const` and `let` keyword are _block-scoped_. A block is anything between curly brackets (`{ }`). In this case, the curly brackets of the if/else statements. You cannot reference a variable outside of the block it's declared in, a ReferenceError gets thrown.
- ↥ back to top + ↥ back to top
## Q. ***What kind of information would get logged?*** @@ -6929,7 +6883,7 @@ fetch("https://www.website.com/api/user/1") The value of `res` in the second `.then` is equal to the returned value of the previous `.then`. You can keep chaining `.then`s like this, where the value is passed to the next handler.
- ↥ back to top + ↥ back to top
## Q. ***Which option is a way to set `hasName` equal to `true`, provided you cannot pass `true` as an argument?*** @@ -6956,7 +6910,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value `name.length` returns the length of the passed argument, not whether it's `true`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -6977,7 +6931,7 @@ In order to get an character on a specific index in a string, you can use bracke Note that this method is not supported in IE7 and below. In that case, use `.charAt()`
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7002,7 +6956,7 @@ You can set a default parameter's value equal to another parameter of the functi If you're trying to set a default parameter's value equal to a parameter which is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7030,7 +6984,7 @@ With the `import * as name` syntax, we import _all exports_ from the `module.js` The `data` object has a `default` property for the default export, other properties have the names of the named exports and their corresponding values.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7064,7 +7018,7 @@ function Person() { Calling a function constructor with `new` results in the creation of an instance of `Person`, `typeof` keyword returns `"object"` for an instance. `typeof member` returns `"object"`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7087,7 +7041,7 @@ The `.push` method returns the _new length_ of the array, not the array itself! Then, we try to use the `.push` method on `newList`. Since `newList` is the numerical value `4`, we cannot use the `.push` method: a TypeError is thrown.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7114,7 +7068,7 @@ console.log(giveLydiaChocolate.prototype); Regular functions, such as the `giveLydiaPizza` function, have a `prototype` property, which is an object (prototype object) with a `constructor` property. Arrow functions however, such as the `giveLydiaChocolate` function, do not have this `prototype` property. `undefined` gets returned when trying to access the `prototype` property using `giveLydiaChocolate.prototype`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7147,7 +7101,7 @@ The first subarray is `[ "name", "Lydia" ]`, with `x` equal to `"name"`, and `y` The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, and `y` equal to `21`, which get logged.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7180,7 +7134,7 @@ getItems(["banana", "apple"], "pear", "orange"); The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]`
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7216,7 +7170,7 @@ a + b; This means that `a + b` is never reached, since a function stops running after the `return` keyword. If no value gets returned, like here, the function returns `undefined`. Note that there is no automatic insertion after `if/else` statements!
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7248,7 +7202,7 @@ console.log(member.name); We can set classes equal to other classes/function constructors. In this case, we set `Person` equal to `AnotherPerson`. The name on this constructor is `Sarah`, so the name property on the new `Person` instance `member` is `"Sarah"`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7274,7 +7228,7 @@ A Symbol is not _enumerable_. The Object.keys method returns all _enumerable_ ke This is one of the many qualities of a symbol: besides representing an entirely unique value (which prevents accidental name collision on objects, for example when working with 2 libraries that want to add properties to the same object), you can also "hide" properties on objects this way (although not entirely. You can still access symbols using the `Object.getOwnPropertySymbols()` method).
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7310,7 +7264,7 @@ The `getUser` function receives an object. With arrow functions, we don't _have_ Since no value gets returned in this case, the function returns `undefined`.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7336,7 +7290,7 @@ SyntaxErrors get thrown when you've written something that isn't valid JavaScrip ReferenceErrors get thrown when JavaScript isn't able to find a reference to a value that you're trying to access.
- ↥ back to top + ↥ back to top
## Q. ***What is the value of output?*** @@ -7360,7 +7314,7 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; `""` is a falsy value. If the left-hand value is falsy, nothing gets returned. `n't` doesn't get returned.
- ↥ back to top + ↥ back to top
## Q. ***What is the value of output?*** @@ -7389,7 +7343,7 @@ With the `||` operator, we can return the first truthy operand. If all values ar `([] || 0 || "")`: the empty array`[]` is a truthy value. This is the first truthy value, which gets returned. `three` is equal to `[]`.
- ↥ back to top + ↥ back to top
## Q. ***What is the value of output?*** @@ -7429,7 +7383,7 @@ With the await keyword in `secondFunction`, we literally pause the execution of This means that it waited for the `myPromise` to resolve with the value `I have resolved`, and only once that happened, we moved to the next line: `second` got logged.
- ↥ back to top + ↥ back to top
## Q. ***What is the value of output?*** @@ -7462,7 +7416,7 @@ However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is `{ name: "Lydia" }` is an object. Neither a number nor an object is a string, so it stringifies both. Whenever we stringify a regular object, it becomes `"[Object object]"`. `"[Object object]"` concatenated with `"2"` becomes `"[Object object]2"`.
- ↥ back to top + ↥ back to top
## Q. ***What is its value?*** @@ -7483,7 +7437,7 @@ We can pass any type of value we want to `Promise.resolve`, either a promise or In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`.
- ↥ back to top + ↥ back to top
## Q. ***What is its value?*** @@ -7518,7 +7472,7 @@ This means that both values have a reference to the same spot in memory, thus th The code block in the `else` statement gets run, and `They are the same!` gets logged.
- ↥ back to top + ↥ back to top
## Q. ***What is its value?*** @@ -7551,7 +7505,7 @@ With dot notation, JavaScript tries to find the property on the object with that JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` and keeps going until it finds the closing bracket `]`. Only then, it will evaluate the statement. If we would've used `colorConfig[colors[1]]`, it would have returned the value of the `red` property on the `colorConfig` object.
- ↥ back to top + ↥ back to top
## Q. ***What is its value?*** @@ -7568,7 +7522,7 @@ console.log("❤️" === "❤️"); Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+2764 U+FE0F"`. These are always the same for the same emojis, so we're comparing two equal strings to each other, which returns true.
- ↥ back to top + ↥ back to top
## Q. ***Which of these methods modifies the original array?*** @@ -7596,7 +7550,7 @@ With `splice` method, we modify the original array by deleting, replacing or add `map`, `filter` and `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7624,7 +7578,7 @@ In JavaScript, primitive data types (everything that's not an object) interact b Then, we change the value of the `favoriteFood` property on the `info` object. The `food` array hasn't changed, since the value of `favoriteFood` was merely a _copy_ of the value of the first element in the array, and doesn't have a reference to the same spot in memory as the element on `food[0]`. When we log food, it's still the original array, `['🍕', '🍫', '🥑', '🍔']`.
- ↥ back to top + ↥ back to top
## Q. ***What does this method do?*** @@ -7657,7 +7611,7 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ```
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7697,7 +7651,7 @@ getName(); // Lydia ```
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7744,7 +7698,7 @@ console.log(two.next().value); // undefined ```
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7763,7 +7717,7 @@ console.log(`${((x) => x)("I love")} to program`); Expressions within template literals are evaluated first. This means that the string will contain the returned value of the expression, the immediately invoked function `(x => x)('I love')` in this case. We pass the value `'I love'` as an argument to the `x => x` arrow function. `x` is equal to `'I love'`, which gets returned. This results in `I love to program`.
- ↥ back to top + ↥ back to top
## Q. ***What will happen?*** @@ -7788,7 +7742,7 @@ config = null; Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. As long as there is a reference, the object won't get garbage collected. Since it's not garbage collected, the `setInterval` callback function will still get invoked every 1000ms (1s).
- ↥ back to top + ↥ back to top
## Q. ***Which method(s) will return the value `'Hello world!'`?*** @@ -7820,7 +7774,7 @@ When adding a key/value pair using the `set` method, the key will be the value o 3 is wrong, since we're creating a new function by passing it as a parameter to the `get` method. Object interact by _reference_. Functions are objects, which is why two functions are never strictly equal, even if they are identical: they have a reference to a different spot in memory.
- ↥ back to top + ↥ back to top
## Q. ***What is the output?*** @@ -7857,7 +7811,7 @@ First, we invoke the `changeAge` function and pass the `person` object as its ar Then, we invoke the `changeAgeAndName` function, however we don't pass a parameter. Instead, the value of `x` is equal to a _new_ object: `{ ...person }`. Since it's a new object, it doesn't affect the values of the properties on the `person` object. `person` is still equal to `{ name: "Lydia", age: 22 }`.
- ↥ back to top + ↥ back to top
## Q. ***Predict the output*** @@ -7869,7 +7823,7 @@ if(2 == false) // returns false ```
- ↥ back to top + ↥ back to top
## Q. ***Being told that an unsorted array contains (n - 1) of n consecutive numbers (where the bounds are defined), find the missing number in O(n) time?*** @@ -7906,7 +7860,7 @@ function findMissingNumber(arrayOfIntegers, upperBound, lowerBound) { ```
- ↥ back to top + ↥ back to top
## Q. ***How will you remove duplicates from an array in JavaScript?*** @@ -7976,7 +7930,7 @@ function uniqueArray(array) { ```
- ↥ back to top + ↥ back to top
## Q. ***Given a string, reverse each word in the sentence*** @@ -7997,7 +7951,7 @@ function reverseBySeparator(string, separator) { ```
- ↥ back to top + ↥ back to top
## Q. ***Implement enqueue and dequeue using only two stacks*** @@ -8029,7 +7983,7 @@ function dequeue(stackInput, stackOutput) { ```
- ↥ back to top + ↥ back to top
## Q. ***How would you use a closure to create a private counter?*** @@ -8060,30 +8014,299 @@ c.retrieve(); // => The counter is currently at: 14 ```
- ↥ back to top + ↥ back to top
## Q. ***How to divide an array in multiple equal parts in JS?*** ```js -function splitArrayIntoChunksOfLen(arr, len) { - let chunks = [], - i = 0, - n = arr.length; +const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +let lenth = 3; + +function split(len) { + while (arr.length > 0) { + console.log(arr.splice(0, len)); + } +} +split(lenth); + +// Output +(3) [1, 2, 3] +(3) [4, 5, 6] +(3) [7, 8, 9] +(1) [10] +``` + +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/split-array-5od3rz)** + +
+ ↥ back to top +
+ +## Q. ***Write a random integers function to print integers with in a range?*** + +**Example:** + +```js +/** + * function to return a random number + * between min and max range + * + * */ +function randomInteger(min, max) { + return Math.floor(Math.random() * (max - min + 1) ) + min; +} +randomInteger(1, 100); // returns a random integer from 1 to 100 +``` + +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-random-integers-yd1cy8?file=/src/index.js)** + +
+ ↥ back to top +
+ +## Q. ***How to convert Decimal to Binary in JavaScript?*** + +**Example 01:** Convert Decimal to Binary + +```js +function DecimalToBinary(number) { + let bin = 0; + let rem, + i = 1; + while (number !== 0) { + rem = number % 2; + number = parseInt(number / 2); + bin = bin + rem * i; + i = i * 10; + } + console.log(`Binary: ${bin}`); +} + +DecimalToBinary(10); +``` + +**Example 02:** Convert Decimal to Binary Using `toString()` + +```js +let val = 10; + +console.log(val.toString(2)); // 1010 ==> Binary Conversion +console.log(val.toString(8)); // 12 ==> Octal Conversion +console.log(val.toString(16)); // A ==> Hexadecimal Conversion +``` + +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-decimal-to-binary-uhyi8t?file=/src/index.js)** + +
+ ↥ back to top +
+ +## Q. ***How do you make first letter of the string in an uppercase?*** + +You can create a function which uses chain of string methods such as charAt, toUpperCase and slice methods to generate a string with first letter in uppercase. + +```js +function capitalizeFirstLetter(string) { + let arr = string.split(" "); + for (var i = 0; i < arr.length; i++) { + arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1); + } + return arr.join(" "); +} + +console.log(capitalizeFirstLetter("hello world")); // Hello World +``` + +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-capitalizefirstletter-dpjhky?file=/src/index.js)** + +
+ ↥ back to top +
+ +## Q. ***Write a function which will test string as a literal and as an object?*** + +The `typeof` operator can be use to test string literal and `instanceof` operator to test String object. + +```js +function check(str) { + if (str instanceof String) { + return "It is an object of string"; + } else { + if (typeof str === "string") { + return "It is a string literal"; + } else { + return "another type"; + } + } +} + +var ltrlStr = "Hi I am string literal"; +var objStr = new String("Hi I am string object"); + +console.log(check(ltrlStr)); // It is a string literal +console.log(check(objStr)); // It is an object of string +``` + +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-literal-vs-object-978dqw?file=/src/index.js)** + +
+ ↥ back to top +
+ +## Q. ***How do you reversing an array?*** + +You can use reverse() method is used reverse the elements in an array. This method is useful to sort an array in descending order. Let us see the usage of reverse() method in an example, + +```js +let numbers = [1, 2, 5, 3, 4]; +numbers.sort((a, b) => b - a); +numbers.reverse(); +console.log(numbers); // [1, 2, 3, 4 ,5] +``` + +
+ ↥ back to top +
+ +## Q. ***How do you find min and max value in an array?*** + +You can use `Math.min` and `Math.max` methods on array variable to find the minimum and maximum elements with in an array. +Let us create two functions to find the min and max value with in an array, + +```js +var marks = [50, 20, 70, 60, 45, 30]; +function findMin(arr) { + return Math.min.apply(null, arr); +} +function findMax(arr) { + return Math.max.apply(null, arr); +} + +console.log(findMin(marks)); +console.log(findMax(marks)); +``` + +
+ ↥ back to top +
+ +## Q. ***How do you find min and max values without Math functions?*** + +You can write functions which loops through an array comparing each value with the lowest value or highest value to find the min and max values. Let us create those functions to find min an max values, + +```js +var marks = [50, 20, 70, 60, 45, 30]; +function findMin(arr) { + var length = arr.length + var min = Infinity; + while (length--) { + if (arr[length] < min) { + min = arr[length]; + } + } + return min; +} + +function findMax(arr) { + var length = arr.length + var max = -Infinity; + while (length--) { + if (arr[length] > max) { + max = arr[length]; + } + } + return max; +} + +console.log(findMin(marks)); +console.log(findMax(marks)); +``` + +
+ ↥ back to top +
+ +## Q. ***Write code for merge two JavaScript Object dynamically?*** + +Let say you have two objects + +```js +const person = { + name: "Tanvi", + age: 28 +}; + +const address = { + addressLine1: "Some Location x", + addressLine2: "Some Location y", + city: "Bangalore" +}; +``` + +Write merge function which will take two object and add all the own property of second object into first object. + +```js +merge(person , address); + +/* Now person should have 5 properties +name , age , addressLine1 , addressLine2 , city */ +``` + +**Method 1: Using ES6, Object.assign method:** + +```js +const merge = (toObj, fromObj) => Object.assign(toObj, fromObj); + +console.log(merge(person, address)); +// {name: "Tanvi", age: 28, addressLine1: "Some Location x", addressLine2: "Some Location y", city: "Bangalore"} +``` + +**Method 2: Without using built-in function:** + +```js +function mergeObject(toObj, fromObj) { + // Make sure both of the parameter is an object + if (typeof toObj === "object" && typeof fromObj === "object") { + for (var pro in fromObj) { + // Assign only own properties not inherited properties + if (fromObj.hasOwnProperty(pro)) { + // Assign property and value + toObj[pro] = fromObj[pro]; + } + } + } else { + throw "Merge function can apply only on object"; + } +} - while (i < n) { - chunks.push(arr.slice(i, (i += len))); +console.log(mergeObject(person, address)); +// {name: "Tanvi", age: 28, addressLine1: "Some Location x", addressLine2: "Some Location y", city: "Bangalore"} +``` + +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-shallow-vs-deep-copy-ik5b7h?file=/src/index.js)** + +## Q. Predict the output + +```js +function find_max(nums) { + let max_num = Number.NEGATIVE_INFINITY; // smaller than all other numbers + for (let num of nums) { + if (num > max_num) { + // (Fill in the missing line here) + } } - return chunks; + return max_num; } -let alphabet = ["a", "b", "c", "d", "e", "f"]; -let alphabetPairs = splitArrayIntoChunksOfLen(alphabet, 2); //split into chunks of two -console.log(alphabetPairs); +// a.) num = max_num +// b.) max_num += 1 +// c.) max_num = num +// d.) max_num += num ``` -**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/splitarrayintochunksoflen-5od3rz?file=/src/index.js:0-345)** +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-code-practice-xjw5n3)**
- ↥ back to top + ↥ back to top