Saturday, June 4, 2016

Object.create and prototype confusions

This is a topic that I like to give anyone interviewing for a JS position at my company. It's a bit of a brain-twister, and unless you really understand how prototypal inheritance works in JS, there's a pretty good chance you'll get it wrong.

What's the difference between:

1. var objB = Object.create(objA);

and

2. var objB = new objA();

When we write #1, objB's internal [[proto]] property points to the object that is objA. That means that when we execute something like:

var objA = {
  a:42;
}
var objB = Object.create(objA); //objB.__proto__ === objA
console.log(objB.a); 

However, when we have the following scenario, invoking a function as a constructor:

function objA(){
  this.a = 42;
}
objA.prototype.b = 43;
var objB = new objA(); //objB.__proto__ === objA.prototype
console.log(objB.a); //42
console.log(objB.b); //43
console.log(objB.__proto__); //objA.prototype

So we see that when when use the new keyword with a function, the object that is created (objB) has it's internal [[proto]] pointing to the function's prototype property (objA.prototype).

Talking DOMball...

Hello all you baseball fans and JS wahoos, it's time for another season of baseball!!
It's also time for us to discuss the differences between two similar sounding words in Javascript, document, and window.

window is the global object in Javascript. It holds everything, like global variables, global functions, history, location, etc. Global functions, such as setTimeout and console, live on the window as well.  Even document lives on the window.

console.log(window.setTimeout === setTimeout); // true
console.log(window.document === document); //true

window can also be thought of as the default scope or this keybinding in browser-based JS (environments like nodejs do not have a window object).

var x = 5; //x in global/window scope
console.log(this.x === window.x); //true

console.log(this === window); //true

document is the DOM. The DOM is a tree of nodes (html tags, like h1, div, span, etc), and may be thought of as an object-oriented representation of the HTML that makes up the page. For an example of what this tree looks like, check out this site:

https://gojs.net/latest/samples/DOMTree.html

document is immensely useful because it allows us to query and manipulate the DOM using Javascript. For example, to grab all h1 elements in the DOM, we would write:

var headers = document.getElementsByTagName('h1');

Check back later, when we'll continue our exploration of window and document.

Friday, May 27, 2016

Interview Prep

It's that time again.

Couple of companies, won't say which until the end. One is an unknown in terms of difficulty, the other can be assumed to have the hardest difficulty of any technical interview. Over the next few weeks, I will document my preparation and practice problems here. I'm not 100% sure which topics should be reviewed/covered, but here's what I'm starting with:

-Sass
-CSS (selectors, specificity, basic transitions/animations, psuedoclasses/elements)
-Basic responsive web refresher
-DNS
-Browsers - Chrome (caching, perf, rendering, etc).
-DOM API
-Javascript
-HTTP
-REST APIs
-Node/Mongo/SQL/Express
-Angular (mostly 1.x, some 2)

-Algorithms (noooooooooooo)

-Review basic dev tools like git/gerrit/npm

Time to go next level!


Sunday, May 22, 2016

Solving a JS Coding Exercise : Building a Color Picker

This is an coding problem I was asked at an interview a year ago. I understood the concept during the interview, I knew what I had to do, but I didn't code it right in the 30 minutes and I failed the interview.

I did it in five minutes this time. See, practice does work!!


Part 1: Here's the deal. Build a color picker. There should be an input where a user can type in a hex color, like #aabbcc. Whatever color is written in the box should be displayed in a div on the screen. So if I type #aabbcc in the input field, I should see a div whose color is #aabbcc.

For this stage, go ahead and have the background color update whenever any change happens to the input box.




Part 2: Change this code to only update the color when the user clicks on a button.






Solution:

Pretty simple, we want an input that listens for either the 'input' event or a button that listens for the 'click' event. Our event handler should read the hex value from the input, and set the div's background color to that value.

HTML:

<input type="text" id="inputBox">
<button id="inputButton">
Pick Color
</button>
<div id="colorBox">
</div>


CSS:
#colorBox{
  margin-top:20px;
  height:100px;
  width:100px;
  border: 2px solid black;
  background-color:#fff;
}



