AddThis

Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, March 28, 2016

Syntax Highlighting

Blog Enhancements

I've been rocking Alex Gorbatchev's syntax highlighter for a while on this blog, and it I really liked it.  It was quick and easy to use and at the time but lately, and for the past few years, I've really been into darker themes.  The syntax highlighter didn't appeal to me anymore and I didn't particularly like the themes they had.  So I searched around and stumbled upon Prism.  I like the way Prism looks and I found the installation super simple.  Take a look below at a code sample:


  var bubbleSort = function(unsorted) {
    for (var i = 0; i < unsorted.length; i++) {
      var swapped = false;
      for (var j = i + 1; j < unsorted.length; j++) {
        if (unsorted[i] > unsorted[j]) {
          var tmp = unsorted[j];
          unsorted[j] = unsorted[i];
          unsorted[i] = tmp;

          swapped = true;
        }
      }
      if (!swapped) {
        return unsorted;
      }
    }
    return unsorted;
  };
If you too want syntax highlighting like this, this is how!


Instructions

  1. Include the theme stylesheet
    
          <head>
            <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.4.1/themes/prism-okaidia.min.css" rel="stylesheet" type="text/css"></link>
          </head>
        
  2. Include the prism javascript file and all the languages you want highlighted, say you wanted support for ruby
    
          <body>
            ...
            <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.4.1/prism.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.4.1/prism-ruby.min.js"></script>
          </body>
        
  3. Wrap your code that you want highlighted
     
      <pre><code class="language-ruby">
        puts 'hi' 
      </code></pre>
      
  4. Done! You should get something like the following:
     
        puts 'hi'
      



Extra

For more information, definitely check out their site http://prismjs.com/.
And once you find the theme you like and language you want highlighted, stop over here for a nice cdn that will serve up the javascript and css's that you need https://cdnjs.com/libraries/prism.

Monday, March 21, 2016

Arrow Functions

I love the new arrow function in EcmaScript 6.  I use it for everything, pretty much all the time :)

Quick Rundown


Basic Form


var add = (numberOne, numberTwo) => {
  return numberOne + numberTwo;
};
add(1, 2);
//returns 3

Here I'm creating a function named add that takes two parameters, numberOne and numberTwo.  This function will return the two numbers added together.  When the body of the function is a single expression, we can write this even more concisely.


var add = (numberOne, numberTwo) => numberOne + numberTwo;

At first glance, this looks just like a different syntax for creating a function.  But there's more to it than that.  Inside of the arrow function, there is no new 'this' pointer defined.

Let's look at an example (taken from MSDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions):

function Person() {
  var self = this; // Some choose `that` instead of `self`.
                   // Choose one and be consistent.
  self.age = 0;

  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    self.age++;
  }, 1000);
}

Notice the strange self variable we had to create in order to access age.  This is because the function growUp gets a brand new 'this' pointer that is quite different than the 'this' pointer inside of Person.  That means that when growUp is called, calling this.age will not work, because there is no 'age' variable inside of the growUp function.  The new fat arrow fixes this:


function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

Notice that 'this' can correctly find and use the age variable.  This is very nice and just feels much better overall.


Gotchas

1.  Returning an object literal needs to be wrapped in parens.


const gimmeFoo = () => {  foo: 1  };
//will not work!  calling gimmeFoo() returns undefined

instead do this:

const gimmeFoo = () => ({  foo: 1  }); 

2.  You also cannot override the 'this' inside of an arrow function.  That means that bind is useless here, so don't try it.  Same thing for call and apply.  You can still pass in arguments, but you cannot override 'this'.

3.  You also don't have access to the 'arguments' variable, but a good workaround is to use rest parameters (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), which we won't cover here.

var f = (...args) => args[0];

4.  Even if you don't have arguments, you still need the parens:

const gimmeHi = () => 'hi';

but you can also do this:

const gimmeHi = _ => 'hi';
That's pretty much it! Go forth and start using it :)

Thursday, October 30, 2014

JavaScript Generators

Intro

