JavaScript Snippet – Get Function Comments

Last year I wrote about having heredoc like strings available in JavaScript. Today I figured i’d briefly bring the topic back, providing a solution for returning an array of all comments found in a function:

Why is this useful? As you may know, writing multiline strings in JavaScript isn’t always the prettiest especially when you have to use \n or \r\n. On the other hand, let’s imagine that we have some multiline strings stored inside of a function as comments:

As you can see in the above jPaq Proof, by using the getComments function on a function which contains comments you can pull the comments out as if they were HEREDOC strings. Have fun! 8-)

NOTE: It is important to remember that if you are minifying your code, these comments will most-likely be stripped out. In this case you will want to find a different solution such as using the string escape characters (\r\n or \n).

Watch Anime & Cartoons Online for Free

Recently I have had the desire to provide more multimedia on my site. Due to the server requirements and the time it would take to keep everything up-to-date I decided to take the easy way out and simply link to the media providers such as Apple and WatchCartoonOnline. If you check out my home page at you will notice I have three new content sections with one of them for displaying anime/cartoon content. How did I get it to work? The following is the JSBin version of the content:
WatchCartoonOnline Links

As is the case with all JSBin content, you will be able to look through all of the HTML, CSS and JS code yourself, but it is important to note that with just a few tweaks here and there you could modify this code to work on your own site. I’d like to note that besides using the RSS feed provided by WatchCartoonOnline I am also using two different services provided by Google:

  1. Google Feed API (…):
    Used to convert the feed into JSON-P.
  2. Google Image Search API (…):
    Used to search for a thumbnail to display next to each episode name. If you want to actually use this on your site it is suggested that you use the non-deprecated Custom Search API :-)

I’d also like to mention that the scripts added to handle the JSON-P calls are created by the function outlined here.

One way you could improve this code would be to avoid making a new JSON-P call for an image for a show that was already search for. There are most-likely other ways to improve this code as well, but I feel it’s a pretty good starting point for anyone that would like to provide similar links to WatchCartoonOnline content on their site. 8-)

JavaScript – Adding A Script Dynamically

First, I want to start off by saying that there are plenty of JS libraries that provide the ability to add scripts to the page such as jQuery. The purpose of this article is to present an alternative function whose sole purpose is to add scripts (JSON-P or otherwise) to a page.

The following is the code for an addScript function which can either add static scripts or server generated scripts such as those used for JSON-P:

 * Adds a script to the page which pulls its code from the specified URL.
 * @param {string} url
 *     URL of the script to add.
 * @param {Object=} opt_params
 *     Optional extra parameters to be added to the URL.  If one of the
 *     parameters is a function, that function will be used as the JSON-P
 *     callback function.
 * @returns {!Element}
 *     The script element that was added to the head.