JAVASCRIPT For Part 2 (for part 1, listen to 'input' event instead of 'click':

var oInput = document.getElementById("inputBox");
var oButton = document.getElementById("inputButton");
var oBox = document.getElementById("colorBox");
oButton.addEventListener('click', updateColor,false);

function updateColor(){
  var color = oInput.value;
  oBox.style.backgroundColor = color;
}

Saturday, May 21, 2016

Solving a JS Coding Exercise: Week 1

Hi Everyone,

I'm going to start a weekly series where I walk through an online Javascript coding exercise. These posts are to give you a feel for the kinds of questions that will be asked of you in Javascript interviews. I will be drawing these questions from sources I find online, from my own experience being interviewed, and from the questions I ask people when I interview them.

Try to solve the problem yourself before reading my solutions. Otherwise, you won't grow.

This problem comes courtesy of Chris Chen.

Time Limit(optional): You should be able to do this in under 30 minutes. I'd aim for 15mins or so.

Here's a link to the live coding exercise:
http://codepen.io/chris-chen-nbcuni/pen/mnfBG

If that doesn't work, here's the problem description:
HTML:
<!--
  Instructions:
  When the value changes in the text field, multiply the 2 values and display in span with ID total.
  If the total is greater than 0, make the text green. Everything else make it red.
-->

<input id="value1" type="text" value="" /> x <span id="value2">1234</span> = <span id="total" class="other">?</span>

CSS:
.positive { color: green; }
.other { color: red; }

Javascript:








SOLUTION:
We need to perform a mathematical operation whenever someone changes the contents of the input box. Your first thought immediately should have been to assign an event listener to that input box. How?
// #1: get a reference to the input box and other elements
var oInput = document.getElementById('value1');
var CONST = 1234;

var oOutput = document.getElementById('total');
// #2: and assign it an event listener for the 'input' event
oInput.addEventListener('input',onInputEvent,false);

The input event fires whenever the contents of an <input> or <textarea> element change.
https://developer.mozilla.org/en-US/docs/Web/Events/input
You could probably solve this by listening to other events, but input makes the most sense here.
Now, we need to multiply the value in the <input> element by 1234 whenever the input changes, and check to see if it's greater than zero. We also want to display the product of this multiplication as well.

// #3:  write out the function for the event listener
function onInputEvent(){
  var nResult = CONST * parseInt(oInput.value);
  oOutput.innerHTML = nResult;
  if(nResult){
    oOutput.classList.remove('other');
    oOutput.classList.add('positive');
  }else{
    oOutput.classList.remove('positive');
    oOutput.classList.add('other');
  }
}

That does the trick. I prefer to get the references to the DOM elements outside of the listener function, so that they aren't rerun every time the event handler fires.

Friday, May 20, 2016

Javascript's Type Coercion

Hi Everyone,

Today we are going to tackle an interesting, and somewhat controversial, topic in Javascript - Type Coercion.

Quick recap - Javascript DOES have types. You'd be surprised how often people get that simple fact wrong.

Javascript types are:
-Primitives-
number
string
boolean
undefined
null

-Complex-
Object
Symbol (ES6)

Type coercion is different from type conversion in that it is handled implicitly by the JS engine at runtime, as opposed to being handled explicitly by the author at writing time.

An example of type conversion would be:
1 + Number("12");

Here, we are explicitly converting the string "12" to a number by calling the function Number.

An implicit coercion would be:
1 + "12";
which returns the string "112". Somehow, our number 1 was coerced into a string!

So, coercion is basically what happens when you give the Javascript engine operands of different types, without explicitly converting one into the other.

Today, we are going to learn which rules Javascript applies when coercing values.

*A quick point before we begin. Every Javascript coercion will result in a scalar primitive value; either a number, string, or boolean. That's it! Never anything complex like an object or a function.

In section 9, the ES5 spec defines what are called abstract value operations. These are internal-only operations that are used in coercion. We will look at four of them here; ToString, ToNumber, ToBoolean, and ToPrimitive.

ToString:
Anytime a non-string value is coerced into a string, ToString is invoked internally.
For primitives, the result is pretty straightforward:
null -> "null"
undefined -> "undefined"
true -> "true"
42 -> "42"
Things are more interesting if you are trying to convert something like an object or a function.
Unless you choose to override an object's ToString method, it will use the default one of Object.prototype.toString(), which will return the internal [[Class]] property of that object. This is why you usually see something like "[object Object]" when you run something like console.log({});

See if you can predict the output of the following code:
true + " " + 42


Answer:
It's the string   "true 42"

So far so good? Let's move on to the next abstract operation.

ToNumber:
This comes into play whenever a non-number value is forced to behave like a number - for example, in a mathematical operation. For example, in 3 - '2';  The string '2' needs to behave like a number.
Some basics, when toNumber is called on each of the following:
true -> 1
false -> 0
undefined -> NaN
null -> 0
strings will be NaN if it can't be coerced into a meaningful number.
"7" -> 7
"seven" -> NaN

Objects and arrays will first be converted to their primitive value ( one of the types we just discussed) via toPrimitive. From there, the resulting value is coerced to a number via toNumber.

You might be wondering just how toPrimitive takes something like an object and turns it into a primitive. In the next update, we will discuss just how this works.

ToPrimitive:

Wednesday, April 13, 2016

Debugging Minified Code

In this blog post, I'm going to step through a task that I'm currently focusing on at work. Sadly, it involves stepping through heavily minified code (with no code-maps), so it's going to be a bit of a doozy.

My employer doesn't open-source its code, but it's all js served to a client browser anyway, so basically public.

The Background: Part of our code injects a js package into a webpage which fires off tracking beacons to an external server at certain intervals. For example, if we inject an advertisement, it will fire a beacon when the ad is loaded (AD_LOADED), when the ad starts playing (AD_STARTED), when the ad has played 25%, 50%, etc.

The Bug: For some weird reason, in our minified code the AD_START beacon is firing twice, when it should fire only once. This isn't occurring in unminified code, so it sounds like a minification issue.

The Build: As part of our build process, we use the Google Closure Library's most optimized minification option (ADVANCED_OPTIONS). Some background on the compiler can be found on Google's site: https://developers.google.com/closure/compiler/docs/api-tutorial3#better

The Process: I've started by opening up my non-minified code in IntelliJ, and stepping though it to get a feel for how/when we are firing beacons. Once I am able to understand this in the non-minified code, I can start mapping it over to the minified code, and begin debugging there.

I'm using Chrome Dev tools to step through the code, and the Charles web proxy to monitor when beacons are firing.

This process goes on for several hours until I eventually discover the error. Closure is renaming the following property:
delete oSWFAdParameters.media.tracking
to
delete a.media.zk

and in this case, 'zk' is undefined, meaning that the tracking data is not being deleted, and is still being passed through to the AS3.