Sunday, August 7, 2016

Cramming for a Senior JavaScript Interview


I have made JavaScript a major part of my development career for a decade now (since the >shudder<  IE6 days!) so I have had my fair share of JavaScript interviews.  If I have not been in an interview for even a few months I try to cram the important topics that do not come up at work too often.  The simplest way to do that is review all the parts of:

JavaScript: The Good Parts   by Douglas Crockford

that I highlighted and marked the crap out of years ago. 

In the following post, I will summarize the most useful concepts from that book as well as some of the questions I have been asked numerous times. This is intended to help experienced JavaScript developers review important concepts for interview purposes.  This is not an ideal interview prep guide for beginners.

Since Douglas Crockford has spent roughly two decades explaining JavaScript concepts, it’s no surprise he simply says it better than most so the longer quotations are simply direct quotes from his book.

First quick concepts worth knowing but are easily forgotten . .

Data Types
  • Six data types that are primitives (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)
    • Boolean
    • Null
    • Undefined
    • Number
    • String
    • Symbol (new in ECMAScript 6)
  • So there is ONE number type
    • But NaN  . . is also a number
    • Note: isNan() is available
  • For Strings and arrays
    • .length  (note it’s not a function but a property)
What is the difference between Call vs apply vs Bind?
  • Said best here:
    • Call invokes the function and allows you to pass in arguments one by one (listed explicitly).
    • Apply invokes the function and allows you to pass in arguments as an array.
    • Bind returns a new function, allowing you to pass in a this array and any number of arguments.
  • And this might be the best stackoverflow answer ever:
    • The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. A useful mnemonic is "A for array and C for comma."
    • Pseudo syntax:
      • theFunction.apply(valueForThis, arrayOfArgs)
      • theFunction.call(valueForThis, arg1, arg2, ...)
What is strict mode?
  • By putting "use strict"; at the top of your code, the interpreter will throw more errors for bad practices that are technically permitted.  The major effect is it forces you to declare your variables properly and avoid using variable names that will someday be keywords.

Conditionals


  • What is the difference between == and ===?
    • === means “equality without type coercion” but == means that the second value will be converted to the data type of the first so that “equivalency” can be determined.
  • True vs False
    • Usually the concept of true and false is referred to as falsy vs truthy because the list of data types you might put in a conditional are a bit sketchy and not exactly in line with math books
    • This is explained well here but in short:
      • falsy: In javascript 6 things are falsy and they are- false, null, undefined, '', 0, NaN
      • truthy: There are only two truthy things- true and everything that is not false
    • all_things_code points out:

null == true; //false

null == false; //false!!

Objects

  • ALL objects are linked to a prototype object.  If you didn’t specify which after creating it, its prototype is pointing to Object.prototype
  • When attempting to find a property in an object, the prototype object will be searched if the object in question is missing said value through a process called delegation.
  • You can for-loop your way through the properties (not methods) of an object[1]:


    for (name in objectInstance) {
               //use name
    }        

Functions

  • “A function encloses a set of statements. Functions are the fundamental modular unit of JavaScript.”
  • “Function objects are linked to Function.prototype (which itself is linked to Object.prototype)."
  • “The Function object created by a function literal contains a link to the outer context.  This is called closure.  This is the source of enormous power.” 

this

  • Is established at invocation of a function
  • The value is determined by the invocation pattern used
    • The method invocation
      • When a function is a member of an object
      • this is bound to that object
    • The function invocation
      • When a function is NOT a member of an object
      • this is bound to global object (see also this)
    • The construction invocation
      • When a function is invoked with the new prefix . . this is bound to that new object.
    • The apply invocation
      • apply simply let’s you control what this is.
  • Return
    • If the function was invoked with the new prefix and the return value is not an object, then this (the new object) is returned instead
  • Modules
    • A module is a function or object that presents an interface but hides its state and implementation
    • See also the “Immediately Invoked Function Expressions (IIFE)
    • Summarized best here
  • Cascading
    • Using a paradigm where some functions do not return values but instead change some kind of state and then return this, we can chain events and enable cascading:
      • Jquery applications use this a lot!
      • $('#bobsDiv').on('mouseup').styleChange('background-color', 'grey')

Arrays

  • Note typeof(anArray) returns “object” so often you will also want to use Array.isArray(arrayInstance) or <Array KeyWord>.isArray(<array variable>)[2]
  • .sort() sorts arrays of numbers improperly:
    • It might return [ 12, 15, 2, 5]
    • So you have to give it a comparison function:


   arrayOfNums.sort(function(a, b) {
       return a-b;
   });        


    • this works bc it needs to return negative num if a should come first, 0 if equal and positive if the two need to be reversed
  • What is the difference between foreach and map?
    • foreach manipulates each member a given list but does not return anything
    • map returns a new list with updated members


Based on my experience this covers a whole lot that will come up in a senior JavaScript interview.  Am I missing anything major?



Much thanks to all_things_code for his input and especially his vital correction!



