JavaScript Object Literal Shorthand Syntax Basics

JavaScript

JavaScript object literal shorthand syntaxJavaScript Object Literal Shorthand Syntax is a feature that provides a path to cleanerJavaScript. Not only does it provide a way to reduce the size of your code, but it will be easier to read and understand.

Many ECMAScript 2015 features provide improved ways to solve problems. Object literal shorthand syntax is a bit unique in that it’s not so much a shiny new tool, but an improved syntax. Now it might be tempting to dismiss this kind of feature as less-than-stellar, but it’s worth working into your routine for a number of reasons. For example, an improved syntax can lead to less code, and not only that, the code you write can be easier to understand. And believe me, those who inherit your code will thank you for this. So, in this article, I’ll explain how to use object literal shorthand syntax when defining properties and methods.

Typical Object Literal Syntax – Example # 1

See the Pen JavaScript Object Literal Shorthand Syntax – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

Let’s start with the way we’re used to working with object literals. In Example # 1 we have a getGoods() method that returns an object. The value argument is used on execution to set the value property, and the lowerValue() and raiseValue() methods lower and raise that value property. So this is all fine and everything works exactly as expected. In fact, if you look at the UI, the text that you see shows that our methods set and value property accordingly. Unlike many of the examples in this blog, there is nothing to “fix” here. Our code works fine and follows a typical syntax pattern because, as stated, I mainly wanted to establish that this is the way we normally work with object literals.

Object Literal Shorthand Syntax -Example # 2

See the Pen JavaScript Object Literal Shorthand Syntax – Solution by Kevin Chisholm (@kevinchisholm) on CodePen.

Now, in Example # 2 we do things quite differently. To start, look at Line # 3. When we set the value property, there is no colon; we simply assign the value of the “value” argument that was provided when the function was executed. This syntax is concise, thereby requiring you to write less code. Now it may seem like a very small savings here, but when you have an application with many thousands of lines of code, the savings quickly add up.

Okay, so next, look at where we define the lowerValue() and raiseValue() methods. Here, notice two things are missing: there is no colon, and we don’t need the function keyword. We simply provide the parentheses and the curly braces (as well as the code inside the curly braces). Here, too, the savings may seem small on a per-line basis, but in a large application, the difference will be dramatic. And the additional benefit, especially when defining methods, is that the code is a bit easier to read.

JavaScript Callback Functions – The Absolute Basics

Functions

JavaScript LogoCallbacks 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, you then “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 executes first, and then 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. So 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).

So the important thing to keep in mind here is that if the script we are loading takes five 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 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

jQuery LogoOnce 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

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

scope and contextIn JavaScript, scope and context are not the same thing, and it’s important to understand the difference between them. Fortunately, the answer is short and simple.

Why Should We Care About Scope and Context ?

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, and I am often surprised by the answers I get. 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 to which a function belongs.

Scope in JavaScript

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 to the function, 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, and that variable is said to be “in-scope”. Functions can “see” variables that are declared inside of them. They can also “see” 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 in JavaScript

Context is related to objects. It refers to the object to which a function belongs. When you use the JavaScript “this” keyword, it refers to the object to which function belongs.

Scope refers to the visibility of variables, and content refers to the object to which a function belongs.

For example, inside of a function, when you say: “this.accoutNumber”, you are referring to the property “accoutNumber”, that belongs to the object to which that function belongs. 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 (except in strict mode). 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. This, in-turn, changes the meaning of “this” inside of that function when it is executed.

Summary

As a front-end developer, you can surely appreciate what an important topic this is, and how critical it is to understand the difference between scope and context in JavaScript. These two subjects become very important as soon as you have to write or edit even intermediate-level JavaScript, and your ability to comfortably and confidently write / edit JavaScript will only improve once you have a good working knowledge of the difference between scope and context. The good news is, it’s not that difficult to understand and once you get it, you’ve got it.

What’s the Difference Between Scope and Context in JavaScript ? | Skillshare

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

JavaScript

JavaScript LogoWhen 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

JavaScript

