JavaScript Callback Functions – The Absolute Basics

Callbacks are a critical tool for properly handling asynchronous events in JavaScript.

Timing is one of the most difficult techniques to master in JavaScript. At first, many look to the setTimeout() method to address the asynchronous nature of JavaScript. But that is most often not the best approach. The concept of a callback function is one of the things that makes JavaScript such a special language.

In order to understand callbacks, it is important to be aware that functions are first class citizens in JavaScript. This means (among other things) that a function can be passed as a value to another function. The upside to this is the fact that if you call function A, and pass it function B as an argument, then inside of function A, you can execute function B. That’s really what it all boils down to: You call a function, and pass it another function, and inside of the first function, when an event that you need to complete has completed, then you “call back” to the function that was passed in.

While you can pass a named function as an argument, quite often you will see an anonymous function passed. Before we demonstrate a callback function, let’s demonstrate why they are so helpful in JavaScript.

Example # 1

PHP FIle:

Client-side JavaScript:

In example # 1, we have two chunks of code: A server-side page that sleeps for three seconds, and then returns a JavaScript file. That JavaScript file simply outputs a message to the console.

When the script loads, it outputs a message to the console (message # 1). We want that message to be output before the 2nd message. The problem is that the script loading process is asynchronous; it could take 200ms, it could take five minutes. I’ve forced the PHP page that returns the JavaScript to “sleep” for three seconds, to exaggerate the effect. But the bottom line is: we don’t know how long that script loading process will take, which means that we have to find a way to execute message # 2 only after the script has finished loading.

Here is a JSFiddle link for Example # 1: http://jsfiddle.net/CZeLv/

Example # 2

In Example # 2, we pass an anonymous function to the getScript() method. Inside of getScript(), we take advantage of the fact that any dynamically loaded script element has an “onload” event. We assign that event to the callback that was passed-in. This means that when the script has successfully loaded, we execute the callback. As a result, we have complete control over the timing of events, even though the entire process is asynchronous. What happens is that message # 1 first first, and them message # 2. This is what we want.

Here is a JSFiddle link for Example # 2: http://jsfiddle.net/dfCM2/

What if the script that we are loading has properties and methods that we need to act upon once the script is available? In example # 3, we demonstrate how using a callback allows us to call a method that does not exist before the script is loaded, but we are able to control the timing of when it is called, so that it works every time.

Example # 3

PHP File:

Client-side JavaScript:

In example # 3, after the PHP file “sleeps” for three seconds, it adds a new method to the window object. That method returns a secret word. We need access to that secret word in our page, but we need to make sure that we don’t try to call the method getSecretWord() until it is available. By passing a callback to the getScript() function, we yield control to getScript() and basically ask it to fire our callback for us. Inside of getScript(), the script’s onload event is assigned to the callback, which means we only attempt to execute getSecretWord() once we know for sure that it exists (because the script’s onload event fired).

The important thing to keep in mind here is that if the script we are loading takes 5 minutes to return, or never returns, it does not matter. Our callback will only fire when that script successfully loads. While it is loading, the user still has complete access to the browser. That is really important.

Here is a JSFiddle link for Example # 3: http://jsfiddle.net/fAn4g/

Summary

In this article, we covered the very basics of JavaScript callback functions. We learned that functions are first-class citizens in JavaScript, and can be passed around to and from functions. We looked at an example of why callbacks are so critical to the JavaScript language and how they are an excellent tool for working around the asynchronous nature of the language,

Helpful Links for JavaScript Callback Functions

http://recurial.com/programming/understanding-callback-functions-in-javascript/

http://www.impressivewebs.com/callback-functions-javascript/

http://javascript.about.com/od/byexample/a/usingfunctions-callbackfunction-example.htm

jQuery Plugin Authoring – The Absolute Basics – Part II

jQuery Logo

Once you have jQuery plugin basics down, it’s time to implement some best practices

In the previous post “jQuery Plugin Authoring – The Absolute Basics – Part I”, we to a detailed look at the architecture of a jQuery plugin. Now that you understand the building blocks, let’s discuss a few best practices. These techniques are considered standard for quality jQuery plugin authoring, and will dress you for success.

Protecting the Dollar Sign

Most jQuery consumers associate the dollar sign with jQuery. But that dollar sign is simply a shortcut to the jQuery object, which is a property of the window object. You could write all of your jQuery code without ever using the dollar sign, and simply “jQuery” instead. But most people prefer the dollar sign because it is of course quite a bit easier and faster to type.

But jQuery offers a “no conflict” mode that allows another library to take over the dollar sign. It is considered best practice to anticipate this scenario and pass the global jQuery object into the immediate function that wraps your plugin. This way, inside of the nice and safe sandbox of your plugin, you can use the dollar sign all you like, without the slightest concern for how it is being used in the global context.

Example # 1

In Example # 1, we pass the global jQuery object into the immediate function. The immediate function takes that jQuery object as “$”, so from there on we are free to use the dollar sign safely, even if jQuery is in no-conflict mode.

Chainability

Method chaining is a popular technique in JavaScript. Many web developers use this technique when they leverage jQuery without even knowing it. How many time have you seen something like this:

$(SOME PARENT).find(SOME CHILD).CSS(“prop”,”val”).click();

What signifies the chaining activity is the fact that we have only one reference to the jQuery collection returned by $(SOME PARENT). Since each method used returns the jQuery object, we can use that return value to invoke another jQuery method, and so on. This is called “Chaining” method calls together.

It is considered best practice to allow method chaining when authoring your own jQuery plugin. Doing so is quite simple; you just need to return the jQuery object from each method.

Example # 2

In Example # 2, we return “this” from our plugin function. It’s important to note where the return statement is. Because the return statement occurs as the last line of code in our plugin’s function, the jQuery collection object is returned to the next method that wants to “chain”, without the need to re-state a jQuery collection.

Example # 3

In Example # 3, we have an example of method chaining in jQuery. Note that $(‘a’) only occurs once. That call to jQuery returns a jQuery collection object, which is returned from our jQuery plugin. As a result, the .attr() method can “chain” onto that return value and function properly.

Example # 4

In Example # 4, we have an even more complex example of method chaining. First we invoke “myPlugin”, and the the jQuery methods: .attr(), .css() and .click()

Here is a fully working JSFiddle.net link that demonstrates the best practices we have covered in this article. Be sure to click a few of the links to demonstrate the method chaining from example # 4:

http://jsfiddle.net/fTA95/

Summary

In this article we discussed a few jQuery plugin authoring best practices. We covered how to safely use the dollar sign in your plugin code, even when jQuery is in no-conflict mode. We also covered how to implement method chaining.

Helpful Links for jQuery plugin authoring

http://docs.jquery.com/Plugins/Authoring
http://stackoverflow.com/questions/12632382/jquery-plugin-authoring-and-namespacing

jQuery Plugin Authoring – The Absolute Basics – Part I

jQuery Logo

You know a little jQuery, you have used a few jQuery plugins, and now you want to write your own jQuery plugin. Don’t worry, it’s no big deal. In fact it’s fun.

If you have been putting off authoring your first jQuery plugin, it’s time to wrap a bandana around your head, fire up “The Eye of the Tiger” by “Survivor” and figure out how to defeat Apollo Creed. Sorry, for the cheesy 80s reference, I couldn’t resist.

But seriously, it really is no big deal. The most important thing is to get a firm grip on the fundamentals. That part is serious. If you don’t understand what you are doing from a jQuery-architecture standpoint, then you will quickly find yourself in a quagmire of muck and filth, and you don’t want that.

In this article we will discuss the absolute basics of how to author a jQuery plugin:

  • Wrapping your plugin in a self-executing anonymous function
  • Extending the jQuery prototype,
  • Iterating over each element in the jQuery collection returned by your plugin.

This is the big stuff. Once you get your noggin around these concepts, the fun can begin.

A note about Self-executing anonymous functions

These are otherwise known as “immediate functions”. An immediate function is simply a function that is wrapped in parentheses, and followed by a pair of parentheses:

You can learn more about immediate functions in my blog post:Immediate Functions in JavaScript – The Basicsas well as my blog post:Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope

The main point here is to make sure you are comfortable with the concept of an immediate function in JavaScript. It’s important to do before reading further.

Where does my jQuery plugin code go?

Good question. The answer is: In its own file. By convention, you’ll want to create a JavaSript file named jquery.myPlugin.js. Then you’ll need to reference it just as you would any other JavaScript file:

Just make sure you reference jQuery before you reference your plugin.

For simplicity sake, we will reference our jQuery plugin via a set of SCRIPT tags, right in the page (that is perfectly valid, but definitely not practical).

Example # 1

In example # 1 we have the absolute bare-bones code needed for a jQuery plugin. Here are the important points to consider for example # 1:

Wrap your jQuery plugin in an immediate Function

This is considered a best-practice and for good reason. Taking this approach allows you to create as many variables as you need in your plugin, without polluting the global namespace. Don’t overlook this, it allows you complete freedom with regards to the number of variables you need to create, and sandboxes all of these variables very nicely.

Again, an immediate function is simply a function that is wrapped in parentheses, and followed by a pair of parentheses. It fires right away when the JavaScript is evaluated, you don’t need to (and cannot) call the function. It just fires right away and whatever code you implement in that function executes. It’s a great way to provide private variable scope to some code without a whole lotta fuss.

If you are still having a tough time with the concept of immediate functions, stop, do a google search for JavaScript Immediate Function, learn it, live it, ask it out on a date, marry it, and then come back here to keep on reading.

https://www.google.com/search?q=javascript+immediate+function

(I’m serious about this immediate function thingy)

Your jQuery plugin becomes a property of the jQuery prototype object

jQuery is a function. Actually, the code in jQuery follows the factory pattern and returns a function that in-turn returns different kinds of things, depending on what you pass into that function. Most of the time, it returns an HTML collection wrapped with jQuery (hence a jQuery collection object), but again, the actual return value depends on what you are passing in.

Every JavaScript object has a prototype property, this includes functions. jQuery exposes its prototype property as “fn”. So, you simply assign your plugin to be a property of that “fn” object. Once you have done that, jQuery now has a new method that is YOUR plugin.

Now you can do this:

Inside of your plugin, the JavaScript keyword “this” is already a jQuery object

Most people know that inside of a jQuery callback, “this” usually refers to the current native DOM element that is being iterated over. When you wrap “this” in jQuery, it becomes a jQuery object. So, we often refer to “this” as “$(this)”.

Inside of your plugin, there is no need to do that because the JavaScript keyword “this” is already a jQuery object. If you refer to “this” as “$(this)”, it’s not going to kill anyone, but it is not necessary and just uses more memory than is needed.

Your jQuery plugin returns a jQuery collection

What your jQuery plugin returns depends on the CSS selector that was passed-in. For example, if you do this: $(body).myPlugin(), your jquery plugin will return a jQuery collection that has exactly one element: the BODY tag of your document (unless of course you have more than one BODY element in your page, which would be a bit of a head-scratcher). So, if you have an unordered list that has for example three items, and you invoke your plugin like this: $(ul li).myPlugin(), then your plugin will return a jQuery collection that contains three elements.

Use this.each() to iterate over all of the elements that are returned by your jQuery plugin

jQuery’s .each() method is a lovely little tool that allows you to iterate over a jQuery collection and “do something” to each element. Keep in mind that a jQuery collection can always contain exactly one element, and when it does, then the .each() method will run once. But when a jQuery collection contains multiple elements, then the .each() method will run once for EACH element in that collection.

When you use the .each() method, you pass in an anonymous function, and inside that function you have access to the current element that is being iterated over. It is here that you will need to wrap “this” with jQuery if you want it to be a jQuery object: Use $(this) for the jQuery object that represents the current element, or simply “this” for the native DOM element implementation. This anonymous function takes as its first argument the index of the current element. This is surprisingly handy: what if you want to know if this the the first element in the collection? or the last? That index number will help you with that task.

Now you are ready to write some awesome jQuery plugin code

Thanks for hanging in there. The preceding details were important. I know you are anxious to write some code, but understanding the outer architecture of a jQuery plugin is critical. If you do not understand what was just covered, then you will quickly be awash in spaghetti code that is not working right and will be difficult to debug. I promise you.

Example # 2

In example # 2, we invoke our jQuery plugin. We wrap it in a $(document).ready() call so that it only fires once the document is ready.

Invoking our plugin is as simple as $(CSS SELECTOR).myPlugin().

This is because our plugin is a property of the jQuery prototype object, which makes it a completely valid jQuery method. Nice.

Example # 3

In example # 3, we see how our plugin can behave differently depending on what we pass into it. In each case, the jQuery collection object returned by our plugin will differ, depending again on what CSS selector we passed-in.

Example # 4

In example # 4, we have included some implementation code so that our jQuery plugin actually does something. I this case, for each element returned in the jQuery collection, we change the CSS so that the element’s color is green, the background color is yellow, and the font is “Comic Sans”. Not too pretty, but just enough so that when we run the code, we can see that our plugin is working perfectly. More importantly, if you vary the CSS selector that is passed-in, you will see that our plugin behaves differently in each case (i.e. the HTML elements that become green with yellow backgrounds and Comic Sans font will vary).

Full Working Code for this Article
http://jsfiddle.net/wdUtL/

Full Working Code for this ArticleWith Comments
http://jsfiddle.net/ewTez/

Summary

In this article we discussed the absolute basics of how to author a jQuery plugin. We covered how to wrap your plugin in a self-executing anonymous function, how to extend the jQuery prototype, and how to iterate over each element in the jQuery collection returned by your plugin.

This example provided in this article was very simple. The main purpose of the article was to provide the overview needed so that you understand how a jQuery plugin is constructed, how it works at the most basic level, and importantly how the value of the JavaScript keyword “this” will vary a bit, depending on where you are in the code.

With a firm understanding of how a jQuery plugin is constructed, we can move on to best practices and more intermediate jQuery plugin authoring techniques.

Helpful Links for jQuery plugin authoring basics

http://docs.jquery.com/Plugins/Authoring

http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/

http://blog.kevinchisholm.com/jquery/jquery-each-method/

 

What is the Difference Between Scope and Context in JavaScript?

JavaScript LogoIn JavaScript, scope and context are not the same thing, and you should understand the difference between them. Fortunately, the answer is short and simple.

When interviewing front-end developers, I usually try to include a question about Scope and Context in JavaScript. I always ask what the difference is. The answers I get often surprise me. It seems that even those with some experience have difficulty answering this question.

The answer is short and simple: Scope pertains to the visibility of variables, and context refers to the object within which a function is executed.

Scope

Scope has to do with the the visibility of variables. In JavaScript, scope is achieved through the use of functions. When you use the keyword “var” inside of a function, the variable that you are initializing is private, and cannot be seen outside of that function. But, if there are functions inside of this function, then those “inner” functions can “see” that variable; that variable is said to be “in-scope”. Functions can “see” variables that are declared inside of them, and any that are declared outside of them, but never those declared inside of functions that are nested in that function. This is scope in JavaScript.

Context

Context is related to objects. It refers to the object within which a function is executed. When you use the JavaScript keyword “this”, that word refers to the object that the function is executing in.

Scope refers to the visibility of variables, and scope refers to the context within which a function is executed.

For example, inside of a function, when you say: “this.accoutNumber”, you are referring to the property “accoutNumber”, that belongs to the object within which the function is executing. If the object “foo” has a method called “bar”, when the JavaScript keyword “this” is used inside of “bar”, it refers to “foo”. If the function “bar” were executed in the global scope, then “this” refers to the window object. It is important to keep in mind that by using the JavaScript call() or apply() methods, you can alter the context within which a function is executed, which in-turn changes the meaning of “this” inside of that function when it is executed.

Summary

In my opinion, it is critical to understand the difference between scope and context in JavaScript. As soon as you have to write or edit even intermediate-level JavaScript, these two topics become very important. If you don’t understand the difference between scope and context, your ability to comfortably and confidently write / edit JavaScript will never improve. This is an important topic. The good news is, it’s not that difficult to understand and once you get it, you’ve got it.

Helpful Links for understanding the difference between scope and context in JavaScript

Understanding Scope in JavaScript – Function Level Scope | Kevin Chisholm – Blog

Understanding Context in JavaScript – Object Literals | Kevin Chisholm – Blog

 

 

Making Your JavaScript Code Easier to Understand: Object Literals

When it comes to organizing your object literals, there are multiple approaches you can take

Object Literals are a very useful feature of JavaScript. They allow you to easily build structures of data or functionality (or both mixed together), without too much fuss and drama. The syntax is simple and they make it easy to name-space your code. But, when your object literals start to grow in size, they can become a bit difficult to manage. And, it can sometimes make your code harder to follow.

In the next few examples, I will cover a couple of  alternate ways to organize your JavaScript Object Literals. This can make your code easier to manage and understand.
Example # 1

In Example # 1, we have an object literal that has been assigned to the variable “mathFuncs”. This object has three members: “add”, “subtract” and “multiply”. Each is a function. This is not too bad, but what if each function was tens or even hundreds of lines of code? The entire “mathFuncs” object itself would grow to become thousands of lines long. This can become unwieldy. Also, if while making edits, one semicolon gets knocked out of place, the entire object is likely to become defective, which will pretty much kill the script.

Example # 2

In Example # 2, “mathFuncs” is initially one line of code: an empty object. We then extend the object by adding more properties. In this case, the three properties we add are “add”, “subtract” and “multiply”. Functionally, there is no difference between this approach and Example # 2. These anonymous functions will perform no differently. What is different is that the code is a little bit easier to follow. First you see that “mathFuncs” is an empty object, and then we add properties to it. These properties are all functions, so they should be referred to as “methods”. Also, if you have a bug in one of the anonymous functions, it is less likely to break the entire script, and could be easier to track down.

Since these functions are very small, there is yet another level of optimization that we can apply:

Example # 3

In Example # 3 we tightened up the first three functions because there is so little going on in them, so it’s no harm to make them all one line each. Again, it’s just easier for someone else to quickly read and understand. We added two new properties, both anonymous functions as well. Since these are bigger functions (let’s pretend they are each 50+ lines of code), we put them last so that they are a bit out of the way, and we only have to see all that implementation code if we care to.

This is all a matter of preference. From time to time, I think that not everyone realizes that there are options when it comes to object literals and how you choose to write them out. The approach taken in Example # 1 is fine, especially when the objects are small. But when you have many properties in your object, and those properties are anonymous functions that contain tens or hundreds of lines of code, it can make your logic hard for someone else to follow.

Summary

There are many ways to skin a cat, and as many ways to organize your JavaScript code. The purpose of this post was to offer a few suggestions that can make your object literals a little bit easier to read, especially for someone else who, in the future, might have to read, understand and then make changes to your code.

JavaScript Closures – The Absolute Basics: Getters and Setters

The next step in mastering JavaScript closures is being able to “get” or “set” a private variable

In Part I of this series: JavaScript Closures – The Absolute Basics, I discussed wrapping one function with another, which produces a closure. When that returned function is assigned to a variable, as long as that variable is alive, it (a function) has access to the context of the function that wraps it. This means that the outer (or “wrapping”) function can contain a private member, but the wrapped function has access to it. In that post, the example code consisted of a function that returned the private member.

Let’s take this one step further: we want to be able to “get” and “set” that private member in real time. Consider the following code:

Example # 1

Here is the JsFiddle link: http://jsfiddle.net/a6LBf/

In example # 1, we first create a global variable named “drink” that is set equal to “wine”. Why we did this will become apparent in a moment. next we have a variable named “foo”, which is set equal to an anonymous function. Here is where the “closure” stuff comes in: That anonymous function (i.e. “foo”) returns an object literal. That object literal contains two properties: “getDrink” and “seDrink”. Both are anonymous functions.

After the declaration of the anonymous function “foo”, we create a variable named “bar” that is equal to the return value of “foo” (i.e. we execute “foo”, and set the variable “bar” equal to that). Because “foo” returns an object literal, it is almost as if we simply did this:

But that does not completely represent what is going on here. Although “bar” is in-fact equal to an object literal that has two anonymous functions as members, that object literal was returned by a function (and that is a critical detail). Because that object literal was returned by a function, the two anonymous functions that are members of the object literal have access to the function that returned them. Because they will execute in the context of “foo”, they have access to the private scope of “foo”.

Ok, so what does this all mean?

Remember when we created a global variable named “drink”, and set it equal to “wine”. Well, in example # 1, when say: “console.log( drink )”, and the output is “wine”, that is because in the global context, “drink” equals “wine”. But there is another variable named “drink” in-play. That variable is in the private scope of “foo” and it is set equal to “beer”.

Hang in there, we are getting to the good stuff now

In example # 1, when we say: “console.log( bar.getDrink() )” and the output is “beer”, that is because “getDrink()” has access to the private scope of “foo”, and in the private scope of “foo”, “drink” is equal to “beer”. Next, when we say: “console.log( bar.setDrink(“juice”) )”, we are mutating (i.e. changing) the value of the variable “drink” that exists in the private context of “foo”. This is because:

  • “bar” was set equal to the value of whatever “foo” returned
  • “foo” returned an object literal
  • The object literal that “foo” returned contains a member: “setDrink()”
  • “setDrink()” has access to the variable “drink” which is in the private scope of “foo”
  • We change that private variable “drink” to “juice” using “bar.setDrink()”

If you run the jsfiddle link for example # 1, you will see this all in action (make sure you have your JavaScript console open). Once the code has run, type the following in your JavaScript console: “console.log( bar.getDrink() )” the return value will be “juice”.

Summary

There is no such thing as a wasted moment when it comes to understanding closures in JavaScript. This is a powerful feature of the language. In this post, we discussed getting and setting the value of a variable that exists in the private scope of a function that returned an object literal. Stay tuned for more to come on this topic which is at times seemingly complex, but more than worth the effort and an important tool in your JavaScript belt.

Understanding Context in JavaScript – Object Literals

JavaScript Logo - context

Why is the word “this” so important in JavaScript?

In the post: “Understanding Scope in JavaScript,” I covered the basics of how scope works when dealing with functions. Sometimes the words “scope” and “context” are used interchangeably, which only leads to confusion because they are not the same thing.

In JavaScript, “context” refers to an object. Within an object, the keyword “this” refers to that object (i.e. “self”), and provides an interface to the properties and methods that are members of that object. When a function is executed, the keyword “this” refers to the object that the function is executed in.

Here are a few scenarios:

“this” can easily give you a headache. But hang in there; we are getting to the good stuff now.

In a nutshell, in Object-literals, you don’t have local variables; you have properties of the object. So, where inside of the function foo() I might say “var drink = ‘beer’; “, for an object literal called “bar”, I would say “bar.dink = ‘beer’. “ The difference is that “beer” is a property of “bar”, whereas when a function is executing, a local variable is defined by the “var” keyword and cannot be seen by anyone or anything outside of the function.

Example # 1

Here is the jsFiddle.net link for Example # 1: http://jsfiddle.net/Q9RJv/

In Example # 1, we first create a global variable named “drink”, and set it equal to “wine”. We’ll come back to that in a minute.

Next, we create an Object Literal named “foo”, with a property “drink” that is equal to “beer”. There is also a method that simply returns “drink”. But why does it return “wine”, and not “beer”? This is because in the object “foo”, “drink” is a property of foo, not a variable. Inside of functions, when reference is made to a variable, the JavaScript engine searches the scope chain and returns the first match it finds. Although this function executes in the context of “foo”, “foo” does not have a variable named “drink”. It has a property named “drink”, but not a variable. So the JavaScript engine searches the next level of the scope chain. The next level of the scope chain is the global object, which contains a variable named “drink”, so the value of that variable (“wine”), is returned.

But wait a minute Kevin, how can we make reference to the property “drink” that is in the context of the object “foo”?

I’m glad you asked.

Example # 2

Here is the jsFiddle.net link for Example # 2: http://jsfiddle.net/HGM93/

In Example # 2, the only change we have made is that in the anonymous function that is assigned to “getDrink”, we return “this.drink” instead of “drink

This is an important detail. When a function executes in the context of an object , the keyword “this” refers to that object. You can access any of the properties of the object by using the “this” keyword, add new ones (e.g. this.color = “blue”), and change existing ones (e.g. this.drink = “juice).

Using Dot Notation to Create a JavaScript Object Literal

Example # 3

Here is the jsFiddle.net link for Example # 3: http://jsfiddle.net/ZA77k/

In Example # 3, we have the exact same functionality as Example # 2. From the JavaScript engine’s perspective, we have achieved the same goal, and the console output is exactly the same.

The difference is how we organized our code. In Example # 2, we created the properties “drink” and “getDrink” at the exact same time that we created the object literal “foo”. It is all one expression. In Example # 3, we create an empty object named “foo” first, and then use dot notation to add properties to the object one-by-one. I just wanted to point out that there is more than one way to go about all of this from a syntax perspective.

Object Literals Can Contain Other Object Literals, and those Objects Have Their Own Context

Example # 4

Here is the jsFiddle.net link for Example # 4: http://jsfiddle.net/8p38y/

In Example # 4, we have added a new property to “foo”, and that property is yet another object. At first it is empty (i.e. foo.under21 = {}), and then we add two properties to it. The first property is “drink”, which is set equal to “soda”. Don’t’ confuse this with the property “drink” that is set in the context of “foo” which is equal to “beer”. In the context of “foo.under21”, “drink” is equal to “soda”.

The second property of “foo.under21” has an anonymous function assigned to it. That anonymous function returns “this.drink”. In the context of “foo.under21”, “drink” is equal to “soda”, so calling that function returns “soda”.

The point of this example is that object literals can have properties that are themselves objects, those objects have their own context. When functions execute in the context of those objects “this” refers to the object, and so on. I am aware of no limit to this kind of object nesting.

The JavaScript .call() and .apply() Methods Allow You to Dynamically Change the Context In Which a Function is Executed

Example # 5

Here is the jsFiddle.net link for Example # 5: http://jsfiddle.net/A5ydt/

Ok, so here is the bonus question: In Example # 5, why does a call to “foo.under21.getDrink()” now return “wine” ?

This is because we changed the inner-workings of that function. Instead of simply returning “this.drink”, we use the JavaScript “.call()” method, which allows you to execute any function in the context of another object. When you do not specify the context in which that function is to be “called”, it executes in the context of the global object. In the global context, there is a variable named “drink” and it is equal to “wine”, so “wine” is returned.

Example # 6:

Here is the jsFiddle.net link for Example # 6: http://jsfiddle.net/cS4cv/

In Example # 6, “soda” is returned because when we used the JavaScript “.call()” method, we specified the context in which the function is to execute. In this case, the context we specify is “this”. “this” refers to the context of “foo.under21”, and “foo.under21” has a property named “drink”, so the value “soda” is returned.

Summary

The last two examples may seem like overkill, but I wanted to point out that just when you start to get a handle on the concept of context in JavaScript object literals, you must realize that there is a bit more to consider. JavaScript Object Literals can have properties that are also objects, and those objects have their own context. In each case, when a function executes within that context, inside of the function, the “this” keyword refers to the object that the function is a property of, because the function executes in the context of that object. By using the JavaScript “.call()” method (or “.apply()” method), you can programmatically change the context in which that function executes, which changes the meaning of the “this” accordingly.

How to Create a JavaScript Object Literal

Learn how to quickly and easily create your first Object Literal, and give it properties and methods

There seems to be a bit of mystery surrounding the subject of JavaScript Object Literals. It is actually a simple concept and it’s easy to get started. There is a great deal of depth to the subject, but creating your first JavaScript Object Literal does not need to be complicated.

The simplest way to create an object literal is to assign an empty object to a variable. For example: var foo = {}; That is it. In that one line, you have created an object literal.

Now, that object is empty. Objects have two kinds of “things”: properties and methods. A property can be any valid JavaScript type (i.e. string, number, boolean, function, array, etc.). A method is essentially a property of the object to which you have assigned an anonymous function. So the property is now equal to a function. It is still a property of the object, but because it “does” something, we now call it a “method”.

Example # 1

Here is the JSFiddle Link for Example # 1: http://jsfiddle.net/jzrDw/

In Example # 1, we create a new Object Literal by assigning an empty object to the variable “foo”. Next, we give foo a property named “drink” and assign a value of “beer” to it. In this case the value of “drink” is a string (“beer”), but it could easily have been a number (i.e. foo.drink = 5) or a boolean (foo.drink = true) or any valid JavaScript type.

Example # 2

In Example # 2, we have added a second property to foo. This property, “say” has an anonymous function assigned to it, so now we call it a “method”. That method: foo.say does not do too much; it just outputs “hello world!” to the console. But nonetheless, it is a method of foo.

Here is the JSFiddle Link for Example # 2: http://jsfiddle.net/PWHM5/

Here is an important note: In the first two examples, technically, we created an object literal by assigning an empty object to the variable “foo”, and then we added a property and a method using dot notation (i.e. foo.property = value). But true “Object Literal” syntax involves creating the object properties as you create the object.

Example # 3

In Example # 3, we use Object Literal Notation. In the end, we have the same result as the previous example, but we achieve it using true Object Literal Notation. The difference is that in the previous example, we created an empty object, and then added properties to it. In Example # 3, we created those properties as we created the object itself.

Here is the JSFiddle Link for Example # 3: http://jsfiddle.net/sGY7E/

Summary

There is plenty more to talk about here. For example, there is the subject of “context” in Object Literals. But this post is about getting started, and to show that creating a JavaScript Object Literal is no mystery. What you do with that object is up to you, but you can be sure that objects in JavaScript are important features of the language, as they allow you to write more powerful and expressive code.

A Video Tutorial About JavaScript Object Literals

Helpful Links for JavaScript Object Literals

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects

http://blog.kevinchisholm.com/javascript/difference-between-object-literal-and-instance-object/

http://www.dyn-web.com/tutorials/obj_lit.php

JavaScript Closures – The Absolute Basics

Demystifying this topic is one of the most important steps towards truly understanding the JavaScript language

It is a little difficult to get your head around JavaScript closures without a basic understanding of scope. I will not attempt to tackle that subject in any kind of detail here. But let’s at least consider this thought: JavaScript functions always (always) retain a reference to any variables that are in-scope when they are defined.

I know that sounds a little nerdy, but it is important to remember. if you are not quite sure what that means, take a little time to explore the concept of scope in JavaScript, then come back to revisit the topic of closures.

Assuming you are comfortable with the concept of scope, think about a function that is defined in the global scope. There is not much going on there because the global scope is the outer-most scope. But what about when a function is defined inside another function? That is where the power of closures starts to take place. When a function is defined within another function, it has access to any variables that are in-scope at the time of definition.

Example # 1

 

Here is the JsFiddle link: http://jsfiddle.net/Xt8HP/

In example # 1, we first creatre a global variable named “drink” and set it equal to “wine”. Next we have a function “foo”, that returns another function. When we say: ‘var bar = foo()’, we are assigning the value that foo returns to bar.

JavaScript functions always (always) retain a reference to any variables that are in-scope when they are defined.

Since foo returns a function, then bar is now a function. Because the function that has been assigned to bar is defined inside of foo, it has access to foo. This means that in our case, bar returns a private variable that lives inside of foo. That variable inside of foo named “drink”, has been set to “beer”. So, in the global context, “drink” equals “wine” and in the context of foo, “drink” equals “beer”.

The end result is that when we pass the variable “drink” to the console, it is “wine”, because in the global scope, “drink” is equal to “wine”. But when we pass “bar()” to the console, we get “beer”. That is because “bar()” is a function, it returns a variable named “drink” and because “Bar()” was defined inside of foo, it returns the first “drink” it finds, which is private to “foo()” and it is equal to “beer”.

At the most basic level, this is how closures work.

Summary

There is much more to talk about with regards to JavaScript closures. But for those of you scratching your heads, just trying to get the basics down, I hope this was helpful.

A video tutorial about JavaScript Closures

Helpful links for getting started with JavaScript Closures

http://www.zimbio.com/Computer+programming/articles/387/Javascript+Closures+basic+explanation

http://jpmcgarrity.com/blog/2011/03/basic-javascript-closure/

http://www.javascriptkit.com/javatutors/closures.shtml

Associative Arrays in JavaScript

You may be finding conflicting information about associative arrays in JavaScript. Well, the answer is quite simple…. and then things start to get a little odd

If you are frustrated because you have been getting different answers on this subject, I”ve got good news and bad news. The good news is, the answer is simple: associative arrays are not supported in JavaScript. Arrays in JavaScript are index-based. Plain and simple, end of conversation. The bad new is, it’s not quite the end of the conversation. The reason for this is because the following code actually works just fine:

 

[insert shrugged shoulders here]  “…ok Kevin, so what’s the problem ?”

The problem is: you do not have an array with five elements. You have an array with three elements, and two properties.

Huh?

…yup, this is the part where JavaScript array objects behave in an unexpected way. But hang in there, it’s actually kind of cool once you understand what is happening.

Arrays are Objects

Arrays in JavaScript are numerically indexed: each array element’s “key” is its numeric index. In a way, each element is anonymous. This is because when you use methods of the Array object such as array.shift() or array.unshift(), each element’s index changes. So, after using array.shift(), array element # 2 becomes array element # 1, and so on. (array.pop() and array.push() may change the length of the array, but they don’t change the existing array element’s index numbers because you are dealing with the end of the array.) All this is to say that in a JavaScript array, each element can only be identified by an index, which will always be a number, and you always have to assume that this number can change, which means that the whole “key/vavlue” idea is out the window (i.e. no associative arrays in JavaScript. Sorry.).

…OK smarty-pants, if you can’t have associative arrays in JavaScript, why does this work: arr[“drink”] = “beer” ?

Glad you asked. This is because in JavaScript, arrays inherit from Object(). Whether you use an array literal or instantiate the array constructor, you are creating an object, plain and simple. Consider the following:

Example # 1

In example # 1, we create an array in three different ways. The first line creates a new array with three elements, but they are all undefined. The second line creates a new array, but it is empty, with no elements (this is an array literal). The third line creates an array literal, but we provide values for the elements as we define the array. In all three cases, you are creating an instance of the Array() constructor, which inherits from Object(). So, these are ALL objects.

Example # 2:

 

In example # 2, we create an array literal, but it is empty. (var arr = []; works just fine, but it is an empty array.) When we check the length property and try to inspect the object with console.dir(arr), we can clearly see that it is empty. Then we add elements to the array, and add named properties (e.g. arr[“drink”] = “beer”). But when checking the array’s length property, and inspecting the object, we can see that the actual “array” part of the array still has only three elements (i.e. “music” and “drink” are NOT elements in the array), and that “music” and “drink” are properties of the array object.

Arrays are Objects with their own special “array-ish” properties

What is happening, is that the Array() constructor returns an instance object that has some special members that other objects such as Function() and Date() do not. So when your code says:  arr[“drink”] = “beer” you are simply adding a new property to your object, which happens to be an array, and that property has a name of “drink”, and you have assigned the value of “beer” to it. You could have easily assigned a number, an object, an anonymous function, or one of JavaScript’s other data types. This property “drink” has no connection to the elements in the array. It does not increase the value of the array’s “length” property, and it cannot be accessed via the array-ish methods such as pop() or shift().

Let’s see what happens when we take advantage of this object’s “array-ness.”

Example # 3:

OK, so things are gettin’ pretty weird, right? Yep, but it’s all cool stuff, and at the end of the day, it’s no big deal. It just illustrates they way objects work in JavaScript. Let’s run it down:

  • First, we use the JavaScrpt Array() object’s push() method to dynamically add an element to the array. It just so happens that this new element is an object literal, with two properties. Its index becomes 3.
  • Next, we use the same push() method to dynamically add another element to the array. This new element is an anonymous function. Its index becomes 4.
  • Next, we create a new property for our array called “testMe” This new property happens to be an anonymous function. It has NO index, because it is NOT an element in the array, just a new property that we have added.
  • Next, we use the console to check the array’s length property, which is now “5”, and we inspect it.
  •  Dont’ forget it is an array, but it is also sill an object; Array() inherits from Object(). When inspecting the object, we see that our two uses of push() did, in fact, add two new elements to the array; one is an object, the other is an anonymous function. We also have “testMe”, wich is a new property of arr.
Ok, so what happens if we attempt to access the two functions that we added? Oh, they will run just fine, but remember: one is an element in the array, the other is a property of the arr object. So we access them differently:

Example # 4:

The output for example # 4 would be:

In each case, we are simply executing a function. It’s just that in the first case, that function is an element in the “arr” array. So, we have to access it using its index, which happens to be “4”. This can get tricky fast, and care should be taken in doing this kind of thing, but just to illustrate a point: array elements in JavaScript can be of any data type. In the second case, we access the function by its name “testMe”, because it is a PROPERTY of the array, not an element. Much easier, and there are no issues, because “testMe” will always be “testMe”, so it’s easy to access.

Summary

This is all pretty overboard. I mean, don’t we usually want this: var arr = [“mon”,”tues”,”wed”] ? Well, yes. Most of the time we do. But the point of this post is two-fold:

  1. JavaScript does NOT support associative arrays. Period.
  2. Arrays are objects, so properties can be added any time. Those properties can be any data type.

In JavaScript, arrays are best used as arrays, i.e., numerically indexed lists. The great thing is that those elements in the array can be of any data type. Index # 0 can be a string, # 1 can be an object, # 2 can be an anonymous function, and # 3 can be another array. But once you start doing things like this: arr[“drink”] = “beer”, you are swimming in somewhat dangerous waters. Unless you really know what you are doing, you will get odd behavior because arr[“drink”] is NOT a numerically indexed “member” of the array (it is not an array “element”), and does NOT have the relation to arr[0] and arr[1] that you may think it does. As soon as you start doing things like: arr[“drink”] = “beer”, it is time to consider putting this key-value pair in an object literal. You don’t have to, but it’s a better way to manage your data, and the approach leverages JavaScript’s strengths, instead of wrestling with the somewhat odd nature of it’s underlying architecture.

P.S.: If you really wanna see some odd JavaScript array behavior, try this:

The strange output of this one is for another discussion : – )

A video tutorial about associative arrays in JavaScript

Helpful links for associative arrays in JavaScript