├── function.js ├── .DS_Store ├── declaration.js ├── .vscode └── settings.json ├── closures.js ├── array and String ├── filter.js ├── fib.js ├── prime.js ├── isSorted.js ├── objects.js ├── reverse.js ├── palindrom.js ├── numbers.js ├── balanced.js ├── timeConversion.js ├── object_geeter_setter.js ├── assign.js ├── merge.js ├── string_anagramV2.js ├── isUnique.js ├── debounce.js ├── maxBinary.js ├── logicalOperators.js ├── isRotation_subString.js ├── string.anagram.js ├── questions-02.js ├── arrayDiff.js ├── missing.js ├── subString.js ├── stringCompression.js ├── duplicates_removal.js ├── queue_dequeue.js ├── enqueue_dequeue.js ├── symbol.js ├── flowControl.js ├── capitalize.js ├── balance_expression.js ├── regex.js ├── main.js ├── largest.js ├── mac_occurence.js ├── count.js ├── strings.js ├── common_in_two_array.js ├── isomorphic.js ├── object_compare.js ├── arrays.js ├── Array.prototype.js └── js_test.js ├── questions-02.js ├── callback.js ├── objects.js ├── event-delegation.js ├── debouce.js ├── interview-cake ├── max_multiple_3.js ├── queue.js ├── extend_classes.js └── stack.js ├── questions-01.js ├── async.js ├── scope.js ├── prototype.js ├── object.js ├── syllabus.js ├── prototype_chain.js └── README.md /function.js: -------------------------------------------------------------------------------- 1 | var app = function(){ 2 | consoel.log('hello') 3 | } -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tkssharma/CRACK_JS_INTERVIEWS/HEAD/.DS_Store -------------------------------------------------------------------------------- /declaration.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | var x = 90; 4 | 5 | y = 90; // will be added in global object 6 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "angulardoc.repoId": "c362cc00-8dc9-498b-9b73-57dd72489ec5", 3 | "angulardoc.lastSync": 0 4 | } -------------------------------------------------------------------------------- /closures.js: -------------------------------------------------------------------------------- 1 | 2 | function add(x){ 3 | return function(y){ 4 | return x+y; 5 | } 6 | } 7 | var addition = add(5); 8 | addition(6); 9 | -------------------------------------------------------------------------------- /array and String/filter.js: -------------------------------------------------------------------------------- 1 | function filter(arr,fn){ 2 | var out = []; 3 | for(var i =0; i< arr.length ; i++){ 4 | if(fn(arr[i])){ 5 | out.push(arr[i]) 6 | } 7 | } 8 | return out; 9 | } -------------------------------------------------------------------------------- /array and String/fib.js: -------------------------------------------------------------------------------- 1 | function Fib(n){ 2 | if(n === 0 ){ 3 | return 0; 4 | } 5 | else if (n === 1){ 6 | return 1; 7 | } 8 | else { 9 | return Fib(n-1) + Fib(n-2); 10 | } 11 | } -------------------------------------------------------------------------------- /array and String/prime.js: -------------------------------------------------------------------------------- 1 | // check if given number is prime or not // 2 | function isPrime(n){ 3 | var _isPrime = n != 0; 4 | for(i=2 ; i < n ; i++){ 5 | if(n%1 === 0){ 6 | _isPrime = false; 7 | } 8 | } 9 | return _isPrime; 10 | } -------------------------------------------------------------------------------- /questions-02.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | What is the difference between apply, call, and bind? 4 | What is event delegation? 5 | What is event bubbling? 6 | What is hoisting and how does it work? 7 | What is the prototype chain? 8 | What determines the value of ‘this’? 9 | What is the event loop? 10 | Implement curry. 11 | -------------------------------------------------------------------------------- /array and String/isSorted.js: -------------------------------------------------------------------------------- 1 | function isSorted(array) { 2 | for (let i = 0; i < array.length; i++) { 3 | let current = array[i] 4 | let next = array[i + 1] 5 | if (next && current > next) { 6 | // exit as soon as we know the array isn't sorted 7 | return false 8 | } 9 | } 10 | return true 11 | }isSorted -------------------------------------------------------------------------------- /array and String/objects.js: -------------------------------------------------------------------------------- 1 | // remove duplicate from array 2 | 3 | function removeDups(arr){ 4 | var exists = {}; 5 | var out =[]; 6 | var elm 7 | 8 | for(var i =0;i 0){ 4 | tmp [j++] = atr [i--] 5 | } 6 | return tmp; 7 | 8 | // another best solution 9 | function reverseM2(){ 10 | var result = ''; 11 | var index = str.length -1; 12 | if(i >= 0 ){ 13 | result + = str[index]; 14 | index -- ; 15 | } 16 | return result 17 | } -------------------------------------------------------------------------------- /callback.js: -------------------------------------------------------------------------------- 1 | 2 | function getInput(options, fn) { 3 | // 2 sec 4 | // async task 5 | // Make sure the callback is a function​ 6 | if (typeof fn === "function") { 7 | // Call it, since we have confirmed it is callable​ 8 | fn(data); 9 | } 10 | } 11 | 12 | getInput({x:90},function(data){ 13 | console.log(data) 14 | }) 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /objects.js: -------------------------------------------------------------------------------- 1 | var obj = {t : 90}; 2 | undefined 3 | var obj2 = obj 4 | undefined 5 | obj === obj2 6 | true 7 | //obj,obj2 =====> mem location => t = 90 8 | undefined 9 | obj = null; 10 | null 11 | obj2 12 | {t: 90} 13 | //--------------------------// 14 | undefined 15 | var obj1 = {t : 90}; 16 | undefined 17 | var obj2 = Object.create(obj1); 18 | undefined 19 | obj1 === obj2 20 | false -------------------------------------------------------------------------------- /array and String/palindrom.js: -------------------------------------------------------------------------------- 1 | function isPalindrom(str){ 2 | return str === reverse(str); 3 | } 4 | // split revserse and join that's all 5 | function reverse(str){ 6 | return str.split('').reverse().join(''); 7 | } 8 | 9 | // we have rev for sentence // 10 | function rev(text){ 11 | return text.split(' ').reverse().join(' ') 12 | } 13 | //text.split('').reverse().join('') 14 | //"nurat si eman ym olleh" -------------------------------------------------------------------------------- /array and String/numbers.js: -------------------------------------------------------------------------------- 1 | exports = typeof window === 'undefined' ? global : window; 2 | 3 | exports.numbersAnswers = { 4 | valueAtBit: function(num, bit) { 5 | 6 | }, 7 | 8 | base10: function(str) { 9 | 10 | }, 11 | 12 | convertToBinary: function(num) { 13 | return num.toString(2); 14 | }, 15 | 16 | multiply: function(a, b) { 17 | var c = a * b; 18 | return c; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /event-delegation.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('DOMContentLoaded', function() { 2 | 3 | let app = document.getElementById('todo-app'); 4 | 5 | // attach event listener to whole container 6 | app.addEventListener('click', function(e) { 7 | if (e.target && e.target.nodeName === 'LI') { 8 | let item = e.target; 9 | alert('you clicked on item: ' + item.innerHTML); 10 | } 11 | }); 12 | 13 | }); 14 | -------------------------------------------------------------------------------- /array and String/balanced.js: -------------------------------------------------------------------------------- 1 | /// solution 2 | 3 | function isBalanced(string) { 4 | let count = 0 5 | for (let letter of string) { 6 | if (letter === '{') { 7 | count++ 8 | } 9 | if (letter === '}') { 10 | count-- 11 | 12 | // if a closing bracket doesn't have a matching 13 | // opening bracket, we should return early. 14 | if (count < 0) { 15 | return false 16 | } 17 | 18 | } 19 | } 20 | return count === 0 21 | } -------------------------------------------------------------------------------- /array and String/timeConversion.js: -------------------------------------------------------------------------------- 1 | function convertToMilitaryHours(time) { 2 | var hours = parseInt(time.substr(0, 2)); 3 | if(time.indexOf('am') != -1 && hours == 12) { 4 | time = time.replace('12', '0'); 5 | } 6 | if(time.indexOf('pm') != -1 && hours < 12) { 7 | time = time.replace(hours, (hours + 12)); 8 | } 9 | return time.replace(/(am|pm)/, ''); 10 | } 11 | 12 | // convertTo24Hour('2:30 pm') 13 | // "14:30 " 14 | // convertTo24Hour('3:30 pm') 15 | // "15:30 " 16 | -------------------------------------------------------------------------------- /debouce.js: -------------------------------------------------------------------------------- 1 | function debouce(fn, delay){ 2 | var timer = null 3 | return function(){ 4 | let content = this; 5 | var args = arguments; 6 | clearTimeout(timer); 7 | timer = setTimeout(()=>{ 8 | fn.apply(this,arguments) 9 | },delay) 10 | } 11 | } 12 | // function to be called when user scrolls 13 | function foo() { 14 | console.log('You are scrolling!'); 15 | } 16 | var app = document.getElementsByTagName('app'); 17 | app.addEventListener('click', debouce(fn,200)); 18 | -------------------------------------------------------------------------------- /array and String/object_geeter_setter.js: -------------------------------------------------------------------------------- 1 | var debitBalance = { 2 | 3 | balance : 3000, 4 | get getBalance() 5 | { 6 | return this.balance 7 | }, 8 | 9 | set setBalance(balance) 10 | { 11 | if(balance > 0){ 12 | this.balance = balance; 13 | } 14 | } 15 | }; 16 | 17 | //debitBalance.balance 18 | //3000 19 | //debitBalance.balance = 900; 20 | //900 21 | //debitBalance.balance 22 | //900 23 | -------------------------------------------------------------------------------- /interview-cake/max_multiple_3.js: -------------------------------------------------------------------------------- 1 | in array of integers of size n */ 2 | int maxProduct(int arr[], int n) 3 | { 4 | // if size is less than 3, no triplet exists 5 | if (n < 3) 6 | return -1; 7 | 8 | // will contain max product 9 | int max_product = INT_MIN; 10 | 11 | for (int i = 0; i < n - 2; i++) 12 | for (int j = i + 1; j < n - 1; j++) 13 | for (int k = j + 1; k < n; k++) 14 | max_product = max(max_product, 15 | arr[i] * arr[j] * arr[k]); 16 | 17 | return max_product; 18 | } 19 | -------------------------------------------------------------------------------- /array and String/assign.js: -------------------------------------------------------------------------------- 1 | 2 | function assignDeep(target, ...sources) { 3 | for (let source of sources) { 4 | for (let key in source) { 5 | if (isObject(source[key])) { 6 | if (!isObject(target[key])) { 7 | target[key] = {} 8 | } 9 | assignDeep(target[key], source[key]) 10 | } else { 11 | target[key] = source[key] 12 | } 13 | } 14 | } 15 | return target 16 | } 17 | 18 | function isObject(a) { 19 | return typeof a === 'object' && a !== null 20 | } -------------------------------------------------------------------------------- /array and String/merge.js: -------------------------------------------------------------------------------- 1 | ([1,2,3,5,6,7]) 2 | i => 0 to n-1 3 | j => i+1 to n 4 | 5 | function topSum(arr){ 6 | var biggest = arr [0]; 7 | second = arr[1]; 8 | len = arr.length; 9 | i= 2; 10 | if(len < 2){return null;} 11 | 12 | if(bigget < second ){ 13 | biggest = arr[1]; 14 | second = arr[0] 15 | } 16 | for(;i< len ; i++){ 17 | if(arr[i] > biggest){ 18 | second = boggest ; 19 | biggest = arr[i]; 20 | }else if(arr[i] > second){ 21 | second = arr[i]; 22 | } 23 | } 24 | return biggest + second; 25 | } -------------------------------------------------------------------------------- /array and String/string_anagramV2.js: -------------------------------------------------------------------------------- 1 | function areAnagrams(str1,str2) { 2 | if (str1.length !== str2.length) return false; 3 | var str1Chars = str1.split('').sort(); //get sorted characters of the strings 4 | var str2Chars = str2.split('').sort(); 5 | var isAnagram = true; 6 | str1Chars.forEach(function (curChar, index) { 7 | if (str2Chars[index] !== curChar) { //every array position should be equal if the strings are anagrams 8 | isAnagram = false; 9 | return; 10 | } 11 | }); 12 | return isAnagram; 13 | } 14 | -------------------------------------------------------------------------------- /array and String/isUnique.js: -------------------------------------------------------------------------------- 1 | // check for duplication in array 2 | [1,2,3,4,5,1,2,3]; 3 | function checkUnique(arr){ 4 | var map = {},i; 5 | for(var i = 0; i digit2) { 14 | return _binary1st 15 | }else{ 16 | return _binary2nd 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /array and String/logicalOperators.js: -------------------------------------------------------------------------------- 1 | exports = typeof window === 'undefined' ? global : window; 2 | 3 | exports.logicalOperatorsAnswers = { 4 | or: function(a, b) { 5 | if(a == b || a % b == 0) { 6 | console.log("this is or logical operator true part"); 7 | } 8 | else { 9 | console.log("this is the false part"); 10 | } 11 | }, 12 | 13 | and: function(a, b) { 14 | if(a == b && a % b == 0) { 15 | console.log("both condition are true"); 16 | } else { 17 | console.log("This is the second part when the condition is not true"); 18 | } 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /questions-01.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | What is the event loop? Can you draw a simple diagram to explain event loop? 4 | How to you explain closure? 5 | How would you make sure value of this works correctly inside setTimeout? 6 | What are the different possible values for this? 7 | What is debounce and how could you implement debounce? 8 | How would you communicate with server 9 | Explain Promise to your grandmother 10 | If and website is slow how what would you do to make it faster? 11 | What ES6 feature do you use other than let, var and arrow? 12 | What build tool you use and tell me some advantages to use that build tool -------------------------------------------------------------------------------- /array and String/isRotation_subString.js: -------------------------------------------------------------------------------- 1 | /* 2 | Problem: Assume you have a method isSubstring which checks if one word is a substring 3 | of another. Given two strings, si and s2, write code to check Ifs2 is a rotation of si 4 | using only onecalltoisSubstring (e.g., "waterbottLe" is a rotation of "erbottLewat"). 5 | */ 6 | 7 | function isRotation(str1, str2) { //determines whether str2 is a rotation of str1 8 | if (str1.length !== str2.length || !str1.length) 9 | return false; //strings must be of equal length and str1 should not be empty 10 | var str1Twice = str1 + str1; 11 | return isSubstring(str1twice, str2); 12 | } 13 | -------------------------------------------------------------------------------- /array and String/string.anagram.js: -------------------------------------------------------------------------------- 1 | //Given two strings, return true if they are anagrams of one another "Mary" is an anagram of "Army" 2 | 3 | var firstWord = "Mary"; 4 | var secondWord = "Army"; 5 | 6 | isAnagram(firstWord, secondWord); // true 7 | 8 | function isAnagram(first, second) { 9 | // For case insensitivity, change both words to lowercase. 10 | var a = first.toLowerCase(); 11 | var b = second.toLowerCase(); 12 | 13 | // Sort the strings, and join the resulting array to a string. Compare the results 14 | a = a.split("").sort().join(""); 15 | b = b.split("").sort().join(""); 16 | 17 | return a === b; 18 | } 19 | -------------------------------------------------------------------------------- /array and String/questions-02.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | What is the event loop? Can you draw a simple diagram to explain event loop? 4 | How to you explain closure? 5 | How would you make sure value of this works correctly inside setTimeout? 6 | What are the different possible values for this? 7 | What is debounce and how could you implement debounce? 8 | How would you communicate with server 9 | Explain Promise to your grandmother 10 | If and website is slow how what would you do to make it faster? 11 | What ES6 feature do you use other than let, var and arrow? 12 | What build tool you use and tell me some advantages to use that build toolquestions-02.js -------------------------------------------------------------------------------- /array and String/arrayDiff.js: -------------------------------------------------------------------------------- 1 | function diffFromArray(array1,array2){ 2 | var map = {}; 3 | var out = []; 4 | if(array1.length == 0 || array2.length === 0 ){ 5 | return null 6 | }; 7 | array1.forEach(function(element){ 8 | map[element] = 1; 9 | }); 10 | array2.forEach(function(element){ 11 | if(map[element] === 1){ 12 | // do nothing we are good here element exist in both array 13 | }else{ 14 | out.push(element) 15 | } 16 | }); 17 | return out; 18 | } 19 | 20 | //diffFromArray([1,2,3],[7,2,4,5,6,7]); 21 | //(5) [7, 4, 5, 6, 7] 22 | //diffFromArray([1,2,3],[1,2,4,5,3]); 23 | //(2) [4, 5] 24 | -------------------------------------------------------------------------------- /array and String/missing.js: -------------------------------------------------------------------------------- 1 | /// solution 2 | 3 | function missing(array) { 4 | 5 | // sum the array, and keep track of the maximum number in it 6 | let max = array[0] 7 | let sum = 0 8 | array.forEach(number => { 9 | sum += number 10 | if (number > max) { 11 | max = number 12 | } 13 | }) 14 | 15 | // the maximum tells us how long the array should be. 16 | // we plug it into the formula to sum a series to see 17 | // what we should expect the sum to be. 18 | let expectedSum = max * (max + 1) / 2 19 | let difference = expectedSum - sum 20 | 21 | if (difference > 0) { 22 | return difference 23 | } else { 24 | return undefined 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /array and String/subString.js: -------------------------------------------------------------------------------- 1 | function subStringFinder(str, subStr){ 2 | var idx = 0, 3 | i = 0, 4 | j = 0, 5 | len = str.length, 6 | subLen = subStr.length; 7 | 8 | for(; i subStringFinder('abbcdabbbbbck', 'ab') 26 | = 0 27 | > subStringFinder('abbcdabbbbbck', 'bck') 28 | = 9 29 | 30 | //doesn't work for this one. 31 | > subStringFinder('abbcdabbbbbck', 'bbbck') 32 | = -1 33 | 34 | -------------------------------------------------------------------------------- /array and String/stringCompression.js: -------------------------------------------------------------------------------- 1 | /* 2 | Problem: Implement a method to perform basic string compression using the counts of 3 | repeated characters. For example, the string aabcccccaaa would become 4 | a2blc5a3. If the "compressed" string would not become smaller than the original 5 | string, your method should return the original string. 6 | */ 7 | 8 | function stringCompression(str) { 9 | var compressedString = ''; 10 | for (var i = 0; i < str.length; i++) { 11 | var curLetter = str[i]; 12 | var curCount = 1; 13 | while (str[i+1] === curLetter) { 14 | curCount++; 15 | i++; 16 | } 17 | compressedString += curLetter + curCount; 18 | } 19 | if (compressedString.length > str.length) return str; 20 | return compressedString; 21 | } 22 | -------------------------------------------------------------------------------- /async.js: -------------------------------------------------------------------------------- 1 | function findIfDigitIsPresent(thisNumber) { 2 | var DIGIT_TO_FIND = 4; 3 | console.log(thisNumber); 4 | while (thisNumber !== 0) { 5 | 6 | console.log(thisNumber); 7 | 8 | var thisDigit = thisNumber % 10; 9 | thisNumber = thisNumber / 10; 10 | 11 | if (thisDigit === DIGIT_TO_FIND) { 12 | return true; 13 | } 14 | } 15 | return false; 16 | } 17 | 18 | 19 | function odoMeter() { 20 | var NUMBER = 56287; 21 | var increment = 0; 22 | for(var i = 1; i <= NUMBER; i++) { 23 | 24 | (function (i) { 25 | setTimeout(function () { 26 | var tmp = findIfDigitIsPresent(i); 27 | if(tmp) { 28 | increment = increment + 1; 29 | } 30 | }, 0); 31 | })(i); 32 | } 33 | console.log(NUMBER - increment) 34 | } 35 | odoMeter(); 36 | -------------------------------------------------------------------------------- /array and String/duplicates_removal.js: -------------------------------------------------------------------------------- 1 | Removing duplicates of an array and returning an array of only unique elements 2 | // ES6 Implementation 3 | var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8]; 4 | Array.from(new Set(array)); // [1, 2, 3, 5, 9, 8] 5 | // done with set in ES6 as it will not allow duplicates in array 6 | 7 | 8 | // ES5 Implementation 9 | var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8]; 10 | 11 | uniqueArray(array); // [1, 2, 3, 5, 9, 8] 12 | 13 | function uniqueArray(array) { 14 | var hashmap = {}; 15 | var unique = []; 16 | 17 | for(var i = 0; i < array.length; i++) { 18 | // If key returns undefined (unique), it is evaluated as false. 19 | if(!hashmap.hasOwnProperty(array[i])) { 20 | hashmap[array[i]] = 1; 21 | unique.push(array[i]); 22 | } 23 | } 24 | 25 | return unique; 26 | } 27 | -------------------------------------------------------------------------------- /array and String/queue_dequeue.js: -------------------------------------------------------------------------------- 1 | Implement enqueue and dequeue using only two stacks 2 | var inputStack = []; // First stack 3 | var outputStack = []; // Second stack 4 | 5 | // For enqueue, just push the item into the first stack 6 | function enqueue(stackInput, item) { 7 | return stackInput.push(item); 8 | } 9 | 10 | function dequeue(stackInput, stackOutput) { 11 | // Reverse the stack such that the first element of the output stack is the 12 | // last element of the input stack. After that, pop the top of the output to 13 | // get the first element that was ever pushed into the input stack 14 | if (stackOutput.length <= 0) { 15 | while(stackInput.length > 0) { 16 | var elementToOutput = stackInput.pop(); 17 | stackOutput.push(elementToOutput); 18 | } 19 | } 20 | 21 | return stackOutput.pop(); 22 | } 23 | -------------------------------------------------------------------------------- /array and String/enqueue_dequeue.js: -------------------------------------------------------------------------------- 1 | // Implement enqueue and dequeue using only two stacks 2 | 3 | var inputStack = []; // First stack 4 | var outputStack = []; // Second stack 5 | 6 | // For enqueue, just push the item into the first stack 7 | function enqueue(stackInput, item) { 8 | return stackInput.push(item); 9 | } 10 | 11 | function dequeue(stackInput, stackOutput) { 12 | // Reverse the stack such that the first element of the output stack is the 13 | // last element of the input stack. After that, pop the top of the output to 14 | // get the first element that was ever pushed into the input stack 15 | if (stackOutput.length <= 0) { 16 | while(stackInput.length > 0) { 17 | var elementToOutput = stackInput.pop(); 18 | stackOutput.push(elementToOutput); 19 | } 20 | } 21 | 22 | return stackOutput.pop(); 23 | } 24 | -------------------------------------------------------------------------------- /array and String/symbol.js: -------------------------------------------------------------------------------- 1 | function SimpleSymbols(str) { 2 | 3 | // pad the strings so that if a character exists at the beginning 4 | // of the string for example, we don't get on out-of-bounds error by 5 | // trying to get the character before it 6 | var str = '=' + str + '='; 7 | 8 | // loop through entire string 9 | for (var i = 0; i < str.length; i++) { 10 | 11 | // check to see if current character is an alphabetic character 12 | // by using a simple case-insensitive regex pattern 13 | if (str[i].match(/[a-z]/i) !== null) { 14 | 15 | // check to see if a + symbol is to the left and right 16 | // if not, then we know this string is not valid 17 | if (str[i-1] !== '+' || str[i+1] !== '+') { 18 | return false; 19 | } 20 | 21 | } 22 | 23 | } 24 | 25 | return true; 26 | 27 | } -------------------------------------------------------------------------------- /array and String/flowControl.js: -------------------------------------------------------------------------------- 1 | exports = typeof window === 'undefined' ? global : window; 2 | 3 | exports.flowControlAnswers = { 4 | fizzBuzz: function(num) { 5 | // write a function that receives a number as its argument; 6 | // if the number is divisible by 3, the function should return 'fizz'; 7 | // if the number is divisible by 5, the function should return 'buzz'; 8 | // if the number is divisible by 3 and 5, the function should return 9 | // 'fizzbuzz'; 10 | // 11 | // otherwise the function should return the number, or false if no number 12 | // was provided or the value provided is not a number 13 | if(num%3 == 0 && num%5 ==0 ) { 14 | console.log("fizzBuzz"); 15 | } else if (num % 3 == 0 ) { 16 | console.log("fizz"); 17 | } else if (num%5 == 0) { 18 | console.log("buzz"); 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /array and String/capitalize.js: -------------------------------------------------------------------------------- 1 | function LetterChanges(str) { 2 | 3 | // we will replace every letter in the string with the letter following it 4 | // by first getting the charCode number of the letter, adding 1 to it, then 5 | // converting this new charCode number to a letter using the fromCharCode function 6 | // we also check to see if the character is z and if so we simply convert the z to an a 7 | var converted = str.replace(/[a-z]/gi, function(char) { 8 | return (char === 'z' || char === 'Z') ? 'a' : String.fromCharCode(char.charCodeAt() + 1); 9 | }); 10 | 11 | // we have now successfully converted each letter to the letter following it 12 | // in the alphabet, and all we need to do now is capitalize the vowels 13 | var capitalized = converted.replace(/a|e|i|o|u/gi, function(vowel) { 14 | return vowel.toUpperCase(); 15 | }); 16 | 17 | // return the final string 18 | return capitalized; 19 | 20 | } -------------------------------------------------------------------------------- /array and String/balance_expression.js: -------------------------------------------------------------------------------- 1 | 2 | // check if expression is balanced or not !! 3 | var expression = "{{}}{}{}" 4 | var expressionFalse = "{}{{}"; 5 | 6 | isBalanced(expression); // true 7 | isBalanced(expressionFalse); // false 8 | isBalanced(""); // true 9 | 10 | function isBalanced(expression) { 11 | var checkString = expression; 12 | var stack = []; 13 | 14 | // If empty, parentheses are technically balanced 15 | if (checkString.length <= 0) return true; 16 | 17 | for (var i = 0; i < checkString.length; i++) { 18 | if(checkString[i] === '{') { 19 | stack.push(checkString[i]); 20 | } else if (checkString[i] === '}') { 21 | // Pop on an empty array is undefined 22 | if (stack.length > 0) { 23 | stack.pop(); 24 | } else { 25 | return false; 26 | } 27 | } 28 | } 29 | 30 | // If the array is not empty, it is not balanced 31 | if (stack.pop()) return false; 32 | return true; 33 | } 34 | -------------------------------------------------------------------------------- /scope.js: -------------------------------------------------------------------------------- 1 | 2 | var x = 90; 3 | 4 | function hello(){ 5 | 6 | var x = 100; 7 | console.log(x); 8 | 9 | 10 | } 11 | hello() 12 | // check value in scope of function first 13 | // check value outside or in global scope 14 | 15 | //-----------------------------------------// 16 | 17 | function hello(){ 18 | var x = 100; 19 | // function level scope 20 | if(true){ 21 | x =80; 22 | } 23 | // console.log(x); 24 | // x will be 80 here 25 | } 26 | //----------------------------------// 27 | function hello(){// 28 | console.log(x); 29 | // undefined 30 | // function level scope 31 | // console.log(x); 32 | // x will be 80 here 33 | // hoisting of variables 34 | var x = 70; 35 | } 36 | //------------------------------------// 37 | var x = 90 ; 38 | function hello(){ // i know i have x inside me 39 | console.log(x); // ?? // x === 90 40 | 41 | var x = 70; // function also have same variable 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /array and String/regex.js: -------------------------------------------------------------------------------- 1 | exports = typeof window === 'undefined' ? global : window; 2 | 3 | exports.regexAnswers = { 4 | containsNumber: function(str) { 5 | var number = /\d+/g; 6 | var t = str.match(number); 7 | if(t != null) { 8 | console.log('Contain number'); 9 | } else { 10 | console.log("there is no number exit"); 11 | } 12 | }, 13 | 14 | containsRepeatingLetter: function(str) { 15 | var regx = /([a-zA-Z]).*?\1/; 16 | var repeatletter = str.match(regx); 17 | console.log(repeatletter); 18 | 19 | }, 20 | 21 | endsWithVowel: function(str) { 22 | var vowel = ['a','e','i','o','u']; 23 | for(i = 0; i < vowel.length; i++) { 24 | var t = str.endsWith(vowel[i]); 25 | if(t == true) { 26 | console.log(t); 27 | } 28 | } 29 | }, 30 | 31 | captureThreeNumbers: function(str) { 32 | 33 | }, 34 | 35 | matchesPattern: function(str) { 36 | 37 | }, 38 | 39 | isUSD: function(str) { 40 | 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /array and String/main.js: -------------------------------------------------------------------------------- 1 | |||===========BASIC INTERVIEW QUESTIONS==========||| 2 | 3 | What is Big O notation, and why is it useful? 4 | What is the DOM? 5 | What is the event loop? 6 | What is a closure? 7 | How does prototypal inheritance work, and how is it different from classical inheritance? (this is not a useful question IMO, but a lot of people like to ask it) 8 | How does this work? 9 | 10 | What is event bubbling and how does it work? (this is also a bad question IMO, but a lot of people like to ask it too) 11 | Describe a few ways to communicate between a server and a client. Describe how a few network protocols work at a high level (IP, TCP, HTTP/S/2, UDP, RTC, DNS, etc.) 12 | 13 | What is REST, and why do people use it? 14 | 15 | My website is slow. Walk me through diagnosing and fixing it. What are some performance optimizations people use, and when should they be used? 16 | What frameworks have you used? What are the pros and cons of each? Why do people use frameworks? What kinds of problems do frameworks solve? -------------------------------------------------------------------------------- /array and String/largest.js: -------------------------------------------------------------------------------- 1 | function LongestWord(sen) { 2 | 3 | // we use the regex match function which searches the string for the 4 | // pattern and returns an array of strings it finds 5 | // in our case the pattern we define below returns words with 6 | // only the characters a through z and 0 through 9, stripping away punctuation 7 | // e.g. "hello$% ##all" becomes [hello, all] 8 | var arr = sen.match(/[a-z0-9]+/gi); 9 | 10 | // the array sort function takes a function as a parameter 11 | // which is used to compare each element in the array to the 12 | // next element in the array 13 | var sorted = arr.sort(function(a, b) { 14 | return b.length - a.length; 15 | }); 16 | 17 | // this array now contains all the words in the original 18 | // string but in order from longest to shortest length 19 | // so we simply return the first element 20 | return sorted[0]; 21 | 22 | } 23 | 24 | // keep this function call here 25 | LongestWord(readline()); 26 | -------------------------------------------------------------------------------- /array and String/mac_occurence.js: -------------------------------------------------------------------------------- 1 | function getMaxOccurence(string) 2 | { 3 | // get array from string first remove spaces from it 4 | var string = string.replace(/ /g,'') 5 | var array = string.split(''); 6 | // check array length 7 | if(array.length == 0) 8 | return null; 9 | 10 | // create hash map to see if elemnt exist or not if exist then increase its counter 11 | var hashMap = {}; 12 | var maxChar = array[0], maxCount = 1; 13 | // loop on array for iteration 14 | for(var i = 0; i < array.length; i++) 15 | { 16 | var element = array[i]; 17 | if(hashMap[element] == null) 18 | // its new elemnt add its value to 1 in map 19 | hashMap[element] = 1; 20 | else 21 | // its existing increase value by 1 22 | hashMap[element]++; 23 | // now finally if value is > max count we got new elemnt with max occurence 24 | if(hashMap[element] > maxCount) 25 | { 26 | maxChar = element; 27 | maxCount = hashMap[element]; 28 | } 29 | } 30 | return maxChar; 31 | } 32 | -------------------------------------------------------------------------------- /interview-cake/queue.js: -------------------------------------------------------------------------------- 1 | // Queue class 2 | class Queue 3 | { 4 | // Array is used to implement a Queue 5 | constructor(){ 6 | this.items = []; 7 | } 8 | // Functions to be implemented enqueue(item) dequeue() front() isEmpty() 9 | // printQueue() enqueue function 10 | enqueue(element){ 11 | // adding element to the queue 12 | this 13 | .items 14 | .push(element); 15 | } 16 | // dequeue function 17 | dequeue(){ 18 | // removing element from the queue returns underflow when called on empty queue 19 | if (this.isEmpty()) 20 | return "Underflow"; 21 | return this 22 | .items 23 | .shift(); 24 | } 25 | // front function 26 | front(){ 27 | // returns the Front element of the queue without removing it. 28 | if (this.isEmpty()) 29 | return "No elements in Queue"; 30 | return this.items[0]; 31 | } 32 | // isEmpty function 33 | isEmpty(){ 34 | // return true if the queue is empty. 35 | return this.items.length == 0; 36 | } 37 | // printQueue function 38 | printQueue(){ 39 | var str = ""; 40 | for (var i = 0; i < this.items.length; i++) 41 | str += this.items[i] + " "; 42 | return str; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /interview-cake/extend_classes.js: -------------------------------------------------------------------------------- 1 | // Define a Person class 2 | // It will as a Base class 3 | // in the inheritance hirarechy 4 | class Person { 5 | // Initializing the name 6 | constructor(name) { 7 | this.name = name;; 8 | } 9 | 10 | // toString method returns the name 11 | toString_Person() { 12 | return "Name of person = " + this.name; 13 | } 14 | } 15 | 16 | // Defining the student class 17 | // It is the derived class 18 | // It extends Person 19 | class Student extends Person { 20 | // Initializing the name and id 21 | constructor(name, Sid) { 22 | // calling the super class constructor 23 | super(name); 24 | 25 | // Initializing Sid 26 | this.Sid = Sid; 27 | } 28 | 29 | // toString method retuns the student detail 30 | // Overriding the toString method from base 31 | // class 32 | toString_Student() { 33 | // Calling the toString method of the base 34 | // class to get the name 35 | return super.toString_Person() + ", Student Id = " 36 | + this.Sid 37 | } 38 | } 39 | 40 | // creating Object 41 | var Student_1 = new Student("Sumit", "GFG_123"); 42 | 43 | // Printing the name and Sid of Student_1 44 | console.log(Student_1.toString()); -------------------------------------------------------------------------------- /array and String/count.js: -------------------------------------------------------------------------------- 1 | exports = typeof window === 'undefined' ? global : window; 2 | 3 | exports.countAnswers = { 4 | countCharinString: function (str) { 5 | str.length; 6 | return str; 7 | }, 8 | removeRepeatedCharInString : function(str){ 9 | // "hellotarun" => helotrun 10 | // remove duplicates 11 | var repSring = ""; 12 | for(var i = 0; i < str.length; i++) { 13 | if(repSring.indexOf(str[i]) < 0) { 14 | repSring += str[i]; 15 | } 16 | } 17 | return repSring; 18 | }, 19 | compareTwoString : function(str1,str2){ 20 | // write code for it 21 | // "hello" & hello are equal return true 22 | // hello & olleh not equal return false 23 | var compareTwoString = str1.localeCompare(str2); 24 | if (compareTwoString == 0) { 25 | console.log("true"); 26 | } else { 27 | console.log("false"); 28 | } 29 | }, 30 | checkSubString : function(str1,str2){ 31 | // check if str1 is subString of str2 32 | var t = str1.includes(str2); 33 | return t; 34 | }, 35 | checkPalindrom : function(str1,str2){ 36 | // check if str1,str2 are palindrom 37 | }, 38 | stringReverse : function(str){ 39 | retutn str.split('').reverse().join(''); 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /array and String/strings.js: -------------------------------------------------------------------------------- 1 | exports = typeof window === 'undefind' ? global : window; 2 | exports.stringAnwsers = { 3 | compress: function(str) { 4 | var createObj = {}; 5 | var saveRepeat = []; 6 | var compressedString = []; 7 | for(i=0;i <= str.length; i++) { 8 | var l = str.charAt(i); 9 | createObj[l] = (isNaN (createObj[l]) ? 1 : createObj[l] + 1); 10 | 11 | } 12 | for (var key in createObj) { 13 | saveRepeat.push(new Array(createObj[key]+1).join(key)); 14 | } 15 | //console.log(repeat.length); 16 | for(j = 0; j < saveRepeat.length ;j++) { 17 | var getLength = saveRepeat[j].length; 18 | var firstChar = saveRepeat[j].charAt(0); 19 | var compressStr = firstChar+getLength; 20 | compressedString.push(compressStr); 21 | } 22 | compressedString.pop(); 23 | console.log(compressedString.join("")); 24 | }, 25 | wordWrap: function(str , cols) { 26 | var re = /.{1,20}/g; 27 | var breakString = str.match(re); 28 | //console.log(breakString); 29 | if(cols <= 1) { 30 | console.log(str); 31 | } else { 32 | for(i = 0; i < breakString.length; i++ ) { 33 | console.log(breakString[i]); 34 | } 35 | } 36 | }, 37 | reverseString: function (str) { 38 | return str.split("").reverse().join(""); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /array and String/common_in_two_array.js: -------------------------------------------------------------------------------- 1 | //Find the intersection of two arrays. An intersection would be the common elements that exists //within both arrays. In this case, these elements should be unique! 2 | 3 | 4 | var firstArray = [2, 2, 4, 1]; 5 | var secondArray = [1, 2, 0, 2]; 6 | 7 | intersection(firstArray, secondArray); // [2, 1] 8 | 9 | function intersection(firstArray, secondArray) { 10 | // The logic here is to create a hashmap with the elements of the firstArray as the keys. 11 | // After that, you can use the hashmap's O(1) look up time to check if the element exists in the hash 12 | // If it does exist, add that element to the new array. 13 | // array1 = [1,5,6,7,8]; 14 | // array2 = [3,4,5,7,9]; 15 | 16 | var hashmap = {}; 17 | var intersectionArray = []; 18 | // assign 1 to all index in hashmap 19 | firstArray.forEach(function(element) { 20 | hashmap[element] = 1; 21 | }); 22 | 23 | // Since we only want to push unique elements in our case... we can implement a counter to keep track of what we already added 24 | // now just check if second array has that index available and should equal to 1 25 | secondArray.forEach(function(element) { 26 | if (hashmap[element] === 1) { 27 | intersectionArray.push(element); 28 | hashmap[element]++; 29 | } 30 | }); 31 | 32 | return intersectionArray; 33 | 34 | // Time complexity O(n), Space complexity O(n) 35 | } 36 | -------------------------------------------------------------------------------- /prototype.js: -------------------------------------------------------------------------------- 1 | function x(){} 2 | undefined 3 | x.prototype 4 | {constructor: ƒ}constructor: ƒ x()__proto__: Object 5 | new x() 6 | x {}__proto__: constructor: ƒ x()__proto__: constructor: ƒ Object()arguments: nullassign: ƒ assign()caller: nullcreate: ƒ create()defineProperties: ƒ defineProperties()defineProperty: ƒ defineProperty()entries: ƒ entries()freeze: ƒ freeze()getOwnPropertyDescriptor: ƒ getOwnPropertyDescriptor()getOwnPropertyDescriptors: ƒ getOwnPropertyDescriptors()getOwnPropertyNames: ƒ getOwnPropertyNames()getOwnPropertySymbols: ƒ getOwnPropertySymbols()getPrototypeOf: ƒ getPrototypeOf()is: ƒ is()isExtensible: ƒ isExtensible()isFrozen: ƒ isFrozen()isSealed: ƒ isSealed()keys: ƒ keys()length: 1name: "Object"preventExtensions: ƒ preventExtensions()prototype: {__defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, __lookupSetter__: ƒ, …}seal: ƒ seal()setPrototypeOf: ƒ setPrototypeOf()values: ƒ values()__proto__: ƒ ()[[FunctionLocation]]: hasOwnProperty: ƒ hasOwnProperty()isPrototypeOf: ƒ isPrototypeOf()propertyIsEnumerable: ƒ propertyIsEnumerable()toLocaleString: ƒ toLocaleString()toString: ƒ toString()valueOf: ƒ valueOf()__defineGetter__: ƒ __defineGetter__()__defineSetter__: ƒ __defineSetter__()__lookupGetter__: ƒ __lookupGetter__()__lookupSetter__: ƒ __lookupSetter__()get __proto__: ƒ __proto__()set __proto__: ƒ __proto__() 7 | x.__proto__ 8 | ƒ () { [native code] } 9 | x.__proto__ === x.prototype 10 | false -------------------------------------------------------------------------------- /interview-cake/stack.js: -------------------------------------------------------------------------------- 1 | // Stack class 2 | class Stack { 3 | 4 | // Array is used to implement stack 5 | constructor() { 6 | this.items = []; 7 | } 8 | 9 | push(element) { 10 | // push element into the items 11 | this 12 | .items 13 | .push(element); 14 | } 15 | // pop function 16 | pop() { 17 | // return top most element in the stack and removes it from the stack Underflow 18 | // if stack is empty 19 | if (this.items.length == 0) 20 | return "Underflow"; 21 | return this 22 | .items 23 | .pop(); 24 | } 25 | // peek function 26 | peek() { 27 | // return the top most element from the stack but does'nt delete it. 28 | return this.items[this.items.length - 1]; 29 | } 30 | // isEmpty function 31 | isEmpty() { 32 | // return true if stack is empty 33 | return this.items.length == 0; 34 | } 35 | // printStack function 36 | printStack(){ 37 | var str = ""; 38 | for (var i = 0; i < this.items.length; i++) 39 | str += this.items[i] + " "; 40 | return str; 41 | } 42 | 43 | } 44 | // Adding element to the stack 45 | stack.push(10); 46 | stack.push(20); 47 | stack.push(30); 48 | 49 | // Printing the stack element 50 | // prints [10, 20, 30] 51 | console.log(stack.printStack()); 52 | 53 | // returns 30 54 | console.log(stack.peek()); 55 | 56 | // returns 30 and remove it from stack 57 | console.log(stack.pop()); 58 | 59 | // returns [10, 20] 60 | console.log(stack.printStack()); 61 | -------------------------------------------------------------------------------- /array and String/isomorphic.js: -------------------------------------------------------------------------------- 1 | For two strings to be isomorphic, all occurrences of a character in string A can be replaced with another character 2 | to get string B. The order of the characters must be preserved. There must be one-to-one mapping for ever char of 3 | string A to every char of string B. 4 | 5 | `paper` and `title` would return true. 6 | `egg` and `sad` would return false. 7 | `dgg` and `add` would return true. 8 | isIsomorphic("egg", 'add'); // true 9 | isIsomorphic("paper", 'title'); // true 10 | isIsomorphic("kick", 'side'); // false 11 | 12 | function isIsomorphic(firstString, secondString) { 13 | 14 | // Check if the same lenght. If not, they cannot be isomorphic 15 | if (firstString.length !== secondString.length) return false 16 | 17 | var letterMap = {}; 18 | 19 | for (var i = 0; i < firstString.length; i++) { 20 | var letterA = firstString[i], 21 | letterB = secondString[i]; 22 | 23 | // If the letter does not exist, create a map and map it to the value 24 | // of the second letter 25 | if (letterMap[letterA] === undefined) { 26 | letterMap[letterA] = letterB; 27 | } else if (letterMap[letterA] !== letterB) { 28 | // Eles if letterA already exists in the map, but it does not map to 29 | // letterB, that means that A is mapping to more than one letter. 30 | return false; 31 | } 32 | } 33 | // If after iterating through and conditions are satisfied, return true. 34 | // They are isomorphic 35 | return true; 36 | } 37 | -------------------------------------------------------------------------------- /object.js: -------------------------------------------------------------------------------- 1 | var obj = {}; 2 | var app = new Object(); 3 | var obj = { x: 80}; 4 | 5 | var obj = {}; 6 | Object.defineProperties(obj, { 7 | 'property1': { 8 | value: true, 9 | writable: true 10 | }, 11 | 'property2': { 12 | value: 'Hello', 13 | writable: false, 14 | enumerable : true, 15 | 16 | } 17 | // etc. etc. 18 | }); 19 | 20 | var obj = { x: 80}; 21 | undefined 22 | Object.freeze(obj); 23 | {x: 80} 24 | obj.x = 90; 25 | 90 26 | console.log(obj) 27 | VM4279:1 {x: 80} 28 | 29 | //--------------------------------------// 30 | 31 | var obj = {}; 32 | Object.defineProperties(obj, { 33 | 'property1': { 34 | value: true, 35 | writable: false 36 | }, 37 | 'property2': { 38 | value: 'Hello', 39 | writable: true, 40 | enumerable : true, 41 | 42 | } 43 | // etc. etc. 44 | }); 45 | {property2: "Hello", property1: true} 46 | Object.getOwnPropertyDescriptor(obj.property1) 47 | undefined 48 | console.log(Object.getOwnPropertyNames(obj)) 49 | VM4747:1 (2) ["property1", "property2"]0: "property1"1: "property2"length: 2__proto__: Array(0) 50 | undefined 51 | console.log(Object.getOwnPropertyDescriptors(obj)) 52 | VM4818:1 {property1: {…}, property2: {…}}property1: {value: true, writable: false, enumerable: false, configurable: false}property2: {value: "Hello", writable: true, enumerable: true, configurable: false}__proto__: Object 53 | undefined 54 | obj.property1 = false; 55 | false 56 | obj.property1 57 | true 58 | //-----------------------------------------------------------// -------------------------------------------------------------------------------- /array and String/object_compare.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | function isEquivalent(a, b) { 4 | // Create arrays of property names 5 | var aProps = Object.getOwnPropertyNames(a); 6 | var bProps = Object.getOwnPropertyNames(b); 7 | 8 | // If number of properties is different, 9 | // objects are not equivalent 10 | if (aProps.length != bProps.length) { 11 | return false; 12 | } 13 | 14 | for (var i = 0; i < aProps.length; i++) { 15 | var propName = aProps[i]; 16 | 17 | // If values of same property are not equal, 18 | // objects are not equivalent 19 | if (a[propName] !== b[propName]) { 20 | return false; 21 | } 22 | } 23 | // If we made it this far, objects 24 | // are considered equivalent 25 | return true; 26 | } 27 | 28 | // Outputs: true 29 | console.log(isEquivalent(bobaFett, jangoFett)); 30 | 31 | 32 | //--------------------------------------// 33 | var jangoFett = { 34 | occupation: "Bounty Hunter", 35 | genetics: "superb" 36 | }; 37 | 38 | var bobaFett = { 39 | occupation: "Bounty Hunter", 40 | genetics: "superb" 41 | }; 42 | 43 | // Outputs: false 44 | console.log(bobaFett === jangoFett); 45 | 46 | //-----------------------------------------// 47 | var jangoFett = { 48 | occupation: "Bounty Hunter", 49 | genetics: "superb" 50 | }; 51 | 52 | var bobaFett = { 53 | occupation: "Bounty Hunter", 54 | genetics: "superb" 55 | }; 56 | 57 | var callMeJango = jangoFett; 58 | 59 | // Outputs: false 60 | console.log(bobaFett === jangoFett); 61 | 62 | // Outputs: true 63 | console.log(callMeJango === jangoFett); 64 | //----------------------------------------------// 65 | -------------------------------------------------------------------------------- /syllabus.js: -------------------------------------------------------------------------------- 1 | JavaScript Resources 2 | ECMAScript Language Specification// skip 3 | Course Plan 6m 58s 4 | Scope // 5 | Scope and the JavaScript Compiler 6 | Compiling Function Scope 7 | Execution of Function Code 8 | Scope and Execution Example 9 | Function Declarations, Function Expressions, and Block Scope 9m 54s 10 | Lexical Scope // i will talk about this 11 | // ES5 js 12 | 13 | IIFE Pattern 9m 31s 14 | IIFE Pattern Questions 4m 17s 15 | 16 | Block Scope in ES64m 11s 17 | Problems with the Let Keyword 8m 10s 18 | 19 | Dynamic Scope 1m 51s 20 | Quiz: Scope 1m 43s 21 | Hoisting 12m 55s // in js 22 | Exercise 12m 54s 23 | Exercise 1: Solution 7m 55s 24 | this Keyword 12m 4s // 25 | 26 | 27 | Binding Confusion 6m 35s 28 | Explicit Binding 12m 39s 29 | The New keyword 8m 11s // creating object 30 | Quiz: this 3m 31s 31 | Closure 32 | 46m 41s 33 | Closures 6m 46s // nexted functions 34 | Closure Examples 7m 57s // covered 35 | More Closure Examples 5m 21s 36 | Module Patterns 10m 29s // design pattern . singelton/factory/ 37 | Quiz: Closure 4m 0s 38 | Exercise 21m 59s 39 | Exercise 2 Solution 10m 5s 40 | Object Orienting 41 | 42 | Prototype 5m 5s // 43 | Prototypes Explained, Part 110m 3s 44 | Prototypes Explained, Part 26m 57s 45 | Prototype Linkages 8m 31s 46 | Prototype: Objects Linked 6m 16s 47 | Linked Prototype Diagram 4m 27s 48 | Quiz: Prototype Behavior 3m 2s 49 | Exercise 32m 49s 50 | Exercise 3: Solution 6m 44s 51 | Inheritance 5m 6s 52 | OLOO 6m 18s 53 | OLOO Questions 9m 7s 54 | Quiz: Prototype Unit 7m 14s 55 | Exercise 42m 11s 56 | Exercise 4 Solution 22m 18s 57 | Async Patterns 58 | 57m 17s 59 | Callbacks 8m 15s 60 | Solving Callback Problems 3m 2s 61 | Generators 7m 33s 62 | Promises 7m 51s 63 | Asynquence 5m 48s 64 | Quiz: Async Patterns 2m 28s 65 | Exercise 52m 31s 66 | Exercise 5 Solution 67 | -------------------------------------------------------------------------------- /array and String/arrays.js: -------------------------------------------------------------------------------- 1 | exports = typeof window === 'undefined' ? global : window; 2 | // complete all other methos 3 | // you can execute this from console 4 | exports.arraysAnswers = { 5 | indexOf: function(arr, item) { 6 | return arr.indexOf(item); 7 | }, 8 | 9 | sum: function(arr) { 10 | var ab=0; 11 | arr.forEach(function(item,arr,index){ 12 | ab=ab+item; 13 | }); 14 | return ab; 15 | }, 16 | 17 | remove: function(arr, item) { 18 | var params=arguments; 19 | var paramLength=params.length; 20 | var itemIndex,itemToRemove; 21 | while(paramLength>1 && arr.length){ 22 | itemToRemove=params[--paramLength]; 23 | while((itemIndex=arr.indexOf(itemToRemove)) !== -1){ 24 | arr.splice(itemIndex,1); 25 | } 26 | } 27 | return arr; 28 | }, 29 | 30 | removeWithoutCopy: function(arr, item) { 31 | var params=arguments; 32 | var paramLength=params.length; 33 | var itemIndex,itemToRemove; 34 | while(paramLength>1 && arr.length){ 35 | itemToRemove=params[--paramLength]; 36 | while((itemIndex=arr.indexOf(itemToRemove)) !== -1){ 37 | arr.splice(itemIndex,1); 38 | } 39 | } 40 | return arr; 41 | }, 42 | 43 | append: function(arr, item) { 44 | arr.push(item); 45 | return arr; 46 | }, 47 | 48 | truncate: function(arr) { 49 | arr.pop(); 50 | return arr; 51 | }, 52 | 53 | prepend: function(arr, item) { 54 | arr.unshift(item); 55 | return arr; 56 | }, 57 | 58 | curtail: function(arr) { 59 | arr.shift(); 60 | return arr; 61 | }, 62 | 63 | concat: function(arr1, arr2) { 64 | arr1=arr1.concat(arr2); 65 | return arr1; 66 | }, 67 | 68 | insert: function(arr, item, index) { 69 | arr.splice(index,0,item); 70 | return arr; 71 | }, 72 | 73 | count: function(arr, item) { 74 | arr.length; 75 | return arr; 76 | }, 77 | 78 | duplicates: function(arr) { 79 | var t = []; 80 | for(i= 0; i < arr.length; i++){ 81 | var count =0; 82 | for(j = 0; j < arr.length; j++) { 83 | if(arr[j] == arr[i]) { 84 | count++; 85 | } 86 | } 87 | if(count > 1) { 88 | console.log("value --- " + arr[i] + " counter -- " + count); 89 | } 90 | } 91 | }, 92 | removeAllduplicates: function(arr) { 93 | var cleanArray = []; 94 | for(var i = 0; i < arr.length; i++) { 95 | let element = arr[i]; 96 | if (cleanArray.indexOf(element) === -1) { 97 | cleanArray.push(element); 98 | } 99 | } 100 | console.log(cleanArray); 101 | }, 102 | 103 | findAllOccurrences: function(arr, target) { 104 | // count occrence of all elements in array 105 | } 106 | }; 107 | -------------------------------------------------------------------------------- /prototype_chain.js: -------------------------------------------------------------------------------- 1 | var obj1 = {a : 100}; 2 | undefined 3 | var obj2 = Object.create(obj1); 4 | undefined 5 | obj2.b = 90; 6 | 90 7 | var obj3 = Object.create(obj2); 8 | undefined 9 | obj3.a 10 | 100 11 | obj3 12 | {}__proto__: b: 90__proto__: a: 100__proto__: constructor: ƒ Object()arguments: nullassign: ƒ assign()caller: nullcreate: ƒ create()defineProperties: ƒ defineProperties()defineProperty: ƒ defineProperty()entries: ƒ entries()freeze: ƒ freeze()getOwnPropertyDescriptor: ƒ getOwnPropertyDescriptor()getOwnPropertyDescriptors: ƒ getOwnPropertyDescriptors()getOwnPropertyNames: ƒ getOwnPropertyNames()getOwnPropertySymbols: ƒ getOwnPropertySymbols()getPrototypeOf: ƒ getPrototypeOf()is: ƒ is()isExtensible: ƒ isExtensible()isFrozen: ƒ isFrozen()isSealed: ƒ isSealed()keys: ƒ keys()length: 1name: "Object"preventExtensions: ƒ preventExtensions()prototype: {__defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, __lookupSetter__: ƒ, …}seal: ƒ seal()setPrototypeOf: ƒ setPrototypeOf()values: ƒ values()__proto__: ƒ ()[[FunctionLocation]]: hasOwnProperty: ƒ hasOwnProperty()isPrototypeOf: ƒ isPrototypeOf()propertyIsEnumerable: ƒ propertyIsEnumerable()toLocaleString: ƒ toLocaleString()toString: ƒ toString()valueOf: ƒ valueOf()__defineGetter__: ƒ __defineGetter__()__defineSetter__: ƒ __defineSetter__()__lookupGetter__: ƒ __lookupGetter__()__lookupSetter__: ƒ __lookupSetter__()get __proto__: ƒ __proto__()set __proto__: ƒ __proto__() 13 | obj1.a = 70; 14 | 70 15 | obj3 16 | {}__proto__: b: 90__proto__: a: 70__proto__: Object 17 | obj3.a = 10; 18 | 10 19 | obj3.a 20 | 10 21 | obj3.b 22 | 90 23 | obj3 24 | {a: 10}a: 10__proto__: b: 90__proto__: Object 25 | 26 | //----------------------------------------------------------------// 27 | 28 | 29 | function hello(){} 30 | undefined 31 | hello.prototype.sayhello = function(){consoel.log('logging from function hello')}; 32 | ƒ (){consoel.log('logging from function hello')} 33 | hello 34 | ƒ hello(){} 35 | console.dir(hello); 36 | VM6819:1 ƒ hello()arguments: nullcaller: nulllength: 0name: "hello"prototype: sayhello: ƒ ()arguments: nullcaller: nulllength: 0name: ""prototype: {constructor: ƒ}__proto__: ƒ ()[[FunctionLocation]]: VM6692:1[[Scopes]]: Scopes[1]constructor: ƒ hello()arguments: nullcaller: nulllength: 0name: "hello"prototype: {sayhello: ƒ, constructor: ƒ}__proto__: ƒ ()apply: ƒ apply()arguments: (...)bind: ƒ bind()call: ƒ call()caller: (...)constructor: ƒ Function()length: 0name: ""toString: ƒ toString()Symbol(Symbol.hasInstance): ƒ [Symbol.hasInstance]()get arguments: ƒ ThrowTypeError()set arguments: ƒ ThrowTypeError()get caller: ƒ ThrowTypeError()set caller: ƒ ThrowTypeError()__proto__: Object[[FunctionLocation]]: [[FunctionLocation]]: VM6589:1[[Scopes]]: Scopes[1]__proto__: Object__proto__: ƒ ()[[FunctionLocation]]: VM6589:1[[Scopes]]: Scopes[1] 37 | undefined 38 | function hello2(){} 39 | undefined 40 | console.dir(hello2); 41 | VM6969:1 ƒ hello2()arguments: nullcaller: nulllength: 0name: "hello2"prototype: constructor: ƒ hello2()__proto__: Object__proto__: ƒ ()[[FunctionLocation]]: VM6905:1[[Scopes]]: Scopes[1] 42 | undefined 43 | hello2.prototype = hello.prototype; 44 | {sayhello: ƒ, constructor: ƒ} 45 | console.dir(hello2); 46 | VM7013:1 ƒ hello2()arguments: nullcaller: nulllength: 0name: "hello2"prototype: sayhello: ƒ ()constructor: ƒ hello()__proto__: Object__proto__: ƒ ()[[FunctionLocation]]: VM6905:1[[Scopes]]: Scopes[1] 47 | undefined 48 | var obj = new hello2(); 49 | undefined -------------------------------------------------------------------------------- /array and String/Array.prototype.js: -------------------------------------------------------------------------------- 1 | Basic Array method 2 | callback function of map, filter, some, every, forEach has three parameters: elem, index, arr. And you can optionally pass "this" as second argument of these Array method. 3 | 4 | forEach 5 | forEach dont return anything. it just run the callback functionf or each element of the array 6 | 7 | 8 | > [1,2,3].forEach(function(elem, index, arr){ 9 | console.log(elem); 10 | }); 11 | = 1 12 | = 2 13 | = 3 14 | 15 | 16 | map 17 | returns new array by executing the callback function for each elements of the array 18 | 19 | 20 | > [1,2,3].map(function(elem, index, arr){ 21 | return elem * elem; 22 | }); 23 | = [1, 4, 9]; 24 | filter 25 | if the condition is true for an element, element is picked for the return array 26 | 27 | 28 | > [1,2,3,4,5,6,7].filter(function(elem, index, arr){ 29 | return index % 2==0; 30 | }); 31 | = [1, 3, 5, 7] 32 | some 33 | if any of element in the arrya fulfil the condition, some will return true else will return false 34 | 35 | 36 | >[1,2,3, 4].some(function(elem, index, arr){ 37 | return elem >3; 38 | }); 39 | = true; 40 | every 41 | it will return true if every elements in the array fulfil the condition. else return false 42 | 43 | 44 | >[1,2,3, 4].every(function(elem, index, arr){ 45 | return elem >3; 46 | }); 47 | = false; 48 | 49 | >[1,2,3, 4].every(function(elem, index, arr){ 50 | return elem >0; 51 | }); 52 | = true; 53 | 11.use build in function 54 | 55 | > ["Happy", 0, "New", "", "Year", false].filter(Boolean); 56 | = ["Happy", "New", "Year"] 57 | 58 | ref: es5 array extra 59 | 60 | reduce 61 | reduce cache the value. for example u want to get the sum of all the element. alternatively, you can initially 62 | 63 | 64 | [1, 2, 3, 4].reduce(function(sum, el, idx, arr){ 65 | return sum + el; 66 | }) 67 | = 10 68 | 69 | [1, 2, 3, 4].reduce(function(sum, el, idx, arr){ 70 | return sum + el; 71 | }, 100) 72 | = 110 73 | 74 | 12. real length by reduce 75 | talk about reduce here 76 | 77 | 78 | > ["hello", , , , , "javaScript"].reduce(function(count){ 79 | return count + 1; 80 | }, 0); 81 | = 2 82 | 83 | 13. check array 84 | 85 | > typeof [] 86 | = "object" 87 | > typeof {} 88 | = "object" 89 | 90 | > Array.isArray([]); 91 | = true 92 | > Array.isArray({}); 93 | = false 94 | 95 | 14. deal with Array-like objects 96 | 97 | function foo(){ 98 | console.log(arguments, 'len', arguments.length, '2nd', arguments[1]) 99 | } 100 | 101 | foo(1, 2, 3,4) 102 | = [1, 2, 3, 4] "len" 4 "2nd" 2 103 | 104 | 105 | function foo(){ 106 | console.log(Array.isArray(arguments)); 107 | arguments.push(5); 108 | console.log(arguments, 'len', arguments.length, '2nd', arguments[1]) 109 | } 110 | foo(1, 2, 3,4) 111 | = false 112 | = TypeError: Object # has no method 'push' 113 | 114 | 115 | function foo(){ 116 | var args = Array.prototype.slice.call(arguments); 117 | args.push(5); 118 | console.log(args, 'len', args.length, '2nd', args[1]) 119 | } 120 | 121 | foo(1, 2, 3,4) 122 | = [1, 2, 3, 4, 5] "len" 5 "2nd" 2 123 | 124 | array method in string 125 | 126 | var dd = 'that JS Dude'; 127 | 128 | dd.filter(function (el, idx){ 129 | return idx>7; 130 | }) 131 | = TypeError: Object that JS Dude has no method 'filter' 132 | 133 | 134 | [].filter.call(dd, function(el, idx){ 135 | return idx>7; 136 | }) 137 | = ["D", "u", "d", "e"] 138 | -------------------------------------------------------------------------------- /array and String/js_test.js: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Write a function which reverses the passed string 4 | */ 5 | 6 | const reverseString = (str) => { 7 | return str.split('').reverse().join(''); 8 | } 9 | 10 | /* 11 | Write a function which removes the passed delimiter from the string. 12 | e.g. 'a-b-c'.removeDelimiter('-') should return 'abc' 13 | */ 14 | 15 | String.prototype.removeDelimiter = function(delimiter) { 16 | var regex = new RegExp('-', 'g'); 17 | return this.replace(regex,'' ); 18 | } 19 | 20 | /* 21 | Write a function which return the multiplication of three numbers. 22 | The function can be called in any of the following forms: 23 | 24 | multiply(2, 3, 4) => 24 25 | multiply(2, 3)(4) => 24 26 | multiply(2)(3, 4) => 24 27 | multiply(2)(3)(4) => 24 28 | */ 29 | 30 | const multiply = (...args) => { 31 | let vals = [].concat(args); 32 | 33 | if(vals.length ===3){ 34 | return vals.reduce((ac, val)=>{return ac*val;},1) 35 | } 36 | 37 | const curry = (...args) => { 38 | vals = vals.concat(args); 39 | if(vals.length !==3){ 40 | return curry; 41 | } 42 | return multiply(...vals); 43 | } 44 | return curry; 45 | }; 46 | 47 | /* 48 | write a function to check if the two object passed are equal or not. 49 | the objects can be nested. 50 | */ 51 | 52 | const areEqualObjs = (obj1, obj2) => { 53 | if(obj1 === obj2){ 54 | return true 55 | } 56 | else if(obj1 === null || obj2 === null){ 57 | return false; 58 | } 59 | else if(obj1 && obj2){ 60 | return JSON.stringify(obj1) === JSON.stringify(obj2) 61 | } 62 | } 63 | 64 | /* 65 | write a function to faltten the array 66 | */ 67 | // [1,2,3,[4,5,6],[1,2,3,4]] 68 | // [1,2,3,4,5,6,1,2,3,4] 69 | Array.prototype.flatten = function() { 70 | 71 | return this.reduce(function (flat, toFlatten) { 72 | return flat.concat(Array.isArray(toFlatten) ? toFlatten.flatten(): toFlatten); 73 | }, []); 74 | }; 75 | 76 | //Test cases 77 | 78 | describe('reverseString', () => { 79 | it('reverses the passed string', () => { 80 | expect(reverseString('')).toBe(''); 81 | expect(reverseString('abcde')).toBe('edcba'); 82 | }); 83 | }); 84 | 85 | describe('removeDelimiter', () => { 86 | it('removes the passed delimiter from the string', () => { 87 | expect(reverseString('')).toBe(''); 88 | expect("Equal-Experts".removeDelimiter('-')).toEqual('EqualExperts'); 89 | }); 90 | }); 91 | 92 | describe('multiply', () => { 93 | it('curries the multiply for three arguments', () => { 94 | expect(multiply(2, 3, 4)).toBe(24); 95 | expect(multiply(2, 3)(4)).toBe(24); 96 | expect(multiply(2)(3, 4)).toBe(24); 97 | expect(multiply(2)(3)(4)).toBe(24); 98 | }); 99 | }); 100 | 101 | describe('areEqualObjs', () => { 102 | it('compares the objects', () => { 103 | expect(areEqualObjs({ 104 | a: 1, 105 | b: 2 106 | }, { 107 | a: 1, 108 | b: 2 109 | })).toBeTruthy(); 110 | 111 | expect(areEqualObjs({ 112 | a: 1, 113 | b: 2 114 | }, { 115 | a: 1, 116 | b: 3 117 | })).toBeFalsy(); 118 | 119 | expect(areEqualObjs({ 120 | a: 1, 121 | b: 2 122 | }, { 123 | a: 1 124 | })).toBeFalsy(); 125 | 126 | expect(areEqualObjs({ 127 | a: { 128 | b: 1 129 | } 130 | }, { 131 | a: { 132 | b: 1 133 | } 134 | })).toBeTruthy(); 135 | 136 | expect(areEqualObjs({ 137 | a: { 138 | b: 1 139 | } 140 | }, { 141 | a: { 142 | b: 2 143 | } 144 | })).toBeFalsy(); 145 | 146 | expect(areEqualObjs({ 147 | a: { 148 | b: 1, 149 | c: { 150 | d: 2 151 | } 152 | } 153 | }, { 154 | a: { 155 | b: 1, 156 | c: { 157 | d: 3 158 | } 159 | } 160 | })).toBeFalsy(); 161 | 162 | expect(areEqualObjs({ 163 | a: { 164 | b: 1, 165 | c: { 166 | d: { 167 | e: 2 168 | } 169 | } 170 | } 171 | }, { 172 | a: { 173 | b: 1, 174 | c: { 175 | d: { 176 | e: 2 177 | } 178 | } 179 | } 180 | })).toBeTruthy(); 181 | }) 182 | }); 183 | 184 | describe('flattenArray',() => { 185 | it('flattens the passed array', () => { 186 | expect([].flatten()).toEqual([]); 187 | expect([1, 2].flatten()).toEqual([1, 2]); 188 | expect([1, [2]].flatten()).toEqual([1, 2]); 189 | expect([1, [2, 3]].flatten()).toEqual([1, 2, 3]); 190 | expect([[1], [2], [3], [4], [5]].flatten()).toEqual([1, 2, 3, 4, 5]); 191 | expect([1, 2, [3, [4, 5, 6]], [7, 8]].flatten()).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); 192 | expect([1, [2, [3, [4, [5, [6, [7, [8]]]]]]]].flatten()).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); 193 | }); 194 | }); 195 | 196 | 197 | 198 | 199 | 200 | 201 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Front end Interview Questions 2 | ============================= 3 | ------- 4 | To rock the interview to achieve what you deserve and to improve your concepts about front end technologies, I have consolidated a list of questions and answers. It's a one stop solution for front end interview process. 5 | 6 | ## Table of Contents 7 | * [JavaScript: Basics and Tricky Questions](#javascript-basics-and-tricky-questions) 8 | * [Algorithm Beginners Level](#javascript-algorithm-beginners-level) 9 | * [Intermediate Level Questions](#javascript-for-intermediate-level-developer) 10 | * [css: Basics and Tricky Questions](#css-basics-and-tricky-questions) 11 | * [DOM related Questions](#javascript-dom-related-questions) 12 | * [html: Basic Questions for Begginers](#html-basic-questions-for-begginers) 13 | 14 | ### [Angular Interview Questions](https://github.com/khan4019/angular-interview-questions) 15 | An exclusive list of Angular interview Questions are [here](https://github.com/khan4019/angular-interview-questions) 16 | 17 | ## [JavaScript: Basics and Tricky Questions](http://www.thatjsdude.com/interview/js2.html) 18 | 21+ questions and answers (for intermediate) 19 | __________________ 20 | 1. What are the differences between ` null ` and ` undefined `? 21 | 2. What are the differences between `==` and `===`? 22 | 3. How would you compare two objects in JavaScript? 23 | 4. 11+ true false related questions that will trick you. 24 | 5. As `[]` is true, `[] == true` should also be true. right? 25 | 6. How could you write a method on instance of a date which will give you next day? 26 | 7. If you want to use an arbitrary object as value of this, how will you do that? 27 | 8. Write a simple function to tell whether 2 is passed as parameter or not? 28 | 9. How could you use Math.max to find the max value in an array? 29 | 10. What the heck is this in JavaScript? 30 | 11. 21 quick questions that will trick you. 31 | 12. How could you set a prefix before everything you log? for example, if you log('my message') it will log: "(app) my message" 32 | 13. What will you see in the console for the following example? 33 | 14. Look at the code below, you have a for loop if you have setTimeout inside it. If log the loop counter inside setTimeout, what will be logged? 34 | 15. Look at the code below, I have a property in a object and I am creating a new object where I am setting it to a new value. If I delete that property what will i get if I try to access that property? 35 | 16. Does JavaScript pass parameter by value or by reference? 36 | 17. How could you implement cache to save calculation time for a recursive fibonacci function? 37 | 18. How could you cache execution of any function? 38 | 19. If you need to implement the following chaining with call back, how will you implement it? 39 | 20. How could you implement moveLeft animation? 40 | 21. How would you implement currying for any functions? 41 | 42 | #### [JS: Answer for Basics and Tricky Questions](http://www.thatjsdude.com/interview/js2.html) 43 | 44 | 45 | 46 | ## [css: Basics and Tricky Questions](http://www.thatjsdude.com/interview/css.html) 47 | 21+ questions and answers 48 | ____________ 49 | 1. What does float do? 50 | 1. How can you clear sides of a floating element? 51 | 1. How can you clear sides of a floating element? 52 | 1. some tricky questions in rapid fire style 53 | 1. Are CSS rule names case sensitive? 54 | 1. Why css selectors mixed up with cases don't apply the styles? 55 | 1. Does margin-top or margin-bottom has effect on inline element? 56 | 1. Does padding-top or padding-bottom has effect on inline element? 57 | 1. Does padding-left or padding-right or margin-left or margin-right has effect on inline element? 58 | 1. If you have a <p> element with font-size: 10rem, will the text be responsive when the user resizes / drags the browser window? 59 | 1. The pseudo class :checked will select inputs with type radio or checkbox, but not <option> elements. 60 | 1. In a HTML document, the pseudo class :root always refers to the <html> element. 61 | 1. The translate() function can move the position of an element on the z-axis. 62 | 1. Which one would you prefer among px, em % or pt and why? 63 | 1. How absolute, relative, fixed and static position differ? 64 | 1. What are the differences between visibility hidden and display none? 65 | 1. What are the differences between inline, block and inline-block? 66 | 1. What are the properties related to box model? 67 | 1. Does overflow: hidden create a new block formatting context? 68 | 1. How could you apply css rules specific to a media? 69 | 1. What is the use of only? 70 | 1. Does the screen keyword apply to the device's physical screen or the browser's viewport? 71 | 1. What are the some pseudo classed u have used? 72 | 1. How do you align a p center-center inside a div? 73 | 1. How do you optimize css selectors? 74 | 1. How can you load css resources conditionally? 75 | 1. Why would you use sprites? 76 | 1. What is specificity? How do u calculate specificity? 77 | 1. What is shadow DOM? 78 | 1. What do you know about transition? 79 | 1. What are the different css filter you can use? 80 | 1. What are the reasons to use preprocessor? 81 | 1. [Show you couple of style example and you have to tell what does it do](http://www.thatjsdude.com/interview/css.html#seeAndTell). 82 | 83 | #### [CSS: Answer for Basics and Tricky Questions](http://www.thatjsdude.com/interview/css.html) 84 | 85 | ### css Deleted questions! 86 | Looks like these are for hardcore designer. Hence, didn't make for developers. 87 | ______ 88 | 1. How descendant css selectors are matched? [get answer](https://www.youtube.com/watch?v=EW8Bg_H_P7M) 89 | 1. How would u implement modularity in css? 90 | 1. If something doesn't work in a specific browser (IE8), you would u approach this problem? 91 | 1. How do you test cross-browser compatibility of your site? 92 | 1. What is the greatest hack you did in css so far? 93 | 1. What is grid layout? 94 | 1. How can you make a site responsive? 95 | 1. Why reset css is useful? or how normalize.css works? 96 | 1. What do you know about text shadows, box shadows? 97 | 98 | 99 | 100 | 101 | ## [JavaScript: Algorithm Beginners Level](http://www.thatjsdude.com/interview/js1.html) 102 | 20 questions and answers (for beginners) 103 | __________________ 104 | 1. Verify a prime number? 105 | 1. Find all prime factors of a number? 106 | 1. Get nth Fibonacci number? 107 | 1. Find the greatest common divisor of two numbers? 108 | 1. Remove duplicate members from an array? 109 | 1. merge two sorted array? 110 | 1. Swap two numbers without using a temp variable? 111 | 1. Reverse a string in JavaScript? 112 | 1. How would you reverse words in a sentence? 113 | 1. Reverse words in place? 114 | 1. Find the first non repeating char in a string? 115 | 1. Remove duplicate characters from a sting? 116 | 1. How will you verify a word as palindrome? 117 | 1. Generate random between 5 to 7 by using defined function. 118 | 1. Find missing number from unsorted array of integers. 119 | 1. Get two numbers that equal to a given number? 120 | 1. Find the largest sum of any two elements? 121 | 1. Total number of zeros from 1 upto n? 122 | 1. Check whether a given string is a substring of bigger string 123 | 2. Get permutations of a string 124 | 125 | #### [JS: Answer for Algorithm Beginners Level](http://www.thatjsdude.com/interview/js1.html) 126 | 127 | 128 | ## JavaScript for Intermediate Level Developer 129 | 130 | 1. What is the event loop? Can you draw a simple diagram to explain event loop? 131 | 1. How to you explain closure? 132 | 3. How would you make sure value of `this` works correctly inside `setTimeout`? 133 | 1. What are the different possible values for `this`? 134 | 1. What is debounce and how could you implement debounce? 135 | 6. How would you communicate with server 136 | 1. Explain Promise to your grandmother 137 | 1. If and website is slow how what would you do to make it faster? 138 | 9. What ES6 feature do you use other than let, var and arrow? 139 | 1. What build tool you use and tell me some advantages to use that build tool 140 | 141 | ## [JavaScript: DOM related Questions](http://www.thatjsdude.com/interview/dom.html) 142 | 21+ questions and answers (for intermediate JS Developers) 143 | __________________ 144 | 1. Is there any difference between window and document? 145 | 1. Does document.onload and window.onload fire at the same time? 146 | 1. Is attribute similar to property? 147 | 1. What are the different ways to get an element from DOM? 148 | 1. What is the fastest way to select elements by using css selectors? 149 | 1. How come, I can't use forEach or similar array methods on a NodeList? 150 | 1. If you need to implement getElementByAttribute, how would you implement it? 151 | 1. How would you add a class to an element by query selector? 152 | 1. How could I verify whether one element is child of another? 153 | 1. What is the best way to create a DOM element? Set innherHTML or use createElement? 154 | 1. What is createDocumentFragment and why you might use it? 155 | 1. What is reflow? What causes reflow? How could you reduce reflow? 156 | 1. What is repaint and when does this happen? 157 | 1. How could you make sure to run some JavaScript when DOM is ready like $(document).ready? 158 | 1. What is event bubble? How does event flows in DOM? 159 | 1. How would you destroy multiple list items with one click handler? 160 | 1. Create a button that is destroyed by clicking in it but two new buttons are created in it's place. 161 | 1. How could you capture all clicks in a page? 162 | 1. How can you get all the texts in a web page? 163 | 1. What is defer and async keyword does in a script tag? 164 | 1. 10 rapid fire questions 165 | 166 | #### [JS: Answers for DOM related Questions](http://www.thatjsdude.com/interview/dom.html) 167 | 168 | 169 | 170 | 171 | ## [html: Basic Questions for Begginers](http://www.thatjsdude.com/interview/html.html) 172 | 173 | 15 basic questions and asnwers 174 | ______ 175 | 1. Why do you need doctype? 176 | 2. What are data-* attributes used for? 177 | 3. How can you generate a public key in html? 178 | 4. How do you change the direction of html text? 179 | 5. How can you highlight text in html? 180 | 6. Can you apply css to a part of html document only? 181 | 7. Will a browser make http request for the following cases? 182 | 8. Which resource would be downloaded first? 183 | 9. What is an optional tag? 184 | 10. What are the differences between div and span? 185 | 11. How would you differentiate between div, section, and article? 186 | 12. How would you select svg or canvas for your site? 187 | 13. How to serve html in multiple languages? 188 | 14. Explain standard and quirks mode. 189 | 15. What is a semantic tag? 190 | 191 | #### [HTML: Answers for Basic Questions](http://www.thatjsdude.com/interview/html.html) 192 | 193 | 194 | ## [JavaScript: LinkedList (part 4: work in process)](http://www.thatjsdude.com/interview/linkedList.html) 195 | Very rough stage..need to finish (for intermediate) 196 | 197 | ## [JavaScript: search and Sort (part 5: work in process)](http://khan4019.github.io/front-end-Interview-Questions/sort.html) 198 | Very rough stage..need to finish (for expert) 199 | 200 | ## [JavaScript: Binary Search Tree (part 6: work in process)](http://khan4019.github.io/front-end-Interview-Questions/bst.html) 201 | Very rough stage..need to finish (for expert) 202 | __________________ 203 | 204 | ## Another Important Questions 205 | 206 | 207 | ## Table of Contents 208 | 209 | 1. [What is a closure?](#1-what-is-a-closure) 210 | 2. [What is the difference between apply, call, and bind?](#2-what-is-the-difference-between-apply-call-and-bind) 211 | 3. [What is event delegation?](#3-what-is-event-delegation) 212 | 4. [What is event bubbling?](#4-what-is-event-bubbling) 213 | 5. [What is hoisting and how does it work?](#5-what-is-hoisting-and-how-does-it-work) 214 | 6. [What does this console?](#6-what-does-this-console) 215 | 7. [What is the prototype chain?](#7-what-is-the-prototype-chain) 216 | 8. [What does this console?](#8a-what-does-this-console) 217 | 9. [Rapid-fire questions!](#9-rapid-fire-questions) 218 | 10. [What determines the value of ‘this’?](#10-what-determines-the-value-of-this) 219 | 11. [What is the event loop?](#11-what-is-the-event-loop) 220 | 12. [What is the output?](#12-what-is-the-output) 221 | 15. [Implement curry.](#15-implement-curry-such-that) 222 | 223 | ---------------- 224 | 225 | # 1. What is a closure? 226 | 227 | - Access to local variables, parameters, variables in the parent scope, and global variables 228 | - 'Remembers' the environment in which it was created 229 | - Still has access to those variables even after the outer function has returned 230 | 231 | MDN: A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression). 232 | 233 | 'A closure is formed when an inner function is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned. At which point it still has access to the local variables, parameters and inner function declarations of its outer function.' 234 | 235 | Source: 236 | 237 | - [MDN Definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) 238 | - [Understanding Closures with Ease](http://javascriptissexy.com/understand-javascript-closures-with-ease/) 239 | 240 | 241 | # 2. What is the difference between apply, call, and bind? 242 | 243 | - Bind allows us to set the `this` value on methods 244 | - Allows us to borrow methods 245 | - '`bind` allows us to easily set which specific object will be bound to this when a function or method is invoked.' 246 | - Bind returns a function, call & apply invoke immediately 247 | - Apply allows us to execute a function with an array of parameters 248 | - each parameter is passed to the function individually 249 | - good for varying number of arguments 250 | - Call is similar to bind, but takes parameters separated by commas 251 | 252 | Source: 253 | 254 | - [JS Is Sexy - JavaScript’s Apply, Call, and Bind Methods](http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/) 255 | - [MDN Bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) 256 | 257 | 258 | 259 | 260 | # 3. What is event delegation? 261 | 262 | 263 | - Event delegation is a strategy where you attach your event handlers to a parent element rather than on multiple child elements 264 | - Classic example: a list (i.e. `ul`) with multiple `li` children. 265 | - If you want to attach some behavior for when the user clicks an `li`, you could either: 266 | - 1) attach an event handler to each `li` specifically, or 267 | - 2) attach one event listener to the parent `ul` and determine which child element was clicked by inspecting the event object itself when it bubbles up. 268 | 269 | This can simplify things quite a bit, especially when `li` elements are going to be added and removed dynamically. It can be a hassle to manually attach and remove all those individual handlers. 270 | 271 | Source: 272 | 273 | - [David Walsh - How JavaScript Event Delegation Works](https://davidwalsh.name/event-delegate) 274 | - [Javascript Info - Event Delegation](http://javascript.info/tutorial/event-delegation) 275 | 276 | # **4. What is event bubbling?** 277 | 278 | 279 | - Event bubbling has to do with how events are propagated through elements in the DOM 280 | - When you click on an element (an li for example), that element will receive the event and then, unless you explicitly stop propagation, the event will "bubble up" to its parent element (the ul), and so on 281 | - After an event triggers on the deepest possible element, it then triggers on parents in nesting order. 282 | - The bubbling guarantees that click on Div 3 will trigger onclick first on the innermost element 3 (also caled the target), then on the element 2, and the last will be element 1. 283 | - The order is called a bubbling order, because an event bubbles from the innermost element up through parents, like a bubble of air in the water. 284 | - deepest element that triggered the element is called the `event.target` or `event.srcElement` 285 | 286 | ![title](http://javascript.info/files/tutorial/browser/events/event-order-bubbling.gif) 287 | 288 | 289 | Source: 290 | 291 | - [JS Info - What is event bubbling and capturing?](http://javascript.info/tutorial/bubbling-and-capturing) 292 | - [Stack Overflow - What is event bubbling and capturing?](https://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing) 293 | 294 | # **5. What is hoisting and how does it work?** 295 | 296 | 297 | [MDN](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting): 298 | 299 | - 'Hoisting is JavaScript's behavior of moving declarations to the top of a scope (the global scope or the current function scope).' 300 | - Compiler reads the entire program to find which functions/variables you have used 301 | - Only declarations are hoisted, not initializations 302 | 303 | 304 | # 6. What does this console? 305 | 306 | ```js 307 | var a = 1; 308 | 309 | function b() { 310 | a = 10; 311 | return; 312 | 313 | function a() {} 314 | 315 | } 316 | b(); 317 | console.log(a) 318 | ``` 319 | 320 | ### Answer: 321 | 322 | ``` 323 | 1 324 | ``` 325 | 326 | - within function `b`, the inner function `a` is hoisted to the top of the scope, before `a` is re-assigned to a value of 10. 327 | - because `a` is hoisted to the top of the scope (within `b`), the re-assignment of 10 does not change the global variable `a`. 328 | 329 | # 7. What is the prototype chain? 330 | 331 | - Each object has an internal property called prototype, which links to another object 332 | - The prototype object has a prototype object of its own, and so on – this is referred to as the prototype chain 333 | - If you follow an object’s prototype chain, you will eventually reach the core Object prototype whose prototype is null, signalling the end of the chain. 334 | 335 | What is the prototype chain used for? 336 | 337 | - When you request a property which the object does not contain, JavaScript will look down the prototype chain until it either finds the requested property, or until it reaches the end of the chain 338 | - This behaviour is what allows us to create “classes”, and implement inheritance. 339 | 340 | Source: 341 | 342 | - [MDN - Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) 343 | - [JS Is Sexy - JavaScript Prototype in Plain Language](http://javascriptissexy.com/javascript-prototype-in-plain-detailed-language/) 344 | 345 | # 8a What does this console? 346 | 347 | ```js 348 | for (var i = 0; i < 5; i++) { 349 | setTimeout(function() { 350 | console.log(i) 351 | }, i); 352 | } 353 | ``` 354 | 355 | ### Answer: 356 | 357 | Almost simultaneously, 358 | 359 | ``` 360 | 5 361 | 5 362 | 5 363 | 5 364 | 5 365 | ``` 366 | 367 | `i` is 5 because the for loop has completed and exited by the time the callback in setTimeout is called. Since the value of `i` in each callback is not bound to a specific value of i, every callback returns the current value of `i`. 368 | 369 | It seems simultaneous because setTimeout delay is set on 0, 1, 2, 3, and 4 ms. 370 | 371 | # 8b What does this console? 372 | 373 | ```js 374 | for (var i = 0; i < 5; i++) { 375 | setTimeout(function() { 376 | console.log(i) 377 | }, i*500); 378 | }; 379 | ``` 380 | 381 | ### Answer: 382 | 383 | 500ms apart each: 384 | 385 | ``` 386 | 5 387 | 5 388 | 5 389 | 5 390 | 5 391 | ``` 392 | 393 | Similar answer as above, but the callback is now being called at 0ms, 500ms, 1s, 1.5s, and 2s. 394 | 395 | # 8c How would you turn this code into its intended effect? 396 | 397 | For example, how could you produce the output 398 | 399 | ``` 400 | 0 401 | 1 402 | 2 403 | 3 404 | 4 405 | ``` 406 | 407 | with 500ms apart? 408 | 409 | ### One answer: 410 | 411 | ```js 412 | for (var i = 0; i < 5; i++) { 413 | (function(i) { 414 | setTimeout(function() { 415 | console.log(i); 416 | }, i * 500); 417 | })(i); 418 | } 419 | ``` 420 | 421 | Turn it into an IIFE and pass the value of `i` for each one. 422 | 423 | ### Another answer: 424 | 425 | ```js 426 | for (var i = 0; i < 5; i++) { 427 | setTimeout(function(num) { 428 | console.log(num) 429 | }.bind(this, i), i*500); 430 | } 431 | ``` 432 | 433 | Use 'bind' to bind the value of `i` for each callback. 434 | 435 | 436 | # 9. Rapid-fire questions! 437 | 438 | What is ... 439 | 440 | 1. `console.log(typeof [])` ? 441 | 2. `console.log(typeof arguments)`? 442 | 3. `console.log(typeof "hi")`? 443 | 4. `console.log(typeof new String('hi'))` 444 | 5. `console.log(typeof NaN)`? 445 | 6. `console.log(2+true)`? 446 | 7. `console.log('6'+9)`? 447 | 8. `console.log(4+3+2+"1")`? 448 | 9. `console.log(-'34'+10)`? 449 | 10. `var a = (2, 3, 5); console.log(a)`? 450 | 11. `console.log(3 instanceof Number)`? 451 | 12. `console.log(typeof null)`? 452 | 453 | 454 | 455 | ### 9. Answers 456 | 457 | 1. `console.log(typeof [])` ? `object`. Array is derived from Object. 458 | 2. `console.log(typeof arguments)`? `object`. arguments is an array-like object. 459 | 3. `console.log(typeof "hi")`? `string`. This is a string primitive. 460 | 4. `console.log(typeof new String('hi'))` ? `object`. Using `new String` constructor makes it an object. 461 | 5. `console.log(typeof NaN)`? `number`. Sidenote: ES6 has a `Number.isNaN` function that will reliably test whether `x` is `NaN` or not, unlike the ES5 `isNaN` - see [Flaws of ES5 `isNaN`](http://ariya.ofilabs.com/2014/05/the-curious-case-of-javascript-nan.html). [Stack Overflow explanation why NaN is a type of number](https://stackoverflow.com/questions/2801601/why-does-typeof-nan-return-number). 462 | 6. `console.log(2+true)`? 3. true is coerced into 1. 463 | 7. `console.log('6'+9)`? `69` 464 | 8. `console.log(4+3+2+"1")`? `91`. Evaluated from left to right. 465 | 9. `console.log(-'34'+10)`? -24. -34 is coerced to -34, in the same way +`34` is coerced to 34. 466 | 10. `var a = (2, 3, 5); console.log(a)`? 5. The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand. [Detailed explanation](https://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/) 467 | 11. `console.log(3 instanceof Number)`? `false`, because 3 is a primitive. `console.log(new Number(4) instanceof Number)` will return true. 468 | 12. `console.log(typeof null)`? 'object'. 469 | 470 | 471 | 472 | 473 | # 10. What determines the value of 'this'? 474 | 475 | [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this): 476 | 477 | - determined by how a function is called 478 | - can't be set by assignment during execution 479 | 480 | 481 | 4 main patterns: 482 | 483 | - global reference (`this` usually refers to global object) 484 | - free function invocation (global object) 485 | - call/apply (first argument to call/apply) 486 | - method invocation (object on the left of dot, at **call time**) 487 | - construction mode (new object created for that invocation) 488 | 489 | 490 | See HR notes on summary of binding patterns for `this` (since it is copyrighted material I won't put it here) 491 | 492 | 493 | 494 | # 11. What is the event loop? 495 | 496 | - event loop runs in a single thread 497 | - want to avoid blocking the whole thread 498 | - non-blocking I/O - define a callback that is called once the action is complete 499 | - incoming callbacks are like events that are propagated to the event loop, which checks for new events in the queue and processes them 500 | - instead of waiting for the results, you can register callbacks that are executed when the event is triggered - so that you can deal with long-taking actions 501 | 502 | 503 | I ***highly*** recommend, especially if you have difficulties understanding the event loop and questions like #8 and #14, to watch this video: **[What the heck is the event loop anyway?](http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html)** 504 | 505 | Other: 506 | 507 | - [Altitude Labs - What is the JavaScript Event Loop?](http://altitudelabs.com/blog/what-is-the-javascript-event-loop/) 508 | - [MDN - Concurrency model and Event Loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop) 509 | 510 | # -- Questions taken from [JS By Examples](https://github.com/bmkmanoj/js-by-examples/tree/master/examples) -- 511 | 512 | # 12. What is the output? 513 | 514 | ```js 515 | var name = "John"; 516 | 517 | (function(){ 518 | console.log("The name is : " + name); 519 | 520 | var name = "Jane"; 521 | 522 | console.log("The name is : " +name); 523 | })(); 524 | ``` 525 | 526 | ## Answer: 527 | 528 | ``` 529 | The name is : undefined 530 | The name is : Jane 531 | 532 | ``` 533 | 534 | Explanation in [JS By Examples](https://github.com/bmkmanoj/js-by-examples/blob/master/examples/function_scope_and_hoisting.md) 535 | 536 | # 13. What is the output? 537 | 538 | ```js 539 | 540 | var data = [0, 1, 2]; 541 | var funcs = []; 542 | 543 | function init() { // 0 544 | for (var i = 0; i < 3; i++) { 545 | 546 | var x = data[i]; // 1 547 | var innerFunc = function() { // 2 548 | return x; 549 | }; 550 | 551 | funcs.push(innerFunc); // 3 552 | } 553 | } 554 | 555 | function run() { // 4 556 | for (var i = 0; i < 3; i++) { 557 | console.log(data[i] + ", " + funcs[i]()); // 5 558 | } 559 | } 560 | 561 | init(); 562 | run(); 563 | 564 | ``` 565 | 566 | ## Answer: 567 | 568 | ``` 569 | 0, 2 570 | 1, 2 571 | 2, 2 572 | ``` 573 | 574 | Detailed solution by [JS By Examples](https://github.com/bmkmanoj/js-by-examples/blob/master/examples/closures_in_loop.md). 575 | 576 | 577 | # 14. What is the output? 578 | 579 | ```js 580 | (function() { 581 | console.log(1); 582 | setTimeout(function() { 583 | console.log(2) 584 | }, 2000); 585 | setTimeout(function() { 586 | console.log(3) 587 | }, 0); 588 | console.log(4); 589 | })(); 590 | ``` 591 | 592 | 593 | Answer: 594 | 595 | ``` 596 | 1 597 | 4 598 | 3 599 | 2 600 | ``` 601 | 602 | Solution by [JS Examples](https://github.com/bmkmanoj/js-by-examples/blob/master/examples/time_for_some_timeout.md) 603 | 604 | 605 | 606 | # 15. Implement curry such that: 607 | 608 | ```js 609 | var add = curry(function(a, b, c) { 610 | return a + b + c; 611 | }); 612 | 613 | console.log(add(1)(2)(3)); 614 | console.log(add(1, 2)(3)); 615 | console.log(add(1)(2, 3)); 616 | console.log(add(1,2,3)); 617 | ``` 618 | 619 | 620 | 621 | ### One possible solution 622 | 623 | This is just my own solution. Aside: [`func.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) specifies the number of arguments expected by the function. 624 | 625 | ```js 626 | var curry = function(func) { 627 | var totalNumArgs = func.length; 628 | 629 | return function curriedFunc() { 630 | var args = [].slice.call(arguments); 631 | if (args.length === totalNumArgs) { 632 | return func.apply(null, args); 633 | } else { 634 | return function () { 635 | var args2 = [].slice.call(arguments); 636 | return curriedFunc.apply(null, args.concat(args2)); 637 | }; 638 | } 639 | }; 640 | }; 641 | ``` 642 | 643 | 644 | 645 | --------------------------------------------------------------------------------