JavaScript LogoThe 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”. Our reason for doing 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 we 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 does, at times, seem complex, but is more than worth the effort, and is an important tool in your JavaScript belt.

Understanding Context in JavaScript – Object Literals

JavaScript

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:

So, as you can see, “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”.

So the point of this example is that object literals can have properties that are themselves objects, and 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

JavaScript

JavaScript LogoLearn 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”. 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

JavaScript

JavaScript LogoDemystifying 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

var foo = function(){ var drink = “beer”; return function(){ return drink; }; }; var bar = foo(); console.log( drink ); //wine console.log( bar() ); //beer

 

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

In example # 1, we first create 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

JavaScript

JavaScript LogoYou 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. But the bad new is, it’s not quite the end of the conversation. The reason for this is that 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. So, 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/value” 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 the 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 : – )

Helpful links for associative arrays in JavaScript

The JavaScript for…in statement – enumerating object properties

JavaScript

The JavaScript “for in” statement allows you to literally “loop” through all the properties of an object, without knowing ahead of time what the object will be or how many properties it will have

Seems as though one of the most over-looked and under-used tools in the JavaScript language is the “for in” statement. This statement allows you to essentially say: “Hey, if I have an object, any object, I wanna know what the name and value of every one of it’s properties is.”

No problem dude.