One of the things people are really excited about that is coming in EcmaScript6 (Harmony) are generators.  There is a lot of writing out there today on generators but for the most part, I found the writing to be too quick to skip over the fundamental question of what they are.  Basically I was looking for a tl;dr.  Cuz ain't nobody got time for that.






Definition

I actually really like Mozilla's definition.  Short and sweet:
"Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances."

Allow me to paraphrase:
tl;dr Generators are special functions that save their variable state between calls.






Example

Now that you got the basic idea, let's look at an example.

First notice that the function definition has an asterick *.

//will double the number passed in
function* doubler(i){
  var doubled = i;
  while(true){
    doubled *= 2;
    yield doubled;
  }
}


Next notice the yield keyword.  We'll come back to that.  Let's take a look at the usage.

var gen = doubler(1);


The interesting thing is that calling doubler doesn't actually invoke the function.  A special object called an iterator is returned.  So gen holds an iterator, so lets see how to use that:

var result = gen.next();


Calling the next method on the iterator actually runs the doubler function, but stops when it hits the keyword yield (told you we'd come back to it).  And whatever you pass to yield (in this case the variable doubled), the iterator returns that.  So line by line:

var doubled = i;
//remember from above that i is 1, var gen = doubler(1);

while(true) {
 //nothing says that the iterator has to terminate. 
 //it can go on forever like this one does

  doubled *= 2;
  //doubled was 1, now its 2, b/c well 1*2 is 2

  yield doubled;
  //the iterator will stop here for now and return 2
}


So there you go, result should be 2.  Conceptually, that's sufficient to say, but in practice, the iterator takes 'doubled' and wraps it inside of a result object.  The result object has two attributes:

1.  The 'value' attribute which holds the value of 'doubled'.
2.  An attribute called 'done' that tells us if the iterator is done, which of course it isn't b/c we have a forever loop there.

{value: 2, done: false}


So what happens if we call next() again?

result = gen.next();


If you said

{value: 4, done: false}


Then congrats!  This is just the surface of how we can use generators, but once you understand this, the rest is cake.




Further Reading

If you would like to dive deeper into generators, check out this guide.  It's pretty detailed and explains some of the many ways you can use generators.

I also recommend the Mozilla documentation:




Using It Today

Great, you love generators now and want to use them today.  Unfortunately, the spec isn't officially finalized yet and not all browsers support it today.  To see who supports it, check out this table here.

You could also use transpilers like Traceur to turn it into regular JavaScript.

Or you can do what I did, and that's to use node.  Let's say all your JavaScript code is in generators.js.  Then just install node and run:

node --harmony generators.js



Monday, June 2, 2014

JavaScript Hoisting

Today I'm going to spend a little bit of time on hoisting in JavaScript.  A very cool and useful feature if you know how it works, but painful and confusing if you don't.

So what is hoisting?  Hoisting is JavaScript's behavior of moving declarations to the top of your scope (typically either the top of the global scope or function if you are in one).

There are two main types of things that can get hoisted, variables and functions.  We will go through each one of these presenting example cases to help illustrate how they work.  And at the end we will put everything together with a short quiz that contain aspects of everything discussed here.


Variable Hoisting

Case 1: Using a variable that doesn't exist.

console.log(name);

If you run this script, you get

ReferenceError: name is not defined.

This makes sense.  The variable name wasn't defined anywhere and as such, our JS engine can't resolve it and blows up.

Case 2: Correctly defining a variable and using it.

var name = 'Jon';
console.log(name);

This declares and defines name, and then uses it.  This works as expected and you will see 'Jon' written out to the console.

Case 3: Defining name after usage.

console.log(name);
var name = 'Jon';

You would expect to see the same behavior as Case 1, a ReferenceError, but what you see instead is 'undefined' written out.  This is because of hoisting, in this case, variable hoisting.  The declaration of the name variable was hoisted to the top of this scope.  Notice I said declaration, not definition.  The definition stays right where it is.  This is why name is undefined when it gets printed out.  Let me rewrite what the JS engine actually executes after hoisting.

var name;  //gets the default value of undefined
console.log(name);
name = 'Jon';

As you can see, now the output makes sense.
What other things can get hoisted?  In the next section, I'll talk about function hoisting.


Function Hoisting

Just like variable declarations, function declarations can get hoisted too.  But fun bit here, since the declaration and definition are done together, everything gets hoisted.

Case 1:  Using a function that doesn't exist.

sayHi();

This gives us the same result as Case 1 above,

ReferenceError: sayHi is not defined.

This makes sense.  You can't use something that you haven't declared.

Case 2: Using a function correctly defined after we declare and define it.

function sayHi() {
  console.log('hi');
}
sayHi();

Output here is 'hi'.  We declare and define a function sayHi, and then invoke it.  Everything works and this code is easy to understand.

Case 3: Using a function before we declare and define it.

sayHi();
function sayHi() {
  console.log('hi');
}


The output here is the same as Case 2, we get 'hi' printed out.  This is because the entire sayHi function is hoisted to the top.  So when we invoke sayHi(), it already exists.  Let's take a look at the code after hoisting.

function sayHi() {
  console.log('hi');
}
sayHi();

Notice that it's exactly the same as Case 2.


Hoisting of a Variable Holding a Function

What about this case, if we have a variable that holds a function.  That function is typically anonymous (it doesn't have to be) and we often see it as such:

var sayHi = function() {
  console.log('hi');
}

How does this get hoisted?

Case 1: Using a function that doesn't exist.

sayHi();

This looks like Case 1 above and is.  It gives us the same result,

ReferenceError: sayHi is not defined.

Same reason as before, you can't call something that isn't declared.

Case 2: Using the function after we declare and define it.

var sayHi = function() {
  console.log('hi');
}
sayHi();

This works as expected and prints out 'hi' into the console.  We've properly defined an anonymous function, set it to a variable, and then later invoked it.

Case 3: Using the function before we declare and define it.

sayHi();
var sayHi = function() {
  console.log('hi');
}

Boom!  We get

TypeError: undefined is not a function. 

What happened here?  Why didn't hoisting save us?  It saved us for both variables and functions, why not this time?  It's very subtle, but if you apply the hoisting rules you have learned thus far, you can see why this failed.  Let's rewrite the code after hoisting is applied.

var sayHi;  //set to default value of undefined
sayHi();
sayHi = function() {
  console.log('hi');
}

Because sayHi is actually a variable here, the variable hoisting rule applies.  The JS engine declared the variable at the top of the scope, and left the definition where it was.  So at the time we try and invoke sayHi, it's actually set to undefined.  Obviously, undefined is not a function, which is what our exception complained about.

An important thing to remember here is that for variables, only the declaration gets hoisted, while as for a function, the whole thing gets hoisted.  So this has implications in that when a function gets hoisted, it's immediately accessable/invocable anywhere within that scope.  But if you have a variable containing a method, you can't actually invoke that method until the definition of that method.  Up until that point, the variable will hold the value 'undefined' which you have already seen.

Now let's put it all together.  Look at the code below and see if you can figure it out before I reveal the answer.


The Quiz

Taking everything you learned, what gets executed here?

var f = function() {
    console.log("Me original.");
}
function f() {
    console.log("Me duplicate.");
}
f();




























Answer just below....









Answer

If you said 'Me original', you are right!  Wow, pat yourself on the back.  If you got it wrong, don't worry, I did too.  Let's see what this thing actually produces after hoisting, and then we'll tackle it step by step.

After Hoisting

var f;  //gets value of undefined
function f() {
    console.log("Me duplicate.");
}
f = function() {
    console.log("Me original.");
}
f();

First thing that happens is that the declaration of f gets hoisted.  Then, the function f gets hoisted.  Even though this looks weird, so far we are ok.  Odd as it looks, this is valid JS.  We just have a single variable, f, that contains a function that prints out 'Me duplicate.'.  Next we redefine f to print out 'Me original.'.  Finally we have our invocation.  This calls f which has been reassigned to an anonymous function that prints out 'Me original.'

Hopefully all this helps clear up the mystery of hoisting in JavaScript.


A lot of these examples were taken from some stackoverflow questions:
http://stackoverflow.com/questions/23889317/explain-this-javascript-name-clash
http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname

Sunday, April 7, 2013

Callback versus Promises


I like Node.  I like the callback mechanism.  I find the approach to multithreading very interesting.  That being said, I should preface that I also like Java's Futures/FutureTasks.  I guess what I'm trying to say is that I like things where I don't have to think about forking and joining (I'm ok with Java7's ForkJoinExecutor because again, I don't have to do it myself).  Just do it for me and give me the result when you get it.  In the meantime I'm going to make myself a sandwich, or whatever else I'm going to do while you're out fetching me whatever it is I asked for.

As such, this post got my attention:
http://blog.jcoglan.com/2013/03/30/callbacks-are-imperative-promises-are-functional-nodes-biggest-missed-opportunity/

James Coglan's basic assertion is that Node's decision to go with the callback mechanism was a mistake.  Before I go much deeper, I'm going to summarize a bit just in case you tl;dr it.  Essentially callbacks is at it's core an imperative construct while Promises (essentially FutureTasks) are more functional.  Why do we like functional versus imperative again?  Well because imperative tells the computer HOW to do something while functional tells the computer WHAT to do.  Imperative programming mutates state of objects as those objects are passed from function to function.  This means our programming is very dependent on the order of method invocations as well as the exact state of the objects over a given time.  Functional programming deals with values.  Arguments are values, and results returned from functions are values.  Nothing is holding state.  This essentially lets you parallelize a lot more because you never have fear or two threads potentially mutating the same object concurrently.  For any given input, you will ALWAYS get the same result.  1+1 is always 2.  But varX + varY could be 2 if varX and varY are both holding 1 at the time of execution.  But let's say this method then mutates varX.  Uh-oh, now depending on when you call this imperative method, you could get 2 or 3.  Get it?  Kind of?  Good enough.

So why did Node go callback?  Well because it's easier to understand.  Promises are much more abstract.

Callback
makeSomeBlockingCallWithCallback(callback);
This is easy to understand, you make some blocking call and when it's done, the callback method is called.

Promise
var promise = function() {
  var p = new Promise();
  var results = makeSomeBlockingCall(); 
  p.resolve(results);
  return p;
}
promise.then(callback);
I tried to do this with as little code as I could, but even without error handling, its longer than the callback example.  But let me explain what's going on here.  You create a promise object, run some blocking code, then shove the results of that onto the promise and return it.
We can chain together functions by using the then, which allows us to call our callback.

So what's the advantage of doing this?  There's a lot of extra code and the end result is the same, isn't it?  Not quite.  The first thing is that you avoid the infamous callback hell.  If you wanted to chain using the standard callback way, you'd have something like

makeSomeBlockingCall(function() {
  anotherLongCall(function() {
    yetAnotherLongCall(function() {
      console.log('im in callback hell!')
    });
  });
});

This happens quite a lot in node, think database work.  You open a connection, if it was successful write, after done writing, say you update a file or something.

For the Promise approach, you just have promises that all chain.
promiseForSomeBlockingCall
  .then(promiseAnotherLongCall)
  .then(promiseYetAnotherLongCall)
  .then(function() {
    console.log('less callback helly');
  });

So there's a slight improvement there in readability.  But if the only reason you're using promises is to reduce your callback hellness, you're missing the point of all this.  Remember what I said before about imperative versus functional programming?  The promises approach does not mutate the arguments.  Each promise does something and after it's done, returns a value into the next call in the promise chain.  If anyone of them fails, then the chain is broken (this is desired, if you can't connect to the db, you shouldn't write to it).

This is not the case with callbacks.  The only way data can get into a callback is via argument.  That means that all behavior is done as a result of a side effect (a side effect is when you mutate the argument).  You are no longer dealing with objects as values, objects now hold state that mutate over time.  This reduces what we can do concurrently as we are now very dependent on the order of method invocations and are extremely sensitive to the state of the variables as they change over time.

So how does this effect you?  Well jQuery now has Promises (http://api.jquery.com/promise/) and Deferred objects (http://api.jquery.com/category/deferred-object/).  A deferred object is like a promise but has no resolve or reject method (resolve is used to store the results, reject is used to break the chain).

Callbacks are great and easy to understand but let me just say on your next javascript project, you should go ahead and give promises a shot and see what you think.