Tuesday, December 8, 2015

TIL: Destructuring in ECMAScript 6/Javascript

I think this is one of the coolest things that's being added to ES6/Javascript and something I've not seen (in this form anyway) in any other language I've played with: Destructuring. Basically, destructuring makes it possible to pop elements out of an array without looping nor using array prototypes. In fact, the fun thing about them is that you can use them on objects and to return multiple values from a function as individual variables.

I think the nicest part about destructuring though is that:

    * It removes the need for loops in lighter operations reducing the chance of 1-off errors.
    * It provides a means of accessing an array's data without modifying the array itself, nor having to clone the array for writes.
    * It keeps code from potentially vague (IE: non-self-descriptive) array traversal syntax such as "arr[3]" when utilizing array literals.

    // Example of array destructuring
    let players = ['kernelpanix', 'cashcab', 'bisnap'];

    let ['first','second','third'] = players;

    // Returns: first == 'kernelpanix'; second == 'cashcab';
    // third == 'bisnap'; && the players array remains unchanged.

And it's really that simple. Quite a bit more efficient seeming to me for certain applications. Here are the other two uses of destructuring in one go. As you'll remember, I said it could also be applied to object literals and enable multiple return values?

    function playerStats() {
        // TODO retrieve some data from a REST API with promises to return JSON as data

        let {name, age} = data;
        let player = {name, age};
        // and destructure back as a return value
        return {, player.age};
    // create the object
    let player = {};
    // populate the player object with literals
    let {, player.age} = playerStats();

While the above doesn't do much, it's a fun bit of syntactical sugar that can be valuable for code readability. The downside as seen above is that it can potentially create redundancies within code if applied to the wrong problem domain or multiple forms of destructuring are applied to the same object. (As all we did above was construct an object, then destructure it for the return values example, and reconstruct/restructure it.)

Monday, December 7, 2015

TIL: How Object Literals Changed In EMCAScript 6/Javascript

So, back in EMCAScript 5, we had to declare new objects in what's become known as JSON. However, in ECMAScript 6, we can simply add variables to a new object as part of a class method/function. The new way of doing things just enables a type of shorthand for the underlying data and greater standardization.

// ECMAScript 6 Object Literals
let appName = name;
let appVersion = version;

var newApp = {appName, appVersion};

This is functionally equivalent to seeing...

// ECMAScript 5 Object Literals
var newApp = {
    appName : name,
    appVersion : version

...including if you were to save the returned object to local storage with something like JSON.stringify(newApp);

Assume the above of course is part of a constructor method/function with name and version provided in the arguments it accepts. What we now have are all variables being declared at the top of the function/script and being consistently named, and reused without extra work throughout the code.

Quite the breath of fresh air from having to re-declare the variable name in the object, (if you chose to standardize your code base by having the variables declared at the top of functions/scripts;) having the variable declared within another variable, (the object in this instance;) or risk the name potentially being different from the variable it's being fed from and potentially causing errors.

Friday, December 4, 2015

TIL: Promises Are Basically Now Mystical Asynchronous Try-Catch

Old school thought: AJAX authentication? Single Page Application? Welcome to callback hell!

Prior to the "invention"/use of promises in libraries such as Angular, (deferreds in jQuery) the systems we've come to know and love on the front-end were hellish slogs through understanding HTTP responses and basically just tossing out replies other than "200/OK" and quite a few event listeners. Needless to say, the more listeners you place on a page, the slower your response times your app will have.

Basically with promises you're executing an asynchronous Try-Catch block. Here's an example (using Angular's implementation) of the two in terms of code.

// Try-Catch Block in JavaScript
try {
    // stuff to evaluate, generally with conditional throws in here to return when improper/unexpected values are returned as custom errors
} catch (err) {
    // if there's an error in what was evaluated above, it spits out default Javascript messages here how/if you tell it...
} finally {
    console.log('This bit runs regardless of success.');

Try-catches are somewhat built-in unit testing albeit, not as efficient as using testing frameworks/libraries such as Mocha, QUnit, Sinon, or expect.js, or Chai.

// Promises in AngularJS
    // try
    .then(function(data) {
        // this bit runs if your request was successful
    // catch
    .error(function(data, status) {
        // this bit runs if your request encounters an issue
        console.log(data + status);
    // finally
        console.log('This bit runs regardless of success.');

As you can see, the only real difference in what's going on here is that: In the try analogue, we're returning the data successfully retrieved from the server via our asynchronous request, rather than testing different conditions. Instead? We're testing that the end point exists. The error/catch and finally are pretty much direct analogues of one another.

finally {
    console.log('Also, a yay for promises being native in ECMAScript 6!');

IQ: What do you know about the Singleton Pattern?

Prior to being asked this question in an interview a few months back, I'd never really given any thought to design patterns in software. I had never really found the need and largely dismissed the concept as something only, "corporate types," embrace like any other buzzword or methodology.

But the thing that always sticks in my craw is when I'm asked about something I can't give an answer to, aside from saying I'm unaware or might have used it in some form without the formal name. I hate it so much that I generally make a note of it in the interview and make a point of looking it up later.

Largely, I've also dismissed them because I don't generally need them. I tend to attempt not repeating myself. In addition, I find that many of the patterns are language or domain specific, such as the question above and I'll explain why in a moment. Aside from all of that though, I've seen these patterns needlessly complicate what would otherwise be simple code such as creating an entire class to create a one-time-use object to do iteration in a for-loop... WTF? (Java aside, this is needless.)

In short BTW, a singleton pattern is where you create a class that can only generate one object of that type (aka class) at a time. Useful for say, working around Java's limitations on declaring globals and log-in/authentication systems.

Don't get me wrong, design patterns can be useful such as a builder or factory pattern. Heck, let's talk controllers, asynchronous vs. concurrent, and locks even. Yet coming back to the singleton pattern..? It has a very limited scope of domain. I used Java for a total of two projects in my professional life (aside from some educational background in it) and never encountered need of singleton in any of the log-in/auth schemes I've implemented. Or perhaps I've done these things unwittingly?

In any case, I feel like this was perhaps a poor question to ask in a situation where you're interviewing for something that will be primarily using Javascript and perhaps PHP in their role. But if I ever encounter this again, I at least have a clue what they're talking about.

Thursday, December 3, 2015

TIL: let vs. var Scoping in ECMAScript 6/Javascript

This is a short and simple one and relates to yesterday's hoisting TIL post. In ECMAScript 6 there's a new scoping type of variable declaration which applies specifically to the nearest closure rather than within the block like our beloved "var": The "let"

Here's the breakdown of the two existing declarations in terms of scope...

for (var iberry = 0; iberry < 10; iberry++) {
    // "iberry" is accessible here, but not outside the for loop

for (let tice = 0; tice < 10; tice++) {
    // "tice" above is only accessible in the parenthesis

This is pretty neat as sometimes wonky things (IE: bugs) could occur within loops like above due to unintentional collisions. And as Murphy's/Sod's states: If it can it will and at the worst possible time.

As seen above, it makes it so that any variable declared with "let" can't be hoisted as it can by utilizing "var". Yet, this might be better practice from the perspective of the principle of least exposure.

Personally, I really rather like let as it's another tool in the box that when understood and used responsibly, results in vastly more stable code, which in turn results in more reusable code.

let there.Knowledge(b);

IQ: What do you use as an IDE?

The first IDE I used was Notepad++ because it was really simple, had what I needed at the time: Syntax highlighting for all of my potential languages, auto-complete, and the ability to specify indentation styles.

From there I grew into Dreamweaver for many of the same reasons a bit before I joined Boomspot, except it allowed me to also control my file structure in a more visible fashion. (IE: There's a frame showing me what I've got rather than me mentally keeping track, having multiple monitors, or multiple windows.) Furthermore it provided a form of CVS functionality that kept everyone who was touching files from stepping on each other's toes and helped us roll-back if something didn't work.

And then we come to my penultimate IDE: Eclipse. But the question is, why Eclipse? Because it does everything I need it to do in every language I work in, including having plug-ins for controlling databases, macros, committing to Git, and currently integration with Node.js via Enide. Plus it's pretty much OS agnostic. If I need to use Windows? I have it, Mac? Got it. Linux? Triple check!

While Eclipse is definitely more hungry in terms of local resources than say, my original Notepad++, I get a massive number of tools out of it for the bother. If I really need to be fast and have all of that? I'd use CLI, but without something like Cygwin on Windows, it's definitely not OS agnostic.

So, in short, I use Eclipse because I've evolved to it and after I have it set-up on my machine? I'm a beast.

Wednesday, December 2, 2015

TIL: Hoisting In Javascript

Prior to today I wasn't aware that in Javascript, one could assign a variable without declaring it first, and then later declare it. While this isn't something I've ever used or seen used. And exploring W3School's page on it, they basically outright say it's bad practice to utilize. And their example is definitely bad practice...

var j = 0;
i = j;
var i;

The short of it as seen above, is that hoisting allows you to declare a variable after it's used and thus making the syntax of the code more confusing (mainly bad practice in style) as the above evaluates to...

var i;
var j = 0;
i = j; // thus i = 0

Though I'm not one who believes anything is bad practice to utilize, but rather that each thing is a tool and that tools get misused and/or misunderstood.

The practical use revealed by Stack Overflow answers is that it's used in OO design in Javascript. Basically you're able to situationally initialize a variable depending on whether or not it already exists.

var a = a || {}; = function() {};

This has two benefits including not needing to execute a line like...

if (typeof a != 'undefined') { var a = a; } else { var a = {}; }

... So what we see here is that we save checking if the variable is defined as we're defining it with itself if it exists and otherwise instantiating it as a new object or say, a default value.

This is definitely a potential game changer in terms of how I look at and create objects and my understanding Javascript OOP code.

PS: Hoisting isn't discussed in the ECMAScript white papers as a feature, but I have to believe it was definitely an intentional.