Wednesday, June 26, 2013

A Look Into How Parameters Are Passed In JavaScript

I recently came across a question on StackOverflow about how JavaScript handles parameters, if they are passed by value or by reference. There seemed to be a lot of confusion and misinformation about what is actually happening behind the scenes.

TLDR; All arguments are passed by value in JavaScript, however, when dealing with non-primitive datatypes like objects and arrays a variable is created that points to the location of the object memory that is then is passed into the function. This means that changes to the variable inside the function will affect the original object's values. Once the argument is reassigned (e.g. arg = {} ) the variable now has the location of the new object in it so the original variable is no longer changed when the value changes.

By Reference vs. By Value

Let's start be defining exactly what by passing a variable reference and by value actually means.

By Reference

If a parameter is being passed into a function by reference it means that only a reference to the variable is being passed into the function is passed as the argument. The variable in the function and the variable that is passed into the function are actually pointing to the same location in memory. Put simply, if the value is modified inside the function the original value is also changed.

By Value

If a value is being passed into a function by value it means that a copy of the variable is being passed into the function. The variable in the function and the variable that is passed into the function are two separate variables. Put simply, if the value is modified inside a function the original value will remain unchanged.

By The Book

According to MDN:
The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function.

Huh?

Let me try to describe this with pictures. First let's create a variable that is a simple object literal:

var obj = { foo : 'foo' };

When we do this the variable obj is really just a reference to a location in memory that holds the actual object:



If a function is invoked and obj is passed into the function as an argument that reference is copied and passed into the function. In other words, the reference is being passed by value:

doSomething( obj );

This is where things start to get interesting. The pointer to the object is passed into the function call by value. In other words, a copy of the pointer is created and passed into the function call. We now have two variables that point to the same object:




At this point if the argument is modified inside the function call the changes will be reflected on the original varialbe outside of the function call. However if the argument is reassigned inside the function the reference will no longer point to the original object and changes inside the function will no longer affect the variable outside the function call:


function doSomething( obj ){

   obj = { baz : 'baz' }; //reassigns the pointer

}

After reassignment our objects in memory look like this:





What about primitives?

At this point you might be asking yourself, what about primitive datatypes like strings and numbers? The truth is that the point is quite moot since primitives are immutable, which means they cannot be changed. When a primitive is changed a new variable is created and reassigned to the original. Since this reassignment happens every time a primitive is changed it doesn't matter, the primitive will never point to the original location in memory once its changed so you'll always end up with the same behavior as if it was being passed by value.

Friday, May 24, 2013

JavaScript Inheritance - HowTo Shoot Yourself In the Foot With Prototypes!


One thing that has long eluded me is a good understanding how JavaScript inheritance works when the parent constructor function has instance properties. The following code has a Widget parent class that has a messages properties. In this case we want each instance to be initialized with an empty messages array:



Before we set SubWidget's prototype to a new instance of our Prototype constructor on line 12 we get an object graph that looks like this:

After the code on line 12 is run the new keyword does its magic and ties everything together creating a new inheritance tree and a new scope.  Our object graph now looks something like this:

Do you see what the problem is yet? Lets create some instances of our subclass to highlight the issue:


Now our object graph looks like this:



Before I talk about the real problem here I'd like to step back and talk about the "type" property on the widget's constructor.  If it is not initialized by assignment each instance's "type" property actually points to the constructor's "type" property.  However, once it is initialized by assigning a value to like so: sub1.type = 'Fuzzy Bunny' it becomes a property of the instance, as shown in the new object graph:

Our bug should start to become clear now.  Let's look at the value of both sub1 and sub2's messages array:

JS Bin

Each object is sharing the same messages array! It would be tempting to fix this by adding another property to the SubWidget constructor like so:



However, what if we wanted to create other objects that extended Widget?  That new object would also need a messages array and pretty soon we have code that is a nightmare to maintain and extend.  Additionally, what if we wanted to add other properties to the Widget constcutor that were initialized when instances of its sub classes were constructed?  This isn't very reusable or flexible solution. 

In order to properly fix this all that needs to be done is  to add a single line of code to our SubWidget constructor that will invoke the Widget constructor with the same scope of our SubWidget constructor:



Now when we create new objects each instance has a new instance of the messages array:

JS Bin