The “for in” statement creates a loop, much like the typical “for ( i=0, i <+ ###, i++)”, but  you can think of it as more of: “for (x = the first property in an object, go until x == the last property in the object, go to the next property in the object”). Needing to know all the names and values of a given object at run time is a scenario that comes up more than you may think, and being able to satisfy that need is a huge (huge) asset.

Example # 1

So, in Example # 1, we created a JavaScript object literal and assigned it to the variable “car”. This object has four properties. We then use a JavaScript “for in” loop to literally loop through the properties of this object. note that in order to build our dynamic statement, we first reference “prop”, which is the variable that represents the name of the currently examined property (i.e. “maker”). In order to the actual value of prop, we use bracket syntax, as opposed to dot notation or dot syntax. This is because in order to use dot notation, we would have to actually know the name of the property (i.e. “car.maker”). Since we only have a variable to use, we can say “car[prop]”, because bracket notation allows us to use a variable, or any valid JavaScript expression inside the bracket.

The output of example # 1 would be:

The maker of this car is: honda
The color of this car is: blue
The type of this car is: sedan
The mpg of this car is: 32

Summary

So, as you can see, the JavaScript “for…in” statement is easy to use and incredibly useful. It helps to write code that deals with objects that are unknown at run time, but as a result, can be easily enumerated and acted upon.

Helpful links for the JavaScript “for in” statement

http://store.kevinchisholm.com/javascript-training/javascript-object-inspection-using-the-for-in-statement/

http://www.w3schools.com/js/js_loop_for_in.asp

http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/

http://webreflection.blogspot.com/2009/10/javascript-for-in-madness.html

JavaScript Interview Questions: Object-Oriented JavaScript

Object-Oriented JavaScript

QUESTION:

True or False: the terms “scope” and “context” refer to the same thing in JavaScript.

Click for Answer

QUESTION:

If you omit the “var” keyword when creating a variable in a function, it becomes a property of what object?

Click for Answer

QUESTION:

How do you determine if a JavaScript instance object was created from a specific constructor or not?

Click for Answer

QUESTION:

True or False: Once you create an object, you can add, remove or change properties of that object at any time.

Click for Answer

QUESTION:

True or False: You can only instantiate a JavaScript constructor function once.

Click for Answer

QUESTION:

When you create a function inside of a method, what does the “this” keyword refer to when used in that function?

Click for Answer

QUESTION:

Name two ways two change the context of a JavaScript method

Click for Answer

QUESTION:

Can a JavaScript constructor return a primitive value (e.g. a number or a string)?

Click for Answer

QUESTION:

In JavaScript, are objects passed by reference or by value?

Click for Answer

QUESTION:

What is the difference between a constructor function and a non-constructor function with respect to the word “this”

Click for Answer

QUESTION:

What is the name of the property that allows you to add properties and methods to an object, as well as every object that inherits from it?

Click for Answer

QUESTION:

True or False: An object literal can be used to create private variables.

Click for Answer

QUESTION:

What is the name of the object that refers to the application used to view a web page?

Click for Answer

QUESTION:

True or False: The object returned by the document.getElementsByTagName() method is an array.

Click for Answer


QUESTION:

Which object.property combination provides a reference to the protocol used to view the current web page?

Click for Answer

QUESTION:

Given the below code, what line of JavaScript would allow foo.getColor to return the value of foo.color, without using the word “foo”?

Click for Answer (+)

QUESTION:

What is the difference between using dot notation and bracket notation when accessing an object’s property?

Click for Answer (+)

QUESTION:

What is important to remember about the last property’s value in a JavaScript object literal?

Click for Answer

QUESTION:

Given the following code, what is very likely the reason that the programmer made the first letter of “Foo” a capital letter?

Click for Answer

QUESTION:

Given the following code, how would you instantiate the function “Foo” and assign it to the variable “bar”?

Click for Answer

QUESTION:

What are two ways in which the variable “foo” can be assigned to an empty object?

Click for Answer

QUESTION:

True or False: When you create an object literal, you must first instantiate the Object() constructor.

Click for Answer

QUESTION:

When using the addEventListener() method to create a click-handler for a DOM element, what is the value of “this” inside of the callback you specify?.

Click for Answer

QUESTION:

True or False: A JavaScript array is not an object

Click for Answer

QUESTION:

If a string is a primitive value, why does it have a split() method?

Click for Answer

QUESTION:

True or False: A function can have its own properties and methods.

Click for Answer

What is the difference between an Object Literal and an Instance Object in JavaScript ?

JavaScript

JavaScript LogoAlthough a JavaScript object literal and a JavaScript instance object are both objects, they differ in their inherent nature and features


Object Literals

An object literal is “flat”. You create it, you add properties and methods to it, and all of those properties and methods are public. You can mutate any members of that object at any time. A JavaScript object literal does not, by nature, provide private scope. But any of the members of an object literal can certainly be a function that is capable of private scope. Object literals are useful because they allow you to create clean name-spaced code that is easy to pass around and consume.

Example # 1

In example # 1, we have defined a JavaScript object literal and assigned it to the variable “data”. This object has two members: the property “fname” and the method “addOne”. At run time, we can mutate this object very easily and add new properties (e.g. “lname”) and methods (i.e. “say”). The upside is that this object is totally exposed and we can access or mutate any of its members any time we like, with no problem. (Remember that if an object member is a function, then that function does provide its own private scope.) The downside of this object is that it does not inherently have a private scope. It also doesn’t have the kind of initialization that is provided by a constructor upon creation.

The output for example # 1 is:

foo
5
bar
baz
this is the say function

Instance Objects

An instance object is what is returned when instantiating a JavaScript constructor function, using the JavaScript “new” keyword. When you say “var bar = new Foo()”, “bar” becomes an “instance” of the function “Foo()”. Any expressions within Foo() are executed, any local variables in Foo() are copied and provided in “bar”, and the value of “this” inside of “bar”, refers to “bar”. The function “Foo” is never changed in any way; it simply acts as a “blueprint” for “bar”, and “bar” is an “instance” of “Foo”. Any local variables inside of “bar” are completely private and can only be muted by privileged members of that object.

Example # 2

In example # 2, we have created a constructor function. A JavaScript constructor function is a function that is not meant to be executed directly. For example, we never plan to do the following: “Foo()”. Instead, a constructor is meant to be instantiated. This means that you create an “instance” of that function using the JavaScript “new” keyword. We have created an instance of Foo() by saying “var bar = new Foo()”. So, now we have a variable named “bar” that is an exact copy of Foo().

What makes “bar” differ from our JavaScript Object Literal that we defined in Example # 1, is that when our instance object (“bar”) is created, any execution code in the constructor (i.e. “Foo()” ) runs. In addition, any private variables defined in the constructor remain private in the instance object (i.e. “_color”).

What makes this scenario a little more special than that of the object literal is that we can have privileged methods. These are methods that are made public by the use of the “this” prefix, but they have access to the instance object’s private members (i.e. “_color”). So, when we run this code, the constructor function code runs (“welcome to your new instance object”). We attempt to output the value of “_color”, but “undefined” is returned, because “_color” is private and cannot be accessed outside of “bar”. We then use the privileged method “getColor()” to get the value of _color the correct way, and “blue” is returned. We then change the value of “_color” using the privileged memer “setColor()”, and return its value using “getColor()” again (“red”).

Summary

Both Object Literals and Instance Objects have their place and purpose in JavaScript. The power of Object Literals is in their lightweight syntax, ease of use, and the facility with which they allow you to create name-spaced code. Instance Objects are powerful because they are derived from a function, they provide private scope when they are created, and expressions can be executed on instantiation.

Helpful links for JavaScript Objects

http://www.w3schools.com/js/js_objects.asp

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

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

http://www.davidpirek.com/blog.aspx?n=JavaScript-Class-Constructor-vs.-Object-Literal:-Difference-in-Implementation-and-Inheritance

Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope

JavaScript

JavaScript LogoKeeping the global namespace clean is a good idea. Immediate functions allow the JavaScript programmer to do so with a great deal of power.

In a previous post, we discussed the topic of the JavaScript Immediate Function. Now let’s re-visit this topic with a focus on creating a private scope with which we can interact.

Most JavaScript programmers know that you can create an object, and then extend that object by simply assigning a new property to it. In fact, you can even do so at run time. Well, this is all very nice, but as you do so, these new properties are public. Which means, of course, that they are accessible to anyone and mutable at any time. So, while this can have it’s uses, there is a downside, because any line of code has access to these properties and can change them. Sometimes, that can get messy.

Example # 1

In Example # 1, we created a global variable named “foo”. We then added two properties to it: “name” and “say”. There is no reason why at a later point in our code, we couldn’t intentionally (or even worse, accidentally) do the following:  foo.name = “marge”. If this is intentional, no problem, but if it is done by accident, it creates cases that become frustrating to debug and manage. So, obviously, what we need is a way to store values inside of foo that have a clearly defined interface for retrieval and mutation.

Example # 2

{ var _name = “bart”; var MyConstructor = function(){ this.getName = function(){ return _name; }; this.setName = function(newName){ _name = newName; }; } return new MyConstructor(); })(); console.log( foo.getName() ); console.log( foo.setName( “simpson” ) ); console.log( foo.getName() );

