├── nodejs └── README.md ├── patterns ├── README.md ├── facade.md └── mediator.md ├── algorithms └── README.md ├── databases ├── README.md ├── having.md └── capTheorem.md ├── javascript ├── callVsApply.md ├── duplicate.md ├── documentVsDOMLoadEvent.md ├── documentWrite.md ├── lateBinding.md ├── repaint.md ├── reverseLoops.md ├── newVsFunction.md ├── closure.md ├── featureDetection.md ├── problems │ ├── anagramArray.md │ ├── stringPermutations.md │ ├── gcd.md │ ├── nextBiggerInteger.js │ ├── towerBuilder.js │ ├── oddSort.md │ ├── maxSumSubArray.md │ ├── tracePolygon.md │ ├── defaultArguments.md │ ├── lcs.md │ ├── fizzBuzz.md │ ├── validBraces.md │ ├── foldAnArray.md │ ├── sumOfIntervals.md │ ├── float2bin.md │ ├── di.md │ ├── minerPath.md │ ├── stringsMix.md │ ├── levinshteinDistance.md │ ├── snailSort.md │ ├── binaryTreeTraversal.md │ ├── battleshipField.md │ ├── imageProcessing.md │ ├── starCatalogMatching.md │ └── maybeMonad.md ├── equalOperator.md ├── nullVsUndefined.md ├── extendingBuiltInObjects.md ├── iife.md ├── truthy.md ├── this.md ├── sameOrigin.md ├── activeElement.md ├── callbacksVsPromises.md ├── toPrimitive.md ├── hostAndNativeObjects.md ├── longPolling.md ├── attributeVsProperty.md ├── functionDeclarations.md ├── useStrict.md ├── hoisting.md ├── void.md ├── SPAvsSEO.md ├── proxyLeak.md ├── browserRender.md ├── references.md ├── reflow.md ├── checkArray.md ├── eventDelegation.md ├── ajax.md ├── syncVsAsyncFunctions.md ├── proxyVsGetters.md ├── comet.md ├── bind.md ├── eventFlow.md ├── primitives.md ├── prototypes.md ├── httpPolling.md ├── jsonp.md ├── dataTypes.md ├── promise.md ├── eventLoop.md ├── README.md ├── shrinkwrap.md └── webComponents.md ├── data-structures ├── bTree.md └── README.md ├── css ├── boxSizing.md ├── inlineBlock.md ├── marginCollapsing.md ├── cssBoxModel.md └── README.md ├── README.md ├── network ├── README.md ├── CSRF.md └── httpVsHttps.md ├── common └── functionalVsUnit.md ├── html ├── standartModes.md ├── dataAttributes.md ├── README.md ├── iconFontsVsSVG.md └── storagesVsCoockies.md └── clojure └── macros.md /nodejs/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /patterns/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /databases/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /javascript/callVsApply.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data-structures/bTree.md: -------------------------------------------------------------------------------- 1 | ## B-tree 2 | 3 | 4 | -------------------------------------------------------------------------------- /data-structures/README.md: -------------------------------------------------------------------------------- 1 | ## Data structures 2 | 3 | * [B-tree](bTree.md) 4 | -------------------------------------------------------------------------------- /javascript/duplicate.md: -------------------------------------------------------------------------------- 1 | ## Make this work: 2 | ```js 3 | [1, 2, 3, 4, 5].duplicate() // [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] 4 | ``` 5 | 6 | ## Answer 7 | 8 | ```js 9 | // But we know that extending built-in objects is a bad idea ^_^ 10 | Array.prototype.duplicate = function() { 11 | return this.contat(this) 12 | } 13 | ``` 14 | -------------------------------------------------------------------------------- /javascript/documentVsDOMLoadEvent.md: -------------------------------------------------------------------------------- 1 | ## Difference between document load event and document DOMContentLoaded event? 2 | 3 | The `DOMContentLoaded` event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. The `load` event can be used to detect a fully-loaded page. 4 | -------------------------------------------------------------------------------- /css/boxSizing.md: -------------------------------------------------------------------------------- 1 | ## What does `* { box-sizing: border-box; }` do? What are its advantages? 2 | It ebables all elements to include paddings and borders in its width. 3 | 4 | You might want to divide up my grid with 50% or 20% columns, but want to add padding via `px` or `em`. 5 | Without `calc()` this is impossible… unless you use `border-box`. 6 | Another good one is applying `100%` width and then wanting to add a padding to that element. 7 | -------------------------------------------------------------------------------- /javascript/documentWrite.md: -------------------------------------------------------------------------------- 1 | ## When would you use `document.write()`? 2 | Generally `document.write` is considered a bad practice. 3 | But it is the simpliest way to include third party content into the document. 4 | Also the shortest, and it does not cause any conflicts. 5 | You may also use `document.write` to: 6 | * include styles that should only work if JavaScript is enabled. 7 | * alter all the content of the iframe (this approach have been used to partially update the page before AJAX) 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Random answers and a bit of copy-paste. 2 | 3 | Started based on https://github.com/h5bp/Front-end-Developer-Interview-Questions 4 | 5 | # Front-end Interview Answers 6 | 7 | * [Javascript](javascript/README.md) 8 | * [Nodejs](nodejs/README.md) 9 | * [Network](network/README.md) 10 | * [CSS](css/README.md) 11 | * [HTML](html/README.md) 12 | * [Databases](databases/README.md) 13 | * [Algorithms](algorithms/README.md) 14 | * [Data Structures](data-structures/README.md) 15 | * [Patterns](patterns/README.md) 16 | -------------------------------------------------------------------------------- /css/inlineBlock.md: -------------------------------------------------------------------------------- 1 | # What is the difference between `display: inline` and `display: inline-block`? 2 | 3 | Inline elements: 4 | * respect left & right margins and padding, but not top & bottom 5 | * cannot have a width and height set 6 | * allow other elements to sit to their left and right. 7 | 8 | Block elements: 9 | * respect all of those 10 | * force a line break after the block element 11 | 12 | Inline-block elements: 13 | * allow other elements to sit to their left and right 14 | * respect top & bottom margins and padding 15 | * respect height and width 16 | -------------------------------------------------------------------------------- /javascript/lateBinding.md: -------------------------------------------------------------------------------- 1 | ## Early Binding vs Late Binding 2 | 3 | Early Binding 4 | 5 | ```js 6 | var sum = function(a, b) { 7 | return a + b; 8 | }; 9 | 10 | var x = 5, y = 6; 11 | var sum5n6 = sum.bind(null, x, y); 12 | 13 | x = 10; 14 | y = 5; 15 | console.log("with Early Binding -->", sum5n6()); 16 | ``` 17 | 18 | Late Binding 19 | 20 | ```js 21 | var sum2 = function(p) { 22 | return p.x + p.y; 23 | }; 24 | 25 | var x = 5, y = 6; 26 | var n = {x: x, y: y}; 27 | var sumLate = sum2.bind(null, n); 28 | 29 | n.x = 10; 30 | n.y = 5; 31 | 32 | console.log("Late Binding -->", sumLate()); 33 | ``` 34 | -------------------------------------------------------------------------------- /javascript/repaint.md: -------------------------------------------------------------------------------- 1 | ## What is browser repaint? 2 | 3 | A repaint occurs when changes are made to elements that affect visibility but not the layout. For example, opacity, background-color, visibility, and outline. Repaints are expensive because the browser must check the visibility of all other nodes in the DOM — one or more may have become visible beneath the changed element. 4 | 5 | Repaint is browser-blocking; neither the user or your application can perform other tasks during the time that a repaint occurring. In extreme cases, a CSS effect could lead to slower JavaScript execution. This is one of the reasons you encounter issues such as jerky scrolling and unresponsive interfaces. 6 | -------------------------------------------------------------------------------- /javascript/reverseLoops.md: -------------------------------------------------------------------------------- 1 | ## Are loops faster in reverse? 2 | 3 | It's not that `i--` is faster than `i++`. Actually, they're both equally fast. 4 | 5 | What takes time in ascending loops is evaluating, for each i, the size of your array. In this loop: 6 | 7 | ```js 8 | for(var i = array.length; i--;) 9 | ``` 10 | You evaluate `.length` only once, when you declare `i`, whereas for this loop 11 | 12 | ```js 13 | for(var i = 1; i <= array.length; i++) 14 | ``` 15 | you evaluate `.length` each time you increment `i`, when you check if `i <= array.length`. 16 | 17 | In most cases you shouldn't even worry about this kind of optimization. 18 | 19 | The fastest loop is 20 | ```js 21 | var i = arr.length; //or 10 22 | while(i--) 23 | { 24 | //... 25 | } 26 | ``` 27 | -------------------------------------------------------------------------------- /javascript/newVsFunction.md: -------------------------------------------------------------------------------- 1 | ## JS: new keyword and functions 2 | 3 | Our question is "What’s the difference between: function Person(){}, var person = new Person(), and var person = Person()?" 4 | 5 | The first one function Person(){} defines a function. Since it’s got a capital letter at the beginning of the function name we expect that it’s a constructor. 6 | 7 | Next var person = new Person() is one way to create new objects. Using this method person will have access to everything Person.prototype has access to, as well as any instance variables set in the Person constructor. 8 | 9 | Finally var person = Person() is a mistake. There are ways of dealing with mistakes like this (my preference is the "use strict" method), but ultimately this should be corrected. 10 | -------------------------------------------------------------------------------- /javascript/closure.md: -------------------------------------------------------------------------------- 1 | ## What is a closure, and how/why would you use one? 2 | 3 | Several defenitions: 4 | 5 | * closure is when a function is able to remember and access its lexical scope even when that function 6 | is executing outside its lexical scope. 7 | * a closure is one way of supporting first-class functions; 8 | it is an __expression that can reference variables within its scope__ (when it was first declared), 9 | assigned to a variable, passed as an argument to a function, or returned as a function result. 10 | * a closure is a __stack frame__ which is allocated when a function starts its execution, 11 | and not freed after the function returns (as if a 'stack frame' were allocated on the heap rather than the stack!). 12 | 13 | Used in module pattern. Can be used for currying. 14 | -------------------------------------------------------------------------------- /javascript/featureDetection.md: -------------------------------------------------------------------------------- 1 | ## What's the difference between feature detection, feature inference, and using the UA string? 2 | 3 | Feature detection checks a feature for existence, e.g.: 4 | 5 | ```js 6 | if (window.XMLHttpRequest) { 7 | new XMLHttpRequest(); 8 | } 9 | ``` 10 | 11 | Feature inference checks for a feature just like feature detection, but uses another function because it assumes it will also exist, e.g.: 12 | 13 | ```js 14 | if (document.getElementsByTagName) { 15 | element = document.getElementById(id); 16 | } 17 | ``` 18 | 19 | Checking the UA string is an old practice and should not be used anymore. You keep changing the UA checks and never benefit from newly implemented features, e.g.: 20 | 21 | ```js 22 | if (navigator.userAgent.indexOf("MSIE 7") > -1){ 23 | //do something 24 | } 25 | ``` 26 | -------------------------------------------------------------------------------- /javascript/problems/anagramArray.md: -------------------------------------------------------------------------------- 1 | ## Task 2 | 3 | Implement anagram checker: 4 | ```js 5 | ['lol', 'oll', 'react', 'actre', 'llo', 'boom'] => 6 | [ 7 | ['lol', 'oll', 'llo'] 8 | ['react', 'actre'] 9 | ] 10 | ``` 11 | 12 | ## Solution 13 | 14 | ```js 15 | function getAnagrams(words) { 16 | const normalize = word => word.toLowerCase().split('').sort().join('').trim() 17 | const map = {} 18 | let n = 0 19 | 20 | const anagrams = words.reduce((res, word, i) => { 21 | const normalized = normalize(word) 22 | 23 | if (typeof map[normalized] === 'number') { 24 | res[map[normalized]].push(word) 25 | return res 26 | } 27 | 28 | map[normalized] = n 29 | res[n] = [word] 30 | n++ 31 | 32 | return res 33 | }, []) 34 | 35 | return anagrams.filter(arr => arr.length > 1) 36 | } 37 | ``` 38 | -------------------------------------------------------------------------------- /javascript/equalOperator.md: -------------------------------------------------------------------------------- 1 | ## What is the difference between `==` and `===`? 2 | JavaScript has both strict `===` and type-converting `==` equality comparison. 3 | For strict equality the objects being compared must have the same type and: 4 | 5 | * Two strings are strictly equal when they have the same sequence of characters, 6 | same length, and same characters in corresponding positions. 7 | * Two numbers are strictly equal when they are numerically equal (have the same number value). 8 | NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another. 9 | * Two Boolean operands are strictly equal if both are true or both are false. 10 | * Two objects are strictly equal if they refer to the same Object. 11 | * `null` and `undefined` types are `==` (but not `===`). I.e. `null == undefined` is `true` but `null === undefined` is `false` 12 | -------------------------------------------------------------------------------- /javascript/nullVsUndefined.md: -------------------------------------------------------------------------------- 1 | ## What's the difference between a variable that is: `null`, `undefined` or undeclared? 2 | ### How would you go about checking for any of these states? 3 | 4 | In JavaScript, `undefined` means a variable has been declared but has not yet been assigned a value. 5 | A variable is declared if accessing the variable name will not produce a `ReferenceError`. 6 | Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed. In `strict mode` the `ReferenceError` error is thrown. 7 | 8 | ```js 9 | // Test if undefined 10 | typeof(a) === "undefined" 11 | // Test if null 12 | a === null 13 | // Test if declared 14 | var aIsDeclared = true; 15 | try{ a; } 16 | catch(e) { 17 | if(e.name == "ReferenceError") { 18 | aIsDeclared = false; 19 | } 20 | } 21 | ``` 22 | -------------------------------------------------------------------------------- /javascript/problems/stringPermutations.md: -------------------------------------------------------------------------------- 1 | ## Task 2 | 3 | Are two strings permutations of each other? 4 | 5 | ## Solution 6 | 7 | ```js 8 | function isPermutation(one, two) { 9 | if (typeof one !== 'string') { 10 | throw new Error('The given word is not a string'); 11 | } 12 | if (typeof two !== 'string') { 13 | throw new Error('The given word is not a string'); 14 | } 15 | 16 | if (one.length !== two.length) { 17 | return false; 18 | } 19 | 20 | const letters = []; 21 | let i; 22 | 23 | for (i = 0; i < one.length; i++) { 24 | letters[one[i].charCodeAt()] = letters[one[i].charCodeAt()] || 0 + 1; 25 | } 26 | 27 | for (i = 0; i < two.length; i++) { 28 | letters[two[i].charCodeAt()] = letters[two[i].charCodeAt()] || 0 - 1; 29 | if (letters[two[i].charCodeAt()] < 0) { 30 | return false; 31 | } 32 | } 33 | 34 | return true; 35 | } 36 | ``` 37 | -------------------------------------------------------------------------------- /javascript/extendingBuiltInObjects.md: -------------------------------------------------------------------------------- 1 | ## Why is extending built-in JavaScript objects not a good idea? 2 | 3 | Because it can break other things. Extending built-in types, such as Object or Array is a bad idea in Javascript because other libraries, and even client, can easily be affected. This is especially true for the Object prototype as everything in Javascript extends from it. 4 | 5 | Consider this code: 6 | ```js 7 | const x = [1, 2, 3] 8 | for (const i in x) { 9 | console.log(i) 10 | } 11 | ``` 12 | 13 | It will print 14 | ```js 15 | // 1 16 | // 2 17 | // 3 18 | ``` 19 | 20 | However if you change the array prototype, like in example below, 21 | the code will instead print: 22 | ```js 23 | Array.prototype.lalka = () => console.log('lalka') 24 | 25 | // 1 26 | // 2 27 | // 3 28 | // lalka 29 | ``` 30 | 31 | With lalka method added to the array prototype by us which can break some other library. 32 | -------------------------------------------------------------------------------- /javascript/iife.md: -------------------------------------------------------------------------------- 1 | ## Explain why the following doesn't work as an IIFE: `function foo(){ }();` 2 | 3 | This is a function definition, it defines `foo`. But it’s not a function expression - that is, it’s not understood by the JS parser to actually call a function. 4 | 5 | For the parser, things look like this: 6 | 7 | ```js 8 | function foo(){ 9 | } // ok, done with that function definition 10 | // (silly human left off the semicolon, how embarrassing!) 11 | 12 | (); // Are they trying to call something? What’s the function’s name? 13 | // PARSE ERROR 14 | ``` 15 | 16 | In order to prep the parser that we're actually dealing with a function expression we have to wrap things up in `()` like so: 17 | 18 | ```js 19 | ( // oh goody, we're going to call some function expressions! 20 | function foo(){ // here's the function definition 21 | }() // and here's where the function is actually called 22 | ); 23 | ``` 24 | -------------------------------------------------------------------------------- /javascript/problems/gcd.md: -------------------------------------------------------------------------------- 1 | ## For two given numbers find the greatest common divisor. 2 | 3 | ### Dumb solution 4 | 5 | ```js 6 | const gcd = (a, b) => { 7 | let Min = Math.min(a, b) 8 | let i = 2 9 | let gcd = 1 10 | while (i <= Min) { 11 | if (a % i === 0 && b % i === 0) { 12 | gcd = i 13 | } 14 | i++ 15 | } 16 | return gcd 17 | } 18 | export default gcd 19 | ``` 20 | 21 | ### Iterative solution 22 | 23 | ```js 24 | function gcd(a,b) { 25 | if (a < 0) a = -a; 26 | if (b < 0) b = -b; 27 | if (b > a) {var temp = a; a = b; b = temp;} 28 | while (true) { 29 | if (b == 0) return a; 30 | a %= b; 31 | if (a == 0) return b; 32 | b %= a; 33 | } 34 | } 35 | ``` 36 | 37 | ### Recursive solution 38 | 39 | ```js 40 | var gcd = function(a, b) { 41 | if ( ! b) { 42 | return a; 43 | } 44 | 45 | return gcd(b, a % b); 46 | }; 47 | ``` 48 | -------------------------------------------------------------------------------- /javascript/problems/nextBiggerInteger.js: -------------------------------------------------------------------------------- 1 | /* 2 | * You have to create a function that takes a positive integer number 3 | * and returns the next bigger number formed by the same digits: 4 | * 5 | * nextBigger(12)==21 6 | * nextBigger(513)==531 7 | * nextBigger(2017)==2071 8 | * 9 | * If no bigger number can be composed using those digits, return -1: 10 | * 11 | * nextBigger(9)==-1 12 | * nextBigger(111)==-1 13 | * nextBigger(531)==-1 14 | * 15 | */ 16 | 17 | export default function nextBigger(n) { 18 | const arr = n.toString().split('') 19 | 20 | for (let i = arr.length - 1; i >= 0; i--) { 21 | const next = i - 1 22 | 23 | if (arr[i] > arr[next]) { 24 | const suffix = arr.splice(i).sort() 25 | 26 | suffix.some((el, j) => { // eslint-disable-line 27 | if (el > arr[next]) { 28 | return [suffix[j], arr[next]] = [arr[next], suffix[j]] // eslint-disable-line 29 | } 30 | }) 31 | 32 | return Number(arr.concat(suffix).join('')) 33 | } 34 | } 35 | 36 | return -1 37 | } 38 | -------------------------------------------------------------------------------- /javascript/truthy.md: -------------------------------------------------------------------------------- 1 | ## As `[]` is true, `[]==true` should also be true. Right? 2 | 3 | You are right about first part, `[]`, empty array is an object and object is always truthy. Hence, if you use `if([]){console.log('its true')}` you will see the log. 4 | 5 | However, special case about `==` (double equal) is that it will do some implicit coercion. 6 | 7 | Since left and right side of the equality are two different types, JavaScript can't compare them directly . Hence, under the hood, JavaScript will convert them to compare. First, right side of the equality will be coerced to a number and number of true would be `1`. 8 | 9 | After that, JavaScript implementation will try to convert `[]` by using `toPrimitive` (of JavaScript implementation). Since `[].valueOf` is not primitive it will use `toString` and will get `""` 10 | 11 | Now you are comparing `"" == 1` and still left and right is not same type. Hence left side will be converted again to a number and empty string will be 0. 12 | 13 | Finally, they are of same type, you are comparing `0 === 1` which will be false. 14 | -------------------------------------------------------------------------------- /javascript/problems/towerBuilder.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Build Tower by the following given argument: 4 | * number of floors (integer and always greater than 0). 5 | * 6 | * A tower of 3 floors looks like below: 7 | * 8 | * [ 9 | * ' * ', 10 | * ' *** ', 11 | * '*****' 12 | * ] 13 | * 14 | */ 15 | 16 | const getFloorLength = n => 1 + (2 * (n - 1)) 17 | const getStarString = n => new Array(n).join('*') 18 | const getFloor = (floorLength, starPadding, middle, str) => ( 19 | str.substring(0, middle - starPadding) + 20 | getStarString(floorLength + 1) + 21 | str.substring(middle + starPadding) 22 | ) 23 | 24 | export default function towerBuilder(n) { 25 | let i = 0 26 | const res = [] 27 | const lastFloorLength = getFloorLength(n) 28 | const middle = (lastFloorLength - 1) / 2 29 | const init = new Array(lastFloorLength).join(' ') 30 | 31 | while (i++ < n) { 32 | const floorLength = getFloorLength(i) 33 | const starPadding = (floorLength - 1) / 2 34 | res.push(getFloor(floorLength, starPadding, middle, init)) 35 | } 36 | 37 | return res 38 | } 39 | -------------------------------------------------------------------------------- /javascript/problems/oddSort.md: -------------------------------------------------------------------------------- 1 | ## Task 2 | 3 | Implement Odd sort (sort only odd indices) 4 | 5 | ```js 6 | const a = [2, 5, 4, 6, 8, 4, 3, 7, 8] 7 | //=> b = [2, 3, 4, 6, 8, 4, 5, 7, 8] 8 | ``` 9 | 10 | ## Solution 11 | 12 | Implementation of Quick sort only for odd indices. 13 | 14 | ```js 15 | const swap = (array, i, j) => [array[i], array[j]] = [array[j], array[i]] 16 | 17 | const oddSort = (array, left = 0, r) => { 18 | const right = r || array.length 19 | if (right - left < 4 || array.length < 4) { 20 | return array 21 | } 22 | 23 | const pivot = left + 1 24 | let border = left + 1 25 | 26 | for (let i = border + 2; i < array.length; i += 2) { 27 | if (array[i] < array[pivot]) { 28 | if (pivot !== border) { 29 | swap(array, border, i) 30 | } 31 | border += 2 32 | } 33 | } 34 | 35 | swap(array, border, pivot) 36 | 37 | const offset = (right - left) % 4 > 0 ? -1 : 1 // To process arrays with odd length 38 | oddSort(array, left, border - offset) 39 | oddSort(array, border + offset, right) 40 | 41 | return array 42 | } 43 | ``` 44 | -------------------------------------------------------------------------------- /javascript/problems/maxSumSubArray.md: -------------------------------------------------------------------------------- 1 | # Maximum Sum Subarray 2 | 3 | ## Task 4 | 5 | The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers: 6 | 7 | ```js 8 | maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) 9 | // should be 6: [4, -1, 2, 1] 10 | ``` 11 | 12 | Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead. 13 | 14 | Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray. 15 | 16 | ## Solution 17 | 18 | ```js 19 | const maxSequence = function(arr) { 20 | let sum = 0, max = 0 21 | for (let i = 0; i < arr.length; i++) { 22 | sum += arr[i] 23 | if (sum > max) { 24 | max = sum 25 | } 26 | if (sum < 0) { 27 | sum = 0 28 | } 29 | } 30 | return max || 0 31 | } 32 | ``` 33 | 34 | ## One-liner 35 | 36 | ```js 37 | const maxSequence = (a, sum = 0) => a.reduce((max, v) => Math.max(sum = Math.max(sum + v, 0), max), 0) 38 | ``` 39 | -------------------------------------------------------------------------------- /javascript/this.md: -------------------------------------------------------------------------------- 1 | ## Explain how `this` works in JavaScript 2 | 3 | Determining the `this` binding for an executing function requires finding the direct call-site of that function. Once examined, four rules can be applied to the call-site, in *this* order of precedence: 4 | 5 | 1. Called with `new`? Use the newly constructed object. 6 | 7 | 2. Called with `call` or `apply` (or `bind`)? Use the specified object. 8 | 9 | 3. Called with a context object owning the call? Use that context object. 10 | 11 | 4. Default: `undefined` in `strict mode`, global object otherwise. 12 | 13 | Be careful of accidental/unintentional invoking of the *default binding* rule. In cases where you want to "safely" ignore a `this` binding, a "DMZ" object like `ø = Object.create(null)` is a good placeholder value that protects the `global` object from unintended side-effects. 14 | 15 | Instead of the four standard binding rules, ES6 arrow-functions use lexical scoping for `this` binding, which means they adopt the `this` binding (whatever it is) from its enclosing function call. They are essentially a syntactic replacement of `self = this` in pre-ES6 coding. 16 | -------------------------------------------------------------------------------- /javascript/sameOrigin.md: -------------------------------------------------------------------------------- 1 | ## Explain the same-origin policy with regards to JavaScript 2 | 3 | The same-origin policy helps prevent malicious attacks by stopping code from another site executing on your site. An attacks like this is known as a Cross Site Scripting attack. 4 | 5 | How does JS decide if it’s a “same” site? 6 | 7 | The “origin” is the same if three things are the same: the protocol (http vs. https), the domain (subdomain.yoursite.com vs. yoursite.com vs. google.com), and the port (:80 vs. :4567). If all three of these line up, then JS views the sites as the same, and code is executed. If any of them are different then the code is marked as potentially malicious and is not run. 8 | 9 | Hmmm, if I own “subdomain.yoursite.com” and “yoursite.com” I might want to share resources. This same-origin policy could be really annoying! 10 | 11 | It’s possible to work around the subdomain problem. You can change the domain of a page, so it can access it’s parent’s resources: 12 | 13 | // in the code on subdomain.yoursite.com 14 | document.domain = "yoursite.com"; 15 | There are a couple other pieces to remember about changing the domain (mostly about the port). 16 | -------------------------------------------------------------------------------- /javascript/activeElement.md: -------------------------------------------------------------------------------- 1 | ## How would you get currently focused element? 2 | 3 | ```js 4 | var curElement = document.activeElement 5 | ``` 6 | 7 | `document.activeElement` returns the currently focused element, that is, the element that will get keystroke events if the user types any. This attribute is read only. 8 | 9 | Often this will return an `` or `