Now our object graph is correct:





Monday, May 13, 2013

Warm and Fuzzies

Be honest, how many times have you looked at someone else's code and said something like, "Who wrote this? They msut be an idiot!" or something to that effect?  I do it all the time, and if my ears aren't deceiving me I hear others doing it all the time as well. Sometimes this kind of response is justified, like the time when I came across a piece of code that queried a table and used a for loop to filter the rows instead of using a WHERE clause. However, sometimes it's our own insecurities and shortsightedness that triggers this reaction and stops us from looking at things more objectively.

Today I found a piece of code that at first appeared to be completely backwards and I started going to the familiar place of negativity. I was ready to rip it out and reactor it till it was perfect, my perfect. Then I'd scour commit logs to find out who wrote such bad code. I'm not sure what happened but something inside me decided to take a step back and look at the code and do a little research first.  After a few minutes I actually learned that the was actually written quite cleverly. I still scoured the commit logs to find out who wrote it but then I took a different approach. I chose to open up my e-mail client and wrote the developer a short e-mail telling them that I really liked the way they wrote that piece of code and that I learned something from it, and you know what, it felt pretty darn good.

It's so easy in the software development industry to focus on the negative, we are surrounded by it most of the time. The users of the software we write rarely communicate with us unless it's to tell us that something went wrong or doesn't work the way they expect. Even our friends and family encourage this sort of reaction by coming to us with their virus-laden computers and never asking to see what cool stuff we've been working on. We also love to look at other people's code and find the slightest problems. Raise your hand if you've scoured someones blog post looking for poorly written code?  I have. It makes me feel like a smarter person when I can find flaws in other people's code, however it still doesn't make me feel any better about the code I've written. My point is, that it's super easy to focus on the negative to make us briefly feel better about ourselves. However, my experience today has taught me that it feels FAR better to focus on the positive aspects of others code and to take a few minutes to tell the other developer that you like what they've written as well. 

Friday, May 10, 2013

cf.Objective() Session: An Introduction to AMD With RequireJS


AMD modules have been the subject of a lot of talk lately, some people really like them, some people hate them. Regardless, there is a lot of AMD JavaScript code being written these days and it would behoove any JavaScript developer to have a working knowledge of AMD and RequireJS in their toolbelt. Personally, what I love about AMD modules is that I don't have to worry about loading my script files in the right order in my markup, I also love that each module's dependencies are clearly defined within its source code. Writing decoupled and reusable "micro" applications within a RequireJS application becomes super easy.

The barrier of entry to AMD and RequireJS can sometimes look a bit high when first exposed to the concepts, and indeed it may be if you are still putting all your code inside your $( document ).ready() function. However, if you've been using a MV* framework, or if you've been using Rebecca Murphey's Object Pattern to organize your code, getting started with AMD will be super easy in most cases.

This session will help you get acquainted with writing AMD modules, adding RequireJS to your project, and using the R.js optimizer to optimize your RequireJS source code. After it you should have a good understanding of how powerful modular JavaScript code can be and have a good working understanding of the moving parts of a RequireJS application so you can go home and start adding RequireJS to your next project.

The best part is, if you attend my session (which is scheduled in the last time slot of the conference) there's a chance we will get to site down one-on-one and talk about Require and AMD.

Thursday, May 9, 2013

cf.Objective() Session: The Art of JavaScript, Level Up Your Skills In 60 Minutes


JavaScript is a funny language, many really smart programmers never really take the time to learn it. They learn how to write jQuery code, but never learn the beauty of the language beneath it. I blame JavaScirpts trouble past for this, if you've ever had to debug JavaScript on IE6 you know what I mean.

This session is for developers who know JavaScript but dont really know JavaScript. If you are unsure about attending ask yourself these following questions, if you answer is "no" to any of them, you might want to attend this session:
  • What is the difference between var func = function(){} and function func(){}?
  • There is a subtle difference between lexical scoping and closures, what is it?
  • What [7] == 7 is and why?
  • What each log statement produces when  running the following code:

  • What undefined || 'foo' returns?
  • Why foo.constructor === Foo is false when running the following code:

If that's not enough to convince you to come to my session maybe this will: I'm giving away a copy of "Effective JavaScript" that is signed by David Herman himself!  



Fork me on GitHub