In Example # 2, we have drastically altered our global variable so that it is an immediate function. Inside of that immediate function, we have a private variable called “_name”. We return an instance of our constructor function, which allows us to use the “this” keyword to create privileged members. These two functions allow us to set, and get the value of name. If you paste Example # 2 in your JavaScript console, and run it, you will see that the value of our private variable “_name” changes over the course of the two “get” statements. This is because in between these two get statements, we use the “setName” method to change the value of that private variable.

Summary

The JavaScript immediate function can be used to create a global variable that has its own private scope. This is useful when creating functionality that requires storing data for the life of the page and managing access to that data.

Helpful links for Immediate Functions in JavaScript

http://dreaminginjavascript.wordpress.com/2008/07/03/immediate-execution/

http://lostechies.com/derickbailey/2011/12/04/achieving-block-scope-with-immediate-functions-in-javascript/

http://www.jameswiseman.com/blog/2011/02/17/jslint-messages-wrap-an-immediate-function-invocation-in-parentheses/

http://www.jspatterns.com/self-executing-functions/

 

 

The JavaScript “for…in” Statement – Don’t Leave Home Without It

JavaScript

JavaScript LogoObjects in JavaScript are first class types that have become a critical component to modern front-end web development. The “for…in” statement allows you to fully examine any object at run-time<

Making objects, instantiating objects, and enjoying all the wonderful properties and methods that we baked into our objects is what advanced JavaScript is all about these days. Let’s face it… it’s hard to imagine a useful JavaScript-based application that does not, in some way, implement object oriented technology. The “for…in” statement is one of the most essential tools in our belt when it comes to introspection in JavaScript.

