Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Monday, May 2, 2016

JavaScript Fun: Method of Wrapping JQuery getJSON to Handle Errors to Avoid Duplicated Code

Here's a great way to wrap JQuery and other libs in your own wrapper so you don't have to repeat yourself, repeat yourself. It's pretty basic and simple for now.

JS Bin on

JavaScript Fun: how to merge two objects, no recursion yet...

I like using objects in javascript. This is a basic and easy way to merge two of them. Good example is if you take in options into something.

JS Bin on

Wednesday, January 20, 2016

C# to JavaScript: Namespacing

Namespacing is one of the most important things you can do when using js. While namespaces are built-in constructs in C#, they are not an official part of the js language. That doesn't mean that you can't or shouldn't use them, on the contrary. In this post, I'm going to show you how to create namespaces and how to add your code to the namespace to not only avoid polluting the global context, but also to avoid potential collisions with variables and functions from other js libraries.

If you are foggy on what exactly a namespace is - my definition is that it's a logical container used to provide identity and scope to related code. If a class "Languages" in C# is defined in a namespace "TDLL.Countries", the class would be accessible from code in other namespaces via TDLL.Countries.Languages or Languages if the code file is has the "using TDLL.Countries" statement outside the class definition. Now that a baseline has been established, let's take a look at some common namespaces in js.

JQuery is definitely one of those libraries that is ubiquitous. I'd say it's the most commonly used js library in the world, but then again I don't have the numbers but I bet you've used it in some capacity. The JQuery library has a namespace - 'jQuery'. Also, that namespace has an alias '$'.

Click each "Say Hello" button in the jsbin demo below to see that both jQuery and $ are the same.

jQuery Namespace on

JQuery has some interesting documentation on the jQuery global namespace and the $ alias here.

And this snippet from the jQuery source code on GitHub is exactly how the global namespaces are assigned:

define( [...], function( jQuery ) {
    return ( window.jQuery = window.$ = jQuery );

in this case "define" is a function from RequireJS which is out of scope for this post. There's a lot that goes into the "jQuery" arg that is passed to the define callback function. It is defined in the files that are omitted in the sample shown then passed into define during build time to eventually add the function to the window object (global). jQuery gives you an option to release '$' in case there is a namespace collision with other libraries - also a good practice if you are aliasing.

Another way to create a namespace is to create the namespace first, then add everything to the namespace.

window.TDLL = {};
TDLL.learnSomething = function(){ ... };

Also you could do it using object notation like this:

window.TDLL = {
    learnSomething : function(){ ... },

One of the challenges in defining a namespace in either of those ways is that if the namespace is already defined, you'd basically overwrite it in subsequently loaded files. To avoid that you can do the following:

window.TDLL = window.TDLL || {};
TDLL.everyDay = function(){ ... };

This neat trick evaluates the first operand of the OR (||) expression as false if it is undefined.

Another way to do this is to use jQuery to merge your new object with the existing one.

window.TDLL = $.extend(window.TDLL, {
    everyDay : function(){ ... },

jQuery Merge Demo on

Using your namespace is simple (once you know it has been loaded anyways).


There are ways to ensure that your namespace has been loaded (by packaging all of your javascript together), but those are beyond the topic of this post and will be a topic for a future post.

Tuesday, January 19, 2016

JavaScript Logical NOT Operator

There are some interesting things to note about the logical NOT operator in JavaScript. What I've found is that if you aren't aware of these, you may find yourself coding up some defects without knowing it. Also, being aware of some important usages may improve your code by reducing complexity.

If you are coming from a strongly typed language or just getting started in JavaScript from ground zero, you may interested to know that the NOT operator (!) has different behaviors depending on the value type that the variable represents at runtime.

For example you may have a statement:
var x = !y;
while x will be assigned a boolean value when this statement is executed, y could be any type (string, number, object, NaN, undefined, null, function) and how each is negated depends on the type.

Plus the process of negation involves first converting the value of the variable to boolean, then negating the result.

When converting to boolean, the following types are always false - null, undefined, NaN.

These are always true - object, function.

But string and number depend on the value - 0 is false and an empty string "" or '' is always false, while any other number or string is true.

An array is an object so it is always true even if it is empty.

{} is also true.

How much fun is that!?

Coming from C#, it would be great to write:


instead of


But when you cam expect x to be of any type, it would get much more complex.

In js, if you are in a position where you cannot use a guard, but need some logic to check for a value you can do the following:

//do something useful

The underlying definition according to ecma 262 v5.1 of the ! is defined as negation of ToBoolean(GelValue(x))

where ToBoolean is defined here

and GetValue, which is more complex, is

Even though the abstract ToBoolean does not cover off on function type or array type (both object types) I listed those above for more clarity.

Since there is no ToBoolean in the JavaScript language, and there is a Boolean function (not to be confused with the constructor [new Boolean]), you'd be better of writing Boolean(x) instead of !!x for sake of clarity AND efficiency. Why have the runtime perform GetValue and ToBoolean twice?

The ecma standard defines the Boolean(x) function as simply calling the abstract ToBoolean(value)

Tuesday, December 8, 2015

Javascript Constructor Pattern to Ensure new is Called

Here is a pattern that will ensure "new" is called when defining an object constructor. When calling a JavaScript constructor function, if "new" is not used, then the variable being assigned will be undefined unless the constructor function returns something else.

function Griffen(name){ = name;
  if(this instanceof Griffen){
  return new Griffen(name)

Friday, August 28, 2015

Battle of the Languages

One great thing about the challenges offered on is that they can be solved in so many languages - e.g. choose the language of your choice and go at it! As a side benefit, one can easily compare run-times and memory footprints of languages by solving a challenge in many languages and viewing the results. As an experiment I did just that with the following challenge.

Here is the description of the challenge, as it can be seen on the site:

And the basic solution, which I implemented using the same basic algo in five languages (JavaScript, Java, PHP, C#, and C).

The test data is supplied via a file passed to args during execution, the same file is used in every execution run. JavaScript is run on Node. Execution takes place server side on a Linux based server (more details on the CodeEval site).

Basic algo is: for each line, split line on comma, parse each val to an int, run computation, print results to standard output.

Drum roll please....

As expected, C has the smallest mem usage and the fastest run-time, and by far at that. But I didn't expect Java to be that bad. Granted this is a trivial example. It would be interesting to see if the gap closes when the C program needs more supporting code. Educated guess is yes but not by much. The Java code for is below, I wonder if I'm doing anything wrong here or if it really is that less efficient in all ways.

public class Main {
    public static void main (String[] args) throws IOException {
        File file = new File(args[0]);
        BufferedReader buffer = new BufferedReader(new FileReader(file));
        String line;
        while ((line = buffer.readLine()) != null) {
            line = line.trim();
            String[] vals = line.split(",");
            int x = Integer.parseInt(vals[0]);
            int n = Integer.parseInt(vals[1]);
    static void compute(int x, int n)
        int m = n;

I plan on doing this same test in Ruby, Python, and GO to do an even broader comparison, when I have some time. Results will follow if I do.