[
  {
    "path": "README.md",
    "content": "Interview Questions for Front-end Developers\n=============================\n\nHow do you validate your markup and why?\n--------\nW3C validator.\n100% valid code is not always the goal, but it helps to write maintainable code.\nTo ensure the code is rendered consistently cross-browser.\n\nWhy use a Doctype?\n--------\nA proper Doctype triggers standards mode in your browser.\n\nWhat is CDATA?\n--------\nUsed to be required to escape JavaScript in Doctypes prior to HTML5 in order to validate code.\n\n\nHow do you waste time in JavaScript?\n--------\nRedraw parts of the DOM, e.g. increase font-size in a loop.\nSee http://www.bennadel.com/blog/2370-Overcoming-Asynchronous-Anxiety-By-Testing-JavaScript-s-Event-Loop.htm\n\nExplain hoisting in JavaScript\n--------\nIn JavaScript function declarations ( function foo() {} ) and variable declarations ( var bar  ) are ‘hoisted’ i.e. are silently moved to the very top of the scope.\n\nWithin its current scope, regardless of where a variable is declared, it will be, behind the scenes, hoisted to the top. However, only the declaration will be hoisted. If the variable is also initialized, the current value, at the top of the scope, will initially be set to undefined.\n\n```javascript\n var myvar = 'my value';\n(function() {\n  alert(myvar); // undefined\n  var myvar = 'local value'; // only the declararion of the variable (var myvar) was hoisted to the top of the scoope\n})();\n```\nAbove, the declaration was hoisted, but the initialization ( = 'local value') was not, resulting in an undefined error.\n\n\nWhat is the difference between var x = 1 and x = 1?\n--------\nNovice JS programmers might have a basic answer about locals vs globals\n\nIntermediate JS guys should definitely have that answer, and should probably mention function-level scope\n\n\"advanced\" JS programmer should be prepared to talk about locals, implied globals (defined without var, assumed belongs to window DOM, problem if third-party script uses same var name and uses var, they can conflict), the window object, function-scope, declaration hoisting (if statements do not create new scope, only functions do), and . Furthermore, I'd love to hear about [[DontDelete]], hoisting precedence (parameters vs var vs function), and undefined.\n\nSee\nhttp://sharkysoft.com/tutorials/jsa/content/031.html\nhttp://schalk-neethling.com/2011/07/quick-tip-the-problem-with-implied-globals-in-javascript/\nhttp://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting\nhttp://stackoverflow.com/questions/1484143/scope-chain-in-javascript\n\nAre objects passed by reference or by value?\n-----------\nBy reference. In JavaScript, all objects are passed by reference. When you make a change to a reference to an object, you change the actual object. Primitive types are passed by value.\n\nIs an Array an Object in JavaScript?\n-----------\nYes, Arrays inherit from Objects, and they have array-specific methods such as sort and length.\n\nExplain bit shifting in JavaScript\n----------\nOperands are treated as 32-bit integers. \nhttp://jsfiddle.net/andyshora/M4xAB/\n```javascript\nvar temp;\ntemp = 5 >> 1; // 101 -> 10 = 2\ntemp = 8 >> 1; // 1000 -> 100 = 4\ntemp = 10 >> 1; // 1010 -> 101 = 5\n// test\ndocument.write(temp);\n```\n\nWhat is the difference between using dot notation and bracket notation when accessing an object’s property?\n-----------\n```javascript\nval = ford.speed; // speed has to be a defined property\n\nval = ford['speed']; \nval = ford[ attr ]; // attr is a variable which may for example hold a string for the property name\nval = ford[ nextAttr() ]; // method call will return before accessing ford object\n```\n\nWhy might a programmer have defined a variable with a capital letter?\n-----------\nAs a constructor for an Object. Instance names should be lower case.\n```javascript\n// example\n\nvar Car = new function(){\n\tthis.wheels = 4;\n}\n// instance of Car\nvar ford = new Car();\n```\n\nthis and its scope\n-----------\n```javascript\ndrink = 'soda'; //global variable\n\nvar Foo = function(){\n    this.drink = 'beer'; //property of instance object\n    console.log('Foo() -> ' + this.drink);\n};\n\nfunction bar(){\n    console.log('bar() -> ' + this.drink);\n};\n\nvar qux = {\n    drink: 'wine', // in the scope of qux, 'drink' = 'wine'\n    getDrink: function(){\n        console.log('qux() -> ' + this.drink);\n    }\n};\n\n//now see how \"this' differs in each case\n                    \nvar baz = new Foo(); // Foo() -> beer\nbar(); // bar() -> soda\nqux.getDrink(); // qux() -> wine\n```\n\n\nWhat is a closure?\n--------\nA closure is formed when you nest functions, inner functions can refer to the variables present in their outer enclosing functions even after their parent functions have already executed.\n\nWhat language is JavaScript based on?\n--------\nECMAScript = core language that JS is based on.\n\n\nWhat's the difference between a variable and a property?\n--------\nvar a = 'hello'; // variable\nYou cant access variables with a . from the owner, you just need to know that they're there.\n\nProperties are the building blocks of objects.\nfoo.bar \n\nThey only appear interchangeable if the parent objects are the same\n\n\nWrite a function to add arguments together\n---------\n```javascript\nfunction sum() {\n  var i, l, result = 0;\n  for (i = 0, l = arguments.length; i < l; i++) {\n    result += parseInt(arguments[i]);\n  }\n  return result;\n}\n\nsum(1,2,3); // 6\n```\nAnd they should invoke it on your array like this (context for apply can be whatever, I usually use null in that case):\n```javascript\nvar data = [1,2,3];\nsum.apply(null, data); // 6\n```\n\nWhy use frameworks?\n---------\nGood coders code, great coders reuse. Thousands of man hours have been poured into these libraries to abstract DOM capabilities away from browser specific implementations. There's no reason to go through all of the different browser DOM headaches yourself just to reinvent the fixes.\n\nWhy use prototype to define methods instead of static methods?\n---------\nYou are extending the constructor function when you use prototype, so it will be available to all the object instances created with the new keyword, and the context within that function (the this keyword) will refer to the actual object instance where you call it.\n\n```javascript\n// constructor function\nfunction MyClass () {\n  var privateVariable; // private member only available within the constructor fn\n\n  this.privilegedMethod = function () { // it can access private members\n    //..\n  };\n}\n\n// A 'static method', it's just like a normal function \n// it has no relation with any 'MyClass' object instance\nMyClass.staticMethod = function () {};\n\nMyClass.prototype.publicMethod = function () {\n  // the 'this' keyword refers to the object instance\n  // you can access only 'privileged' and 'public' members\n};\n\nvar myObj = new MyClass(); // new object instance\n\nmyObj.publicMethod();\nMyClass.staticMethod();\n```\n\nPublic, private and privaledged members in JavaScript\n---------\n```javascript\n//Private\n\n// Constructor\nfunction Kid (name) {\n\t// Private\n\tvar idol = \"Paris Hilton\";\n}\n```\n\nYou can delete or replace a privileged method, but you cannot alter its contents.\n```javascript\n// Constructor\nfunction Kid (name) {\n\t// Private\n\tvar idol = \"Paris Hilton\";\n\t\n\t// Privileged\n\tthis.getIdol = function () {\n\t\treturn idol;\n\t};\n}\n```\n\nA static member is shared by all instances of the class as well as the class itself (i.e. the Kid object), but it is only stored in one place. This means that its value is not inherited down to the object’s instances\n```javascript\n// Constructor\nfunction Kid (name) {\n\t// Constructor code\n}\n\n// Static property\nKid.town = \"South Park\";\n\n\n// Public\n// Constructor\nfunction Kid (name) {\n\t// Public\n\tthis.name = name;\n}\nKid.prototype.getName = function () {\n\treturn this.name;\n};\n\n// ---------------------- all examples\n\n// Constructor\nfunction Kid (name) {\n\t// Private\n\tvar idol = \"Paris Hilton\";\n\t\n\t// Privileged\n\tthis.getIdol = function () {\n\t\treturn idol;\n\t};\n\t\n\t// Public\n\tthis.name = name;\n}\n\n// Public\nKid.prototype.getName = function () {\n\treturn this.name;\n};\n\n// Static property\nKid.town = \"South Park\";\n\n// ---------------- usage\n\n // Create a new instance\n\nvar cartman = new Kid(\"Cartman\");\n\n// Access private property\ncartman.idol; // undefined\n\n// Access privileged method\ncartman.getIdol(); // \"Paris Hilton\"\n\n// Access public property\ncartman.name; // \"Cartman\"\n\n// Access public method\ncartman.getName(); // \"Cartman\"\n\n// Access static property on an instance\ncartman.town; // undefined\n\n// Access static property on the constructor object\nKid.town; // \"South Park\"\n```\n\nSee http://robertnyman.com/2008/10/14/javascript-how-to-get-private-privileged-public-and-static-members-properties-and-methods/\n\nWhat is Progressive Enhancement?\n----------\nProgressive Enhancement consists of the following core principles:\n\nbasic content should be accessible to all browsers\nbasic functionality should be accessible to all browsers\nsparse, semantic markup contains all content\nenhanced layout is provided by externally linked CSS\nenhanced behavior is provided by [[Unobtrusive JavaScript|unobtrusive]], externally linked JavaScript\nend user browser preferences are respected\n\nCan you describe the difference between progressive enhancement and graceful degradation?\n----------\nDescribe feature detection.\nWhen features are not supported, maintain accessibility.\nContent should always be accessible, but user experience sacrificed for older browsers. Try to keep all functionality, and try to keep custom solutions compartmentalised where necessary, for example, in external files loaded for specific browsers.\n\nIf you have 10 different stylesheets for a given design, how would you integrate them into the site?\n----------\nFile concatenation and minification in the build process.\nDon't use @import as it results in an additional request.\n\nHow would you reduce page load time/perceived load time?\n----------\nReduce image sizes\nUse image sprites\nImage datauris inline for small things like avatars\nConcatenate assets\nHost assets on different hostnames\nUse CDN for assets\nLoad content async and feedback loading state to user\nMinify scripts and stylesheets\nPage data\nCache files\n\n\nWhat is FOUC? How do you avoid FOUC?\n----------\nhttp://www.learningjquery.com/2008/10/1-way-to-avoid-the-flash-of-unstyled-content\nhttp://paulirish.com/2009/avoiding-the-fouc-v3/\n\n\nWhat's a doctype do, and how many can you name?\n----------\nWhen you use a DOCTYPE declarations in your web pages, you are telling the web browser what version of (X)HTML your web page should be displayed in. The doctype gives the browser a list of supported tags and does not include any deprecated or proprietary tags in the list. You can get away with writing invalid or incorrect HTML code because most web browsers are amazingly forgiving.\n\n\nTo define the language of a section of the document, add the lang attribute to the appropriate element, such as a div element:\n\n\nHow do you serve a page with content in multiple languages?\n----------\n```html\n<div lang=\"fr-CA\" xml:lang=\"fr-CA\">\n Canadian French content...\n </div>\n <div lang=\"en-CA\" xml:lang=\"en-CA\">\n Canadian English content...\n </div>\n```\n\nProbably use a CMS to serve up different content, but same styles.\n\nWhat are data- attributes good for?\n---------\nStoring data in the DOM\n\nWhat's the difference between Java and JavaScript?\n---------\nHere are some differences between the two languages:\n\nJava is an OOP programming language while Java Script is an OOP scripting language.\nJava creates applications that run in a virtual machine or browser while JavaScript code is run on a browser only.\nJava code needs to be compiled while JavaScript code are all in text.\n\nJava is a statically typed language; JavaScript is dynamic.\nJava is class-based; JavaScript is prototype-based.\nJava constructors are special functions that can only be called at object creation; JavaScript \"constructors\" are just standard functions.\nJava requires all non-block statements to end with a semicolon; JavaScript inserts semicolons at the ends of certain lines.\nJava uses block-based scoping; JavaScript uses function-based scoping.\nJava has an implicit this scope for non-static methods, and implicit class scope; \nJavaScript has implicit global scope.\n\nHere are some features that I think are particular strengths of JavaScript:\n\nJavaScript supports closures; Java can simulate sort-of \"closures\" using anonymous classes. (Real closures may be supported in a future version of Java.)\nAll JavaScript functions are variadic; Java functions are only variadic if explicitly marked.\nJavaScript prototypes can be redefined at runtime, and has immediate effect for all referring objects. Java classes cannot be redefined in a way that affects any existing object instances.\nJavaScript allows methods in an object to be redefined independently of its prototype (think eigenclasses in Ruby, but on steroids); methods in a Java object are tied to its class, and cannot be redefined at runtime.\n\n\nHow would you optimize a websites assets/resources?\n---------\nFile concatenation\nFile minification\nCDN Hosted\nCaching\netc.\n\nWhy is it better to serve site assets from multiple domains?\n---------\nBrowsers restrict simultaneous downloads per domain, so you can just add different A records to point to the same location if you like, or create different buckets on a blob storage account.\n\n\n\n\nAdvantages of LESS\thttp://tympanus.net/codrops/2012/01/27/modular-front-end-development-with-less/\n---------\nVariables. Define any variable like so: @color1: #df0290;and use it later in your code:\nMixins.Define useful functions with or without parameters\nNested rules.Pretty self-explanatory, as I’m sure this is something you’ve been wishing for in CSS since you started using it\n\nWhat does & stand for in LESS?\n-----------\nAn ampersand (&) refers to the parent rule. So &.category would translate to article h2.category once the LESS code had been compiled.\n\nHow would you organize a LESS library for a large project?\n-----------\n/project/css/\n- reset.css — resets default browser styling\n- grid.less — supplies mixins for a grid system, such as the .col(@width) mixin above\n- type.less — supplies mixins for font styling as well as @font-face rules\n- colorscheme.less — LESS variables for the design’s various colors\n- interface.less — mixins for interface features like buttons, forms, and dialogs\n- layout.less — design-specific layout of the site\n- style.less — the main stylesheet, including all of the above and adding in whatever site-specific styles are otherwise necessary\n\nExample LESS template - colorscheme.less\n------------\n```css\n@background: \t\t#ffffff;\n@textcolor: \t\t#252525;\n@textcolor-strong:\t#090909;\n@textcolor-em:\t\t#666666;\n@textcolor-blockquote:\t#aaaaaa;\n\n@accent1:\t\t#2d9681;\n@accent2:\t\t#f8a34b;\n\n@warning:\t\t#d4230f;\n```\n\nCSS3 Advantages with LESS\n-----------\nLong repetitive CSS3 code such as gradients, keyframe animations, can all be simplified with Mixins, taking in for example keyframe durations, percentages, animation and easing types as parameters. For gradients, start and stop colours, and blending positions can be controlled with variables.\n\nHow does the content model differ in HTML4/5?\thttp://www.w3.org/TR/html5-diff/#content-model\n------------\nContent model is what defines how elements may be nested — what is allowed as children (or descendants) of a certain element.\n\nAt a high level, HTML4 had two major categories of elements, \"inline\" (e.g. span, img, text), and \"block-level\" (e.g. div, hr, table). Some elements did not fit in either category.\n\nSome elements allowed \"inline\" elements (e.g. p), some allowed \"block-level\" elements (e.g. body), some allowed both (e.g. div), while other elements did not allow either category but only allowed other specific elements (e.g. dl, table), or did now allow any children at all (e.g. link, img, hr).\n\nNotice the difference between an element itself being in a certain category, and having a content model of a certain category. For instance, the p element is itself a \"block-level\" element, but has a content model of \"inline\".\n\nTo make it more confusing, HTML4 had different content model rules in its Strict, Transitional and Frameset flavors. For instance, in Strict, the body element allowed only \"block-level\" elements, but in Transitional, it allowed both \"inline\" and \"block-level\".\n\nTo make things more confusing still, CSS uses the terms \"block-level element\" and \"inline-level element\" for its visual formatting model, which is related to CSS's 'display' property and has nothing to do with HTML's content model rules.\n\nHTML5 does not use the terms \"block-level\" or \"inline\" as part of its content model rules, to reduce confusion with CSS. However, it has more categories than HTML4, and an element can be part of none of them, one of them, or several of them.\n\nFunction.prototype.bind\n----------\n\n\nCan you explain how inheritance works in JavaScript?\n----------\nExplain how scope works.\n\nThen show how objects can inherit properties:\nhttp://jsfiddle.net/andyshora/nvcZE/\n```javascript\n(function() {\n    var genericObject = {\n        bar : \"Hello World\",\n        get_bar : function() {\n            return this.bar;\n        }\n    };\n    var customObject = Object.create(genericObject);\n    customObject.bar = \"Aloha folks!\";\n    document.write(customObject.get_bar() + '<br />'); //outputs: \"Aloha folks\"\n    delete customObject.bar;\n    document.write(customObject.get_bar()); //fallbacks to the prototype's value, outputs: \"Hello World\"\n})();\n```\n\nWhen would you use document.write()?\n----------\nWhen messing around on jsfiddle or debugging code perhaps!\n\n\nChallenges\n----------\n1. Write a function to reverse a string\nhttp://jsfiddle.net/andyshora/8zby5/\n```javascript\n// a function to reverse a string\nfunction reverseString(str){\n    if (str===undefined) return false;\n    if (str.length < 2) return str;\n    \n    return str.split('').reverse().join('');\n}\ndocument.write(reverseString(\"hello\"));\n```\n2. Implement a function to detect palindromes.\nhttp://jsfiddle.net/andyshora/WN2Bv/\n```javascript\n// function to detect palindromes\nfunction isPalindrome(str){\n    if (typeof str!=='string') return false;\n    if (!str.length) return false;\n    \n    var len = str.length;\n    var arr = str.split(''); // split string into array\n    var breakAt = Math.floor(len/2);\n    \n    for (var i=0; i<len; i++){\n        if (i===breakAt) break;\n        if (arr[i]!==arr[(len-1)-i]) return false;\n    }\n    return true;\n}\ndocument.write(isPalindrome('aaaaabaaaaa'));\n```\n3. Calculate the number of digits for a given number.\n4. Implement a function that calculates square roots\nhttp://jsfiddle.net/andyshora/W5Gzj/2/\n```javascript\n// function to manually calculate square root in javascript\n// returns false on error or no integer square root\nfunction calcSquareRoot(x){\n    \n    if (typeof x !== 'number') return false;\n    if (x===1) return x; // test for 1, quickest = doesnt mess with logic below\n    if (i<0) return false;\n    \n    for(var i=2; i<=(x/2); i++){\n        if (i*i === x) return i;\n    }\n    \n    return false;\n}\ndocument.write(calcSquareRoot(225)); // 15\ndocument.write('<br />');\ndocument.write(calcSquareRoot(226)); // false\ndocument.write('<br />');\ndocument.write(calcSquareRoot(-1)); // false\ndocument.write('<br />');\ndocument.write(calcSquareRoot(1)); // 1\ndocument.write('<br />');\ndocument.write(calcSquareRoot('2')); // false\ndocument.write('<br />');\ndocument.write(calcSquareRoot(4)); // 2\n```\n\n5. Sort and concat arrays in a optimal way\n6. Guess the two missing numbers in a array with n - 2 length containing 1..n unsorted numbers"
  }
]