“Introspection” in JavaScript is the act of “looking into” an object, to discover what it has inside. The answer is: “properties and methods.” But, the thing is, you don’t always know the name of the object that you will want to “look into” or exactly when you will have to do it. Also, as we know, an object member can itself be an object, which has properties and methods, and one or more of those properties might be another object with its own properties and methods… or a method might return an object, that has properties and methods…. and so on.

So, add this all up and what you get is the need to “look into” an object without knowing anything about it. It may be an object that you did not create, so our introspection tool cannot look for a specific set of named members; it just has to be able to say:  “the object that you told me to look into contains the following properties and methods,” and based on the object that we fed to that tool, the answer can vary.

The JavaScript “for…in” loop is incredibly simple and equally powerful. With its basic syntax, we can easily say: “for each X in Y… do this…”. X is the object’s property and Y is the object. So, if I had an object named “foo”, I could say “for X in foo”. If foo had 5 properties, then the loop would run 5 times. In each iteration of the loop, “X” will represent the current property that is being “looked at”. To access the property name, simply refer to X (i.e. alert(x) ), and to access the property value, refer to object[x] (i.e. alert(foo[x]) ). The reason that we use the bracket notation, and not dot notation, is that dot notation requires a string literal (i.e. foo.name), whereas with bracket notation, we can place any valid expression inside the brackets, such as a variable (e.g. foo[X] ).

Now what follows this is the “loop”, which is a set of curly brackets. So, our syntax looks as follows:

Inside “the loop”, we can do whatever we like. Typical scenarios are to do something with either the property name (i.e. X) or the property value (i.e, foo[X]). Let’s look at an example of a JavaScript “for in” loop that does something.

Example # 1

The output for Example # 1 would be:

the value of color, is: blue
the value of name, is: fred
the value of say, is: function (){ return “this is the say function” }

In Example # 1, the object “foo” has three members: two properties and one method. So, the “loop” executes three times. In each case, we output the name of the member “prop” and the value of the member “foo[prop]”.

Hmmm… ok, but what if one of the members is a function? Can’t we do more than just output what the name of the function is?

Sure! Functions are meant to be executed, so let’s execute a function if we find one!

Example # 2

In Example # 2, we examine each property courtesy of the “typeof” operator. If the property currently being “looked at” is a function, we assign the value of the property (the actual function code) to a variable, and then execute that variable. The output of Exmple # 2 is:

the value of color, is: blue
the value of name, is: fred
we found a function, and here it comes: hello from is the say function

Summary

So, as you can see, the sky is pretty much the limit with regard to the JavaScript for…in statement. It’s a very powerful introspection tool, i.e., one that gives us the ability to examine the properties and methods that an object contains. The reason that this statement is so important is that you may not always know the name of the object that you want to “look into” or much about it at all. This means that the JavaScript for…in statement allows you to abstract away the details of the future object that you will want to examine, and just say: “whatever object I reference, find out what is inside that object and tell me all  about it!”

Helpful links for the JavaScript “for…in” statement

 http://www.w3schools.com/js/js_loop_for_in.asp

http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/

http://msdn.microsoft.com/en-us/library/55wb2d34(v=vs.94).aspx

How to return an object literal from a JavaScript constructor

JavaScript

JavaScript object LogoWhile it is easy enough to create an object literal, there are cases in which you may want to return one from a constructor. When doing so, you return an object literal that has added value.

Everyone knows that creating a JavaScript object literal is as simple as: var foo = {}. No problem at all. In fact, we can even add properties and methods to this object with such expressions as:

or…

While these approaches are both simple, there is a difference between an object literal and an instance of a class. For example, var foo = new Foo() is not quite the same thing as our previous var foo = {}. The question is, can we have it both ways? On the whole, the answer is: “Yes!

Because of the very expressive nature of JavaScript, what we return from a function is really up to us. So, if we want to have a constructor function that returns an object literal, we can literally (sorry : – ) just use the “return” statement, and put an object on the other side of that.

Example # 1 – Return a simple object

In example # 1, the bar variable becomes an instance of our Foo() constructor. As a result, bar is an object literal. When we run its say() method we get the expected output, and if we were to run the following command: console.log(bar.color), we would get “blue“. But there is really not much added value here. Of course we could have accomplished the same end result by simply saying var bar = {} and including the same exact properties and methods.

But there is, in-fact, great potential for some pretty serious added value here. For example, the difference between simply assigning an object literal to bar and returning an object literal from our Foo() class is that when we instantiate Foo(), we sill have access to the outer function. This closure provides a scope in which we can store private members, to be accessed later if we wish, which is very important.

Example # 2 – Return an object with a privileged method

In example # 2, we still return an object literal, and as a result, the resulting instance is just an object literal. The added value is that we also defined one private variable:  _acctNum. In fact, translates to a new level of functionality: the _acctNum variable is not available to the outside world. Therefore, we have complete control over how it is mutated. Here we have defined two methods _getAcctNum and _SetAcctNum. Therefore, these privileged members have access to our private variable _acctNum. So, most importantly, we can change or retrieve the value of _acctNum using these two privileged methods.

Finally, we can do the following:

Summary

The added value of returning an object literal from a constructor is that while you have a very simple hash table to work with as your instance, you also have access to private variables that were defined within the constructor. As a result, in this case, you can think of the returned value as bar = {}, but with added value.

Helpful Links about JavaScript Objects

http://www.w3schools.com/js/js_objects.asp

http://www.quirksmode.org/js/associative.html

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

How to Include a Function as a JavaScript Object Literal Member

JavaScript

JavaScript LogoJavaScript object literals can contain not only properties, but methods too

Some may automatically think of a JavaScript object as a name / value pair scheme with flat members that are essentially just scalar values. Fortunately, this is not quite the case. An object literal can also include functions among its members. Those functions can do everything that any function would otherwise do; it just happens to be a member of an object. You define a function as an object member simply by assigning an anonymous function to the key, instead of the usual scalar value.

Example # 1:

The output for Example # 1 would be: “Hi, my name is: Don Draper, my address is: 123 E. Maple Ave., and I am 36, years old” The reason for this is that in addition to the properties we have defined, we define a member that is a reference to an anonymous function. That function takes two arguments: the current year and the year Don was born. It calculates Don’s age, and then returns the result.

Some might say: “Why not just declare a function and use it?” You can certainly do that, but as I have covered in previous posts, it is usually best practice to create name-spaced objects in order to keep the global space clutter free. When doing so, you can define your members within your object. And, one or more of those members can be a function. I can think of few circumstances when this is not a good idea. It makes your code more readable and easy to manage.

Summary

There are many useful things you can do when making a function a member of an object literal. This post simply covers the basics.

Helpful Links about JavaScript Objects

http://www.w3schools.com/js/js_objects.asp

http://www.quirksmode.org/js/associative.html

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

Immediate Functions in JavaScript – The Basics

JavaScript

JavaScript LogoFunctions are a very powerful feature in JavaScript; they provide modularity and scope. The immediate function, WHICH offers a heightened level of functionality, is an often overlooked feature of JavaScript

An immediate function is one that executes as soon as it is defined. Creating an immediate function is simple: you add the open/close parentheses after the closing curly bracket, and then wrap the entire function in parentheses. That’s it!

Example # 1:

In Example # 1, we have a very simple function. If you were to paste this function into your code and run it, nothing would happen. This is because the function is assigned to a variable, and that is it. We have only the function declaration here, but we never call the function. But if you were to add the line “myFunc();” to this code and run it, the output would be: “I am a simple function”.

Example # 2:

In order to turn this function into an immediate function, we add the open/close parentheses after the closing curly bracket and then wrap the entire function in parentheses. After we do this, we run the code and whatever happens in that function is executed immediately after the function declaration is complete.

So the output for Example # 2 would be: hello, I am an immediate function

Example # 3:

In Example # 3, we first declare a variable called “myName” before declaring our function. When declaring our immediate function, we take one argument: “thisName”. At the end of the immediate function declaration, the open/close parentheses pass the variable “myName” to our immediate function. So, not only does this set of open/close parentheses execute the function, it also allows you to pass an argument to that function.

The output for Example # 3 would be: “hello, my name is: bart Simpson”

Summary:

In this article, we touched on what immediate functions in JavaScript are, how to construct one, and how to pass parameters into them. But immediate functions in JavaScript can get very deep, very quickly. There is a world of power and subtlety that is available to you via immediate functions. Since that is out of the scope of this post, however, it will be covered in more detail in later posts.

Helpful Links for JavaScript Immediate Functions

http://nandokakimoto.wordpress.com/2011/05/17/javascript-immetiate-object-initialization/

http://stackoverflow.com/questions/939386/javascript-immediate-function-invocation-syntax

http://dreaminginjavascript.wordpress.com/2008/07/03/immediate-execution/

 

How to Create a Custom Object with Public and Private Members

JavaScript

JavaScript LogoBy making a distinction between what members of your object will be accessible to the  outside world, you can enforce a much higher degree of control and avoid unpredictable behavior

In a previous post, I discussed how to create your own name-spaced JavaScript object. This is a highly recommended approach that keeps the global name space free of clutter and helps make your code easier to read and manage. When you create your own custom JavaScript object, by default, all members are public. This is generally not to your advantage. While wrapping all of your functionality in a custom object is a smart move, because all of its members are public, other code in the page that might be out of your control has full access to your object, which cold lead to problems.

Best practice is to make a clear distinction between which members of your object are public, and which members are private. The goal is to provide the absolute minimum access possible in order to allow your code to work as intended.  This is known as “Principle of least privilege” or “Principle of least authority” (POLA).

In some programming languages, there are reserved words that easily provide scope for object or class members, such as “private”, “public”, “static” or “protected”.  There is no built-in syntax that provides scope in JavaScript. Functions are the tool you use to provide scope and they do so very well. But because there is only one tool we have in-hand to create the desired scope for object members (or variables in general), there are a few techniques you need to use that allow you to use functions to create scope.

Example # 1:

The output for Example # 1 would be:  “My name is: Foo, My address is: 123 E. Bar St.”

This is not an optimal situation because all the members of our object are public. In order to create the desired scope, we can wrap all of the objects members in a function.

Example # 2:

The output for Example # 2 would be: “undefined, undefined”

While we have made progress by wrapping the members in a function to provide scope, we have created another problem because these members are no longer publicly accessible. By using “var” when declaring the variables, they remain local to the function (good), but un-available to the outside world. The way to correct this is to create a public member that has privileged access to these private members.

Example # 3:

The output for Example # 3 would be: “Foo, 123 E. Bar St.”

In Example # 3, the variable “obj” is set to the data member, inside of our object: “myObj”.  By using the “this” keyword, we expose the members “getMyName” and “getMyAddress” publicly. While “getMyName” and “getMyAddress” are public methods, the variables “myName” and “myAddress” are still local, which means that they are private and not available outside of the member “data”. But, and here is the part that makes all work, “getMyName” and “getMyAddress” have complete access to all the private members of “data”. So “getMyName” and “getMyAddress” can  return these private members, while they and anything else we want to protect, remain privately scoped.

Summary:

This is a very basic example, but the building blocks you need are all there. Creating a name-spaced global variable is a great approach that keeps the global name space clutter free. But, it is generally good practice to keep your object’s properties and methods private to whatever degree makes sense. Exposing the minimal number of members publicly is known as “Principle of  least privilege” or “Principle of least authority”. By taking this approach, you keep your code safe from harm, easier to manage and also keep a tight leash on the behavior of your application.

Helpful Links regarding public and private Object members in JavaScript

http://javascript.crockford.com/private.html

http://stackoverflow.com/questions/55611/javascript-private-methods

http://stackoverflow.com/questions/483213/javascript-private-member-on-prototype

http://en.wikipedia.org/wiki/Principle_of_least_privilege