function addScript(url, opt_params) {
  // The context can be changed from this frame's window to a different
  // frame's window by using the call or apply function.
  var context = this, document = context.document;

  // Construct the entire URL.
  var urlHasParams = url.indexOf('?') +  1;
  if (opt_params) {
    var keys = Object.keys(opt_params), i = keys.length;
    while (i--) {
      var key = keys[i], value = opt_params[key];
      if ( == '[object Function]') {
        var callback = value;

        // Add a function to the global namespace that will be used for the
        // JSON-P callback.
        value = '_';
        do {
          value += +new Date;
        } while (value in context);
        context[value] = function() {
          delete context[value];
          callback.apply(this, arguments);
      url += (urlHasParams++ ? '&' : '?')
        + encodeURIComponent(key) + '=' + encodeURIComponent(value);

  // Add the script to the HEAD.
  var script = document.createElement('script');
  script.src = url;
  script.type = 'text/JavaScript';
  return script;

Now if you wanted to use this function for a JSON-P call you could do something like the following:


This will only work assuming that you have myFunction defined in the global namespace. Now let’s say you want to make the same call but you want the callback to be an anonymous function. Here’s how you can do it:

addScript('', {
  callback: function() {
    // Do the stuff you want here

Of course the name of the callback parameter doesn’t have to be `callback`; it can be arbitrary. If you check out the code you will see that this works by actually temporarily adding a function to the global namespace. As soon as the temporary function is called it is removed from the global namespace.

As a final note it is important to mention is that if you will be passing opt_params to this function you will want to ensure that Object.keys is available in the environment in which your code will run (most browsers natively support this function). If this function isn’t assured to be defined in the environment, it would be a good idea to use code which emulates it. 8-)

Upcoming Movie Trailers Thanks to Apple & YouTube

A little bit ago in this article I talked about being able to convert XML to JSON(P). I finally got around to making a page which shows upcoming movie trailers and information. First, I have to admit that the data is coming from both Apple and YouTube. You can check my trailers page by clicking here. One cool thing you’ll notice is that your given all of the summary data you may want to know about the upcoming movies (these are the same ones found on It also provides a way to search and show any of the YouTube trailers without having to leave the page. The main link for each movie actually opens an IFRAME to the corresponding page on

Even though having the trailers page worked out nicely I still wanted to trailers displayable on the home page. If you visit the page now you will see that they are available, but the following JSBin shows how this code actually works:

Feel free to check out as well to see how i’m actually pulling the movie data in from Apple. 8-)

JavaScript Snippet – Fancy getKeys

Most of us know the simple way to get the keys from an object in JavaScript (~61 bytes after minified):

function getKeys(obj) {
    var k = [];
    for (var i in obj) {
    return k;

But how many of us knew that array assignment within the for-in loop would work? (~58 bytes after minified)

function getKeys(obj) {
    var i = 0, k = [];
    for (k[i++] in obj) {}
    return k;

To be honest I cant take the credit for this because I actually found it here. Even though knowing this may rarely help you shorten your code, this is still a pretty cool capability! 8-)


  • The above defined getKeys function is really just to prove that you can do for(anArray[counter++] in anObject)....
  • If you can be certain that Object.keys will be defined in the environment in which your code will run, you should use that native function instead.
  • Using this function as is will include prototypal properties defined for the class of the object passed.
  • This function will not return properties that override prototypal properties (such as toString) in some environments.


Today I was looking for a way to easily pull in RSS feed data from Apple Trailers onto my site via AJAX. At first I was thinking about using jQuery to do it but then I got thinking about how cool it would be to have a PHP script that transforms any XML file into JSON. Thus, the following PHP script was written:

$json = json_encode(simplexml_load_string(file_get_contents($_GET['url'])));
if(isset($_GET['jsonp'])) {
  $json = "{$_GET['jsonp']}($json);";
echo $json;

Pretty cool, right?! The above five lines can be used to make a proxy which can convert XML to JSON or even JSONP. Let’s say I had this script at With such a script in place one could simply pull the JSON version of the Apple Trailers RSS feed from The JSONP equivalent (using loadTrailers as the callback function) would be Believe it or not, it is really that easy!!! 8-)

JavaScript – Equality & Strict Equality of null & undefined

One thing I have been doing for quite a while is using equality to (==) undefined or null to check if something is equal to one of those two values. Unfortunately, if your JS code needs to pass a linter, this type of check is not acceptable. On the other hand, it is important to note that the following three equality checks all result in true:

Therefore, the main reason linters make sure you use strict equality (===) when checking for these values is because it is assumed that you only want to check for one or the other. Notice that if we do same test as above, but switch out normal equality for strict equality, the first comparison results in false:

In conclusion, if your goal is to see if a variable is null or undefined you can use standard equality (==) against one of these values. If you need to know if it is specifically equal to one of these values, you should use strict equality (===). You can find more information from Mozilla here.

Chrome – Array.prototype.slice(…) Difference

At first I thought this was an infinite loop bug issue. After that, I thought it was just simply a bug. Now, after a co-worker (Geoff) pointed me to the JavaScript specs, I see that Chrome implemented this correctly and others didn’t. In most browsers the following code would result in an empty array, but in Chrome (at least in v34.0.1847.116) you will get an array of length 4294967295:


Immediately you would think this is a bug but interestingly if you do the following you will get an array of length 1:


After looking at the specs you can see that the length is converted to a 32-bit integer:

Python – List Comprehension of Updated Dictionaries

First of all, i’m sure that the title is a bit confusing, but I couldn’t think of a good way to state in a few words the scope of a solution I was looking for today. Basically, I had a list of dictionaries and I wanted to create a new list of dictionaries with an additional key-value pair. For example, let’s say I have a list of dictionaries which define a and b:

my_list = [
    { 'a': 1, 'b': 2 },
    { 'a': 2, 'b': 3 },
    { 'a': 3, 'b': 4 }

What I wanted to do was create a new list containing copies of the dictionaries with a new key-value pair. After finding this stackoverflow answer I came up with a solution similar to the following:

import math
list1 = [
    {'a': 1, 'b': 2},
    {'a': 2, 'b': 3},
    {'a': 3, 'b': 4}
list2 = [dict(d.items() + [('c', math.hypot(*d.values()))]) for d in list1]
# [
#     {'a': 1, 'c': 2.23606797749979, 'b': 2},
#     {'a': 2, 'c': 3.605551275463989, 'b': 3},
#     {'a': 3, 'c': 5.0, 'b': 4}
# ]

Cool stuff, right? Do you know what is actually happening? d.items() actually turns each key-value pair into a tuple and returns them all as a list. Then we are concatenating our tuple to make a new list of three tuples. In this case doing math.hypot(*args) actually passes each item in the list as a separate argument (here is more information about using an apply-like function in Python). After that dict(...) takes that list of tuples and creates a dictionary from them. Finally, this is done for each dictionary in list1, add the new dictionary to a new list which is assigned to list2.

How cool is that?!?!?! Even though I still am a big fan of JavaScript, the fact that you can write this type of code in Python is pretty inspiring! 8-)

JavaScript Snippet – Simple Stack Trace In Chrome

Often times in JS it is necessary to trace through someone else’s code (or your own ;-) ) to determine the root of a problem. Many times I have found that knowing how a function was called in the first place can be very helpful. Since I use Chrome for development, as i’m sure many others do, I thought it appropriate to point out that you can show the stack trace whenever you want in the console by adding the following snippet to your code:

console.log('Stack trace:', (new Error).stack);

For those who need similar functionality in other browsers, I did a quick Google search and found stacktrace.js. Happy coding! 8-)

JavaScript, Math, and much more.