[1] Note different syntax from Python
[2] G3E9 points out that the Array.isArray is not supported by all browsers so for your IE8 or below users (or FF 3 users, if they exist?) so please note this simple polyfill:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}



JavaScript: Quick thoughts on *this* in inner functions

For insight into function invocation and the global scope, please note following code:


    var scope_example = "global";
    var outerDude1 = function(){
        var that = this;
        var scope_example = "outer Function";
        var scope_example_as_well = "outer Function";
        var innerDude = function() {
            var scope_example = "inner Function";
            console.log("1: " + scope_example);
            console.log("1: " + this.scope_example);
            console.log("1: " + that.scope_example);
            console.log("1: " + scope_example_as_well);
        };
        innerDude();
    };
    outerDude1();


When run, this produces:
1: inner Function
1: global
1: global
1: outer Function

  1. Of course, the first console.log will see the local variable
  2. The second console.log is using this refers to the global scope.  Douglas Crockford calls this a mistake in the design of the language as it is more useful and intuitive to have this include variables just outside this inner function. I could not agree more.
  3. The third console.log also has access to this global variable because we gave that a pointer to the this in the outer scope.
  4. It’s important to remember that by not using this, we still have access to the variables in the function scope just outside of this inner function
But the previous example is not the typical way to use that.  We usually use it to access public properties of the outer function from within the inner function like this:

        
    var scope_example = "global";
    var outerDude2 = function(){
        var that = this;
        this.scope_example = "outer Function Public";  // Very different here
        var scope_example_as_well = "outer Function Private";
        var innerDude = function() {
            var scope_example = "inner Function";
            console.log("2: " + scope_example);
            console.log("2: " + this.scope_example);
            console.log("2: " + that.scope_example);
            console.log("2: " + scope_example_as_well);
        };
        innerDude();
    };
    outerDude2();


When run, this produces:
2: inner Function
2: outer Function Public
2: outer Function Public
2: outer Function Private

The major difference here is that (in line 4) we tie the scope_example variable to this.  In that context, this is the global this and updates the variable defined in the first line.  Therefore both 3rd and 4th console.log(s) are referring to this global variable with the now misleading value of “outer Function Public.”


Another great example is here: JS Fiddle

Thursday, August 4, 2016

CSS Basics: part 1

The Front End Engineering Interview Series

I have over a decade of web application development experience and most of that time has been focused on “front end” (or user interface) development.  I have been accumulating a list of questions to ask candidates so I thought I would share them with the world so that I can dream of a candidate responding with my own words.  See also The Butterfly Effect 

CSS Basics: part 1


What are the 4 positioning options and what do they mean:


static: The default.  All objects positioned in order they are listed within the parent.  Default is left to right for block items.  Often used with float.

relative: Similar to static except that you can move an item “relative” to where it would naturally lie in static.  You could add top: -2px and the object would be 2 pixels higher relative to where it would be in static

absolute: positioned relative to the first parent (meaning climb the DOM until you find a parent that) is relative or static positioned

fixed: Similar to absolute but positioned relative to the browser (view port, specifically).  Remember when Facebook had a lower tray that was “fixed” to the bottom of the browser?  That’s how they did that.

Technically you also have inherit and initial, but I have yet to see a developer use them and I would check for drugs if they did.



And do not read this one because if you are seen at work reading w3schools, you might get demoted on the spot.


What is specificity?

Short answer: 
How you determine which conflicting CSS rule applies to your DOM object.

Longer answer:
If this is our HTML: 


   <div class=”carousel weekly-ads” id=”fred-carousel”> </div>



 General element selector such as:

div {
color: red;
}


      will be overridden by a class selector such as:

.carousel {
color: chartreuse;
}


and a class selector will be over ridden by an id selector

#fred-carousel {
color: blue;
}


    and an id selector will be overridden by in-line styles (Big EWWWwwww)

<div style=”color: yellow”> </div>


Then within each of these tiers in the hierarchy, the more “specific” you are with the definition, the higher it is in the precedence scale. The following will override the single class selector above but will not override the id selector.

.carousel.weekly-ads {
color: blue;
}


Full answer:
And Chris Coyier always skillfully gets to the point: https://css-tricks.com/specifics-on-css-specificity/


What is the box model?

This has been answered quite well many times previously so I will just give my short-short version:
All block elements are effectively rectangles made up of:
  1. content surrounded by padding
  2. padding surrounded by border
  3. border surrounded by margin


And the size of each of these CSS values determines how much space the element takes up and therefore it effects how it interacts with its siblings and parents.  Kind of like puppies.

The bad (don’t read this): http://www.w3schools.com/css/css_boxmodel.asp

I also like how concise this one is: http://learnlayout.com/box-model.html

That’s it for part 1.  If you are interviewing for a developer’s position beyond entry level, you’d better know these three concepts backwards and forwards.  Stay tuned for more advanced CSS posts as well as HTML, JavaScript, and general software engineering questions that I will call “other” for now.