Understanding the difference between scope and context in a JavaScript method

JavaScript

scope and contextSometimes the concepts of scope and context are misunderstood in JavaScript. It is important to understand that they are not the same thing. This is particularly important inside of a method.

In JavaScript, the concept of scope refers to the visibility of variables. On the other hand, the concept of context is used to mean: “the object to which a method belongs”. That may sound like an odd statement, but it is accurate. The only time we care about context is inside a function. Period. Inside a function, the “this” keyword is very important. It refers to the object to which that function belongs. In other words, every function is a property of some object. In client-side JavaScript (i.e. in a browser), if you declare a function at the top of your code, then that function is a property of the window object. So, inside of that function, the “this” keyword refers to the window object. If you create a new object (let’s call it: “myObject”) and add a method (i.e. a property that happens to be a function), then inside of that function, the “this” keyword refers to the object (i.e. “myObject”).

So the main issue is that inside of a method, object properties and variables can sometimes be confused. In short; when the JavaScript “var” keyword is used, that is a variable. A variable will not be a property of an object (except in the global scope, which is for another discussion). But inside a method, any variable created using the JavaScript “var” keyword will be private to that method. So this means that it is not possible to access that variable from outside the method. But inside of a method, you have access to all of the properties of the object to which that method belongs. And you access these properties using the JavaScript “this” keyword. So, for example; if myObject.greeting = “Hello” and myObject.greet is a method, then inside myObject.greet, if I reference this.greeting, I should get the string: “Hello”. And if I have declared a variable named “speed” inside of myObject.greet, I would access it simply by referring to “speed” (i.e. I would not use the JavaScript “this” keyword). Also, a big difference between variables and properties in a method is that properties are always public. That is to say: all object properties can be seen and in most cases modified. But a private variable inside of a method is completely hidden from the outside world. And only our code inside of the method has access to that variable.

Try it yourself !

In above example, we start out by creating a property on the window object named: “foo”. This “foo” object is the result of an immediately invoked function expression (aka: “IIFE“). The reason that we take this approach is so that we can have a private variable: count. Our getCount method as access to that private count variable.

There is also a count property on the “foo” object. This property is available publicly. That is to say: we are able to make changes to the count property, whereas the count variable is not available outside of the IIFE. Our getCount method has access to the count variable, but that is the only way we can reach it.

When we call foo.getCount() without passing any arguments, then it increments the count property and returns it. This is CONTEXT. By using the JavaScript “this” keyword inside of the getCount method, we are leveraging the concept of context. Conversely, when we call foo.getCount(“scope”), then the count variable is incremented and returned. This is SCOPE. It is very important to understand the difference between scope and context in JavaScript.

Getting Started with ECMAScript 6 Arrow functions – The “this” keyword

JavaScript

ECMAScript 6 LogoOther than syntax, the biggest change that ECMAScript Arrow Functions brings about, is how it relates to context: in the function body, “this” has a different meaning than you may expect.

It seems to me that the two problems that are solved by ECMAScript 6 Arrow functions are: verbose syntax and the tricky nature of “this” inside a function. Granted, when working with methods and constructors, the meaning of “this” is a bit easier to understand. But when working with functions that are not constructors, or not bound to an object, the “this” keyword will resolve to the window object, and that is rarely the behavior you want. In a function that is defined in the global scope, it is probably unlikely that you will intentionally want to refer to “this” (and global function declarations should really be kept to a minimum or even better, avoided at all costs). But when you have a function that is declared inside of a method for example, it is not at all uncommon to attempt access to “this” from the nested function. This is where the frustration starts, because the meaning of “this” will vary depending on the circumstances.

Example # 1A

In Example # 1A, the object foo has two properties: “color”, whose value is: “red”, and the method: “getColor”. The method foo.getColor has a nested function: privateGetColor, which references “this”. The problem is: inside of privateGetColor, “this” refers to the window object. Since there is no window.color, privateGetColor returns: “undefined”, which means that foo.getColor() returns “undefined”.

Example # 1B

In Example # 1B, we have fixed the situation by creating a private variable named: “me” inside of foo.getColor, which caches “this”. This way, the nested function: “privateGetColor” now has access to “this”, and this foo.getColor returns “red”.

Example # 2

In Example # 2, we have a more elegant solution. By leveraging an arrow function, we no longer need to create the variable “me”, in order to cache the value of “this”. Now that the nested function: privateGetColor is an arrow function, we can reference “this” in the arrow function’s body. Since privateGetColor now returns “red”, foo.getColor() returns “red”.

Lexical binding of “this”

The reason that Example # 2 saves the day, is because of the change in meaning for the “this” keyword inside of an arrow function. Normally, “this” will refer to the object of which the function is a method. With arrow functions, “this” is bound lexically. This means that it is where an arrow function is defined that affects the meaning of “this”, not where it is executed.

Example # 3

In Example # 3, we have an object named “bar”, which has a “color” property. When we execute foo.getColor(), we use the call method to change the context in which getColor is executed. This should have changed the meaning of “this” to “bar”, which would result in the return value of “blue (i.e. privateGetColor.call(bar) should return: “blue”). But that is not what happens; the return value of foo.getColor() is: “red”.

The reason for all of this is that inside of an arrow function, “this” is bound lexically. So, it is where an arrow function is DEFINED, not where it is executed, that determines the meaning of “this”. It might help of think of how scope works in JavaScript. The lexical binding of “this” inside the body of an arrow function behaves in a similar way. The closest containing object outside of the arrow function will be resolved as “this”.

Summary

The meaning of “this” inside an arrow function is without doubt a significant change in the JavaScript specification. Since ECMAScript 6 is 100% backwards-compatible, this has no effect on the meaning of “this” inside of normal function definitions, function expressions, constructors or methods. While it may take a while to get used to this concept, the ramifications are very positive. The ability to reference a specific object inside of a click-handler or AJAX calls makes for code that will be easier to read, manage and extend.

The JavaScript “this” Keyword Deep Dive: jQuery Click Handlers

JavaScript

JavaScript LogoLearn the difference between $(this) and “this” inside of your jQuery event handler.

In two previous posts, we learned that functions that are properties of an object are called “methods” (The JavaScript “this” Keyword Deep Dive: Nested Methods & The JavaScript “this” Keyword Deep Dive: An Overview). In this case, the JavaScript “this” keyword refers to the object that the method belongs to. Well, of course, this is usually pretty obvious from looking at the code.

But in an event handler, it may not be apparent to all that the JavaScript “this” keyword, is available to you inside of the event handler, and that it refers to the element that generated the event. Since many front-end developers are comfortable with jQuery, I thought I’d start with jQuery event handlers. And since click events are so common, let’s stick with that.

Example # 1

In Example # 1, we have created a click event handler using jQuery. When the user clicks the anchor tag inside of the element with the class: “download”, the jQuery “toggleClas” method is used to change the text “Click Me” fom red to blue.

Of course, many have seen $(this) used inside of the event handler to set a reference to the element that was clicked. It is helpful to know, however, that $(this) is an enhanced version of the JavaScript “this” keyword. That is to say: inside of the click event handler, “this” refers to the element that was clicked. When you put “this” inside of: $( ), you “wrap” the JavaScript “this” keyword with jQuery, which adds a number of properties and methods.

As a result of this “wrapping”, you can set a reference to the element that was clicked, but you can also leverage the power of jQuery. The native JavaScript HTML element does not have a “toggleClass” method, but jQuery does. So, by wrapping the JavaScript “this” keyword with jQuery, $(this) has allowed you to reference the clicked element, and use jQuery methods.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/9gZbE/

How to Demo: Click the text that says: “Click Me”. Each time you click that element, the text color will toggle between red and blue.

Example # 2

In Example # 2, we have changed the reference to the clicked element from $(this) to “this”. But when you click that element, there is an error in the JavaScript console. In Google Chrome, the error is: Uncaught TypeError: Object [object HTMLAnchorElement] has no method ‘toggleClass’, and in FireFox, the error is: TypeError: this.toggleClass is not a function. The reason for this error is that while the JavaScript “this” keyword can be used to reference the element that was clicked, it does not have a “toggleClass” method. So, an error occurs.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/9gZbE/1/

How to Demo: Open up your JavaScript console, and then click the text that says: “Click Me”. When you do, you will see an error indicating that the element you clicked does not have a “toggleClass” method.

Example # 3

So, in Example # 3, we continue to reference the element that was clicked by using the JavaScript “this” keyword, without the jQuery “wrapping”. That is: we are not using: $(this). The reason that the example now works, is because we are using the “classList” property of the element, and in-turn, the “contains”, “remove” and “add” methods. Consequently, this allows us to mimic jQuery’s “toggleClass” method.

It’s important to note that although we used jQuery to create the click handler, we can still use the JavaScript “this: keyword inside of that event handler, and access the native JavaScript element object.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/9gZbE/2/

How to Demo: Click the text that says: “Click Me”. Each time you click that element, the text color will toggle between red and blue.

Summary

In this article, we learned about the JavaScript “this” keyword when used inside of a jQuery event handler. We learned that we can “wrap” that keyword with jQuery, leveraging that library’s DOM manipulation methods. We also discussed how inside of a jQuery event handler, we can still use the “un-wrapped” version of “this”, and leverage native JavaScript DOM manipulation methods.

The JavaScript “this” Keyword Deep Dive: Constructor Functions

JavaScript

JavaScript LogoLearn how the JavaScript “this” keyword differs when instantiating a constructor (as opposed to executing the function).

In earlier articles of the “The JavaScript “this” Keyword Deep Dive” series, we discussed how the meaning of “this” differs in various scenarios. In this article, we will focus on JavaScript constructors. It is critical to keep in mind that in JavaScript, constructor functions act like classes. They allow you to define an object that could exist. The constructor itself is not yet an object. When we instantiate that constructor, the return value of the instantiation will be an object, and in that object, “this” refers to the instance object itself.

So, inside of a constructor function, the JavaScript keyword refers to the object that will be created when that constructor is instantiated.

Example # 1

In Example #1, you’ll see that we have created two new properties of the window object: “music” and “getMusic”. The “window.getMusic” method returns the value of window.music, but it does so by referencing: “this.music”. Since the “window.getMusic” method is executed in the global context, the JavaScript “this” keyword refers to the window object, which is why window.getMusic returns “classical”.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor.

We’ve also created a constructor function named “Foo”. When we instantiate Foo, we assign that instantiation to the variable: “bar”. In other words, the variable “bar” becomes an instance of “Foo”. This is a very important point.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor. If you remember from previous articles, constructor functions act like classes, allowing you to define a “blueprint” object, and then create “instances” of that “class”. The “instances” are JavaScript objects, but they differ from object literals in a few ways.

For an in-depth discussion of the difference between an object literal and an instance object, see the article: “What is the difference between an Object Literal and an Instance Object in JavaScript? | Kevin Chisholm – Blog”.

Earlier on, we established that inside a function that is not a method, the JavaScript “this” keyword refers to the window object. If you truly want to understand constructor functions, it is important to remember how the JavaScript “this” keyword differs inside that constructor. When you look at the code, it seems as if “this” will refer to the window object. If we were to simply execute Foo as if it were a normal function, this would be true (and we will discuss this scenario in Example # 3). But we don’t simply execute Foo; we instantiate it: var bar = new Foo().

When you instantiate a JavaScript constructor function, an object is returned. The JavaScript “this” keyword has a special meaning inside of that object: it refers to itself. In other words, when you create your constructor function, you can use the “this” keyword to reference the object that WILL be created when the constructor is instantiated.

So, in Example # 1, the getMusic method returns “this.music”. Since the “music” property of Foo is: “jazz”, then the getMethod returns “jazz”. When we instantiate Foo, the variable “bar” becomes an instance of Foo, so bar.getMusic() returns “jazz”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/2RFa3/

Example # 2

In Example # 2, we have changed Foo’s “GetMusic” method. Instead of returning “this.music”, it returns an executed function. While at first glance, it may seem as though the “getMusic” method will return “jazz”, the JSFiddle.net link demonstrates that this is not the case.

Inside of the “getMusic” method, we have defined a variable that is equal to an anonymous function: “myFunction”. Here is where things get a bit tricky: “myFunction” is not a method. So, inside that function, the JavaScript “this” keyword refers to the window object. As a result, that function returns “classical” because inside of “myFunction”, this.music is the same thing as window.music, and window.music is “classical”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/2RFa3/1/

Example # 3

In Example # 3, we have an example of a scenario that you don’t want: executing a JavaScript constructor function instead of instantiating it. Hopefully, this is a mistake that you will catch quickly, but it can happen. It is also possible that you might inherit code that contains such a bug. Either way, this is bad.

While the Foo constructor still has a “getMusic” method, because we execute Foo, instead of instantiating it, the code inside of Foo overwrites two properties that we created earlier: window.music and window.getMusic. As a result, when we output the value of “this.getMusic()”, we get “jazz”, because when we executed Foo, we overwrote window.music, changing it from “classical” to “jazz”.

While this is a pattern that you want to be sure to avoid in your code, it is important that you be able to spot it. This kind of bug can leave you pulling your hair out for hours.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/2RFa3/2/

Summary

In this article we learned how the JavaScript “this” keyword behaves in a constructor function. We learned about instantiating a constructor and the relationship between “this” and the instance object. We also discussed a couple of scenarios that are important to understand with regards to “this” and constructor functions.

The JavaScript “this” Keyword Deep Dive: Nested Methods

JavaScript

JavaScript LogoDepending on the scenario, the JavaScript “this” keyword may refer to the object of which the method is a property, or the window object.

In an earlier article: The JavaScript “this” Keyword Deep Dive: Nested Functions, we learned how functions that are not methods evaluate “this” to the window object. In that post, we demonstrated that no matter how deeply you nest functions, this behavior is always the same. In this article, we will learn how the JavaScript “this” keyword behaves in nested methods.

So, here, it might be a good idea to quickly answer the question: “What is a nested-method”?

A method is a function that is a property of an object. A nested method occurs when a method, in turn, returns an executed method.

The reason that this scenario is an important one to consider is that while you may execute method A, if that method returns the executed method of object B, then inside of that second method, the JavaScript “this” keyword refers to object B (not object A).

Example # 1

In Example # 1, we have added a property to the window object named “music”, and set the value to: “classical”. We have also added a method to the window object named “getMusic”, which returns the value of window.music. But, notice that instead of referencing window.music, the method returns: this.music. The reason that works is that since the method is a property of the window object, “this” refers to the window object. This means that this.music is the same thing as this.music, and the value of that property is: “classical”.

We have also created an object named “foo”, and it has the exact same-named properties we specified above, and the “getMusic” method has the exact same code: return this.music. But foo’s “getMusic” method returns “jazz”, because foo.music = “jazz”, which means that inside of foo’s “getMusic” method, the JavaScript “this” keyword refers to the foo object, and foo.music is “jazz”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/5uUJ8/

Example # 2

In Example # 2, we have created an object named: “foo”, which has a method named: “getMusic”. The getMusic method returns an object with two properties: “music”, which is equal to “rock”, and “getMusic” which returns this object’s “music” property.

When we pass the output of foo.getMusic() to the console, we see that is: “rock”, and now “Jazz”. The reason for this is that foo’s getMusic method ignores foo’s music property. That is, it returns an object, and that object’s getMusic method returns its own “music” property. In this scenario, we have nested a method: foo.getMusic, that returns the executed method of another object. The reason for this example is to demonstrate the fact that even though foo.getMusic returns a nested method, when the nested method utilizes the JavaScript “this” keyword, it refers to the object that it is a property of, not foo.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/5uUJ8/1/

Example # 3

So, in Example # 3, we take the exact same approach as Example # 2, providing an additional level of method-nesting. As you might expect, the innermost method returns “metal”, the value of the “music” property to which the getMusic method belongs.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/5uUJ8/2/

Example # 4

Example # 4 is somewhat similar to Example # 3, except that the nesting is logical, not physical: each getMusic method, in turn, calls the getMusic method of a different object. The end result is the same as Example # 3: “metal”. But instead of one method returning an anonymous object whose getMusic method is executed, each of the getMusic method calls here return the execution of another named-object’s “getMusic” method.

It is also important to note that the first console.log call: this.getMusic returns “classical”, because the window.getMusic method is a property of the window object. But, each of the other objects (i.e. “rockObject” and “metalObject”) have its own “music” properties, so when the “metalObject.getMusic” is called, it returns the value of metalObject’s “music” property, which is “metal”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 4: http://jsfiddle.net/5uUJ8/3/

Summary

In this article we discussed how the JavaScript “this” keyword behaves inside of nested methods. We learned what a nested method is. And we also learned how, in this scenario, the JavaScript “this” keyword refers to the object of which the method is a property, not the window object.

The JavaScript “this” Keyword Deep Dive: Nested Functions

JavaScript

JavaScript LogoLearn how the JavaScript “this” keyword behaves inside of function declarations and expressions, even when nested 10 levels deep.

In the article: The JavaScript “this” Keyword Deep Dive: An Overview, we discussed a number of scenarios in which the JavaScript “this” Keyword has different meanings. In this article, we will concentrate on functions and methods.

It’s important to note that methods are functions. What makes a method a method is that the consumer of the code specifies an object, and then calls a method of that object.

Example # 1

In Example # 1, we have executed a function and a method. We have actually executed two functions, but the second function: “someMethod” is actually a method of the “bar” object. We know this because we have used the syntax: object.method().

It’s important to understand the difference between executing a function and a method.

Example # 2

foo = function (){ return this.music; }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/84Yd4/

In Example # 2, we have executed the function “foo”, which returns the value of “this.music”: “classical”. Both console.log statements return the value: “classical”, because since we are not inside of a method, the JavaScript “this” keyword refers to the window object, and at the top of the code, you’ll see that window.music is equal to “classical”.

Example # 3

foo = function (){ function bar(){ function baz(){ function bif(){ return this.music; } return bif(); } return baz(); } return bar(); }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/84Yd4/1/

In Example # 3, things get a bit silly, but the effect is the same. Even inside of nested functions, because none of these functions are methods, the JavaScript “this” keyword refers to the window object. And “this.music” is the same as “window.music”, which is equal to “classical”.

Example # 4

foo = function (){ function bar(){ function baz(){ function bif(){ function billy(){ function bobby(){ function betty(){ function jetty(){ function jimmy(){ function judy(){ return this.music; } return judy(); } return jimmy(); } return jetty(); } return betty(); } return bobby(); } return billy(); } return bif(); } return baz(); } return bar(); }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

In Example # 4, the function-nesting concept is taken to a ridiculous level. Nonetheless, the output is exactly the same: “this.music” is the same as “window.music”, which is equal to “classical”. It does not matter how deeply a function is nested. Unless it is a method of an object, the JavaScript “this” keyword will always refer to the window object.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/84Yd4/2/

Summary

In this article we learned that when a function is not specified as a method of an object, the JavaScript “this” keyword refers to the window object. This is true even in the case of nested functions. In fact, no matter how many levels deep we nest functions, the JavaScript “this” keyword refers to the window object.

The JavaScript “this” Keyword Deep Dive: An Overview

JavaScript

JavaScript LogoLearn the subtle yet critical details that allow you to leverage the JavaScript “this” keyword.

In JavaScript, the “this” keyword is one of the most overly-used yet under-utilized aspects of the language. It is also one of the most mis-understood topics. While it facilitates more readable, expressive object-oriented JavaScript, improper use is a catalyst for confusing code that is difficult to debug.

Personally, I’ve struggled to understand the mystery. I’ve heard many unusually long-winded explanations, which I feel only contribute to the silliness. Simply put: In JavaScript, “this” refers to the object upon which a function is invoked. That’s it.

In JavaScript, “this” refers to the object upon which a function is invoked.

This means that “this” can only be used in a function, or globally. When used in either of these cases, “this” refers to the window object. When the function is a method of an object, then “this” refers to the object that the method is a member of. When the function is a constructor, then “this” refers to the instance object. There is much more to talk about with regards to what “this” means in varying scenarios, but these are the most common situations.

Example # 1

In Example # 1, we have added a property to the window object, named it: “music”, and assigned the value “classical”. In the line that follows, we output the value of “this.music”, and the result is: “classical”.

The reason for the output is simple: If you execute arbitrary code in the global context (i.e. outside of a function), then “this” refers to the window object. Executing arbitrary code in the global context is highly discouraged, but it is important to understand this behavior from a theoretical standpoint; in the global context: “this” will evaluate to the window object.

Example # 2

In Example # 2, we have added a function named foo, and then logged the output of that function’s execution. The resulting value is: “classical”. Some may have expected the output to be “blues”. This is a common mistake.

In the function “foo”, “music” is a variable. The “this” keyword has to do with objects, never variables (there is a very subtle scenario where “this” refers to a variable, which we will address in a later post). So the fact that there is a variable named “music” is completely meaningless in this example. The function “foo” does only one thing: it returns the value of this.music. In that function, “this” is the widow object, and the value of window.music is: “classical”. So, the variable “music” is completely ignored.

Example # 3

In Example # 3, we have added an object named “bar”. This object has two properties: “music”, which has a value of “jazz” and “getMusic”: a method that returns the value of bar’s “music” property.

The “getMusic” method has a line of code that you have seen in previous examples: “return this.music”. But why does that line of code return: “jazz”? The reason for this behavior is that when a function is a method of an object, the “this” keyword refers to the object upon which that function is invoked. In this case, the object is “bar”, and bar’s “music” property is equal to “jazz”, so “this.music” is equal to “jazz”.

Example # 4

In Example # 4, we have added the constructor function: “Baz”. “Baz” has a property named “music”, and it is equal to “rock”. It also has a property named “getMusic”, which is a method. The “getMusic” method returns the value of Baz’s “music” property.

You may be thinking that inside of the “Baz” constructor, the “this” keyword refers to the window object, as discussed in Example # 2. If we were to simply execute “Baz” (e.g. Baz() ), then yes, the property window.music would be overwritten and given the value of “rock”, and there would be a new global property named “getMusic”, which would return “rock”.

But that’s not what happens. After we create the constructor: “Baz”, we instantiate it, which results in a variable named “bif”, an instance of “Baz”. When you instantiate a JavaScript constructor function, the “this” keyword inside of that function refers to the instance object that the constructor returns.

HERE IS THE JS-FIDDLE.NET LINK

FOR EXAMPLE # 3:

Summary

In this article we discussed the high-level details of the JavaScript “this” keyword. We learned that it refers to the object upon which a function is invoked, and how it means different things in different scenarios. The scenarios we covered are: the window object, inside of a function, inside of a method, and inside of a constructor function.

What’s the Difference Between jQuery().each() and jQuery.each() ?

jQuery

jQuery LogojQuery’s two .each() methods are similar in nature, but differ in level of functionality

Some may find it difficult to understand the difference between jQuery.each() and jQuery().each(). Perhaps the easiest way to understand the difference is to start with jQuery().each(). This method can only be used against a jQuery collection. So when you do this: jQuery(‘#someDiv p’).each(), what you are saying is: “for EACH paragraph that is inside of the element with the ID of “someDiv”, I want to do something. That’s it.

The jQuery.each() method is a static method of the jQuery object. This means that it is just a method that’s out there for you to use, and you need to give it a little more info. But there is a bigger payoff with this method: it can be used to iterate over different kinds of things, not just a jQuery collection.

The syntax for the jQuery.each() method is also simple:

So, OBJECT can be an object, an array, an array-like object or even a jQuery collection. How cool is that? The CALLBACK is a function that will be run against each element in the first argument. The super-star feature here is that the first argument can be a jQuery DOM collection. This means that jQuery.each() can do ANYTHING that jQuery().each() can do. Let’s jump into some code:

jQuery().each()

Example # 1.A

In Example # 1.A, we have an unordered list, with the days of the week as list items. The last two have the “weekend” class applied. We use the $().each() method twice. In the first run, it will iterate over every one of the list items. In the second run, the jQuery collection contains only the last two list items because they have the “weekend” class.

In both cases though, we can see how the $().each() method does one thing and does it well: it iterates over a jQuery collection. Inside of that collection, we use $(this) to get a reference to the current element being iterated over.

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

 

Example # 1.B

In Example # 1.B, we take advantage of two additional features that the jQuery().each method has to offer. The callback takes two optional arguments: the index of the current element being iterated over, and the element itself. In our example, we add the index of each element to its text, and we do so by referencing ‘element’ instead of ‘this’. Keep in mind that ‘element’ is just what we decided to name that argument variable. We could just have easily named it ‘foo’ or ‘glove’. It doesn’t matter what you name these variables, just as long as you are aware of what they are.

We also used the .hasClass() method to see if each element had the “skip” class. This was just a way to illustrate the fact that while you CAN do things to each element inside of the callback function, you can also choose not to. There are numerous ways that you can organize this kind of logic. Using the ‘skip’ class was merely a ‘quick and dirty’ approach.

Here is the JSFiddle Link for Example # 1.B: http://jsfiddle.net/9C8He/

jQuery.each()

Example # 2.A

In Example # 2A, we pass-in two arguments to the static jQuery.each() method: an array and an anonymous callback function. The array has three elements, and the callback merely outputs the value of each array element to the console. Pretty simple stuff.

Here is the JSFiddle Link for Example # 2.A: http://jsbin.com/epanov/1/edit

 

Example # 2.B

In Example # 2.B, we provide an object as the first argument to the jQuery.each() method. When iterating over an object, the jQuery.each() method will return the property name for ‘index’. This is a brilliant approach, as it provides a very flexible alternative to the native JavaScript “for/in” loop.

Here is the JSFiddle Link for Example # 2.B: http://jsbin.com/examuz/1/edit

 

Example # 2.C

In Example # 2.C, we provide a jQuery DOM collection as the first argument to the jQuery.each() method. Essentially, this is just like using the jQuery().each() method. Inside of the callback function, ‘index’ can be used to get a numerical reference to the current element being iterated over, and ‘value’ will be the element itself. Brilliant.

NOTE: You may wonder why the last two elements have indexes of 0 and 1 respectively. This is because we specified that list items with the ‘weekend’ class should be returned in the collection. So, our jQuery collection object contains only two elements (‘saturday’ and ‘sunday’).

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

 

Summary

In this article we learned the difference between the jQuery.each() and jQuery().each() methods. We also discovered that while they do differ, the jQuery.each() is flexible enough to provide the same functionality as jQuery().each() if needed.

Helpful Links for jQuery().each() and jQuery.each()

jQuery().each()

http://api.jquery.com/each/

jQuery.each()

http://api.jquery.com/jQuery.each/

How to Create a Name-Spaced Object to Avoid Using Global Variables in JavaScript

JavaScript

JavaScript LogoThere are two ways to dynamically add an element to the end of a JavaScript array

Sometimes you may need variables that are available to every function in your script. While it is tempting to use global variables to achieve this kind of scope, doing so can cause unpredictable results and spaghetti code. If you create your own object, define your properties and methods, and then access them via a clean, name-spaced syntax, you control the scope as well as the code’s behavior.

Example # 1:

Here are a few examples of using global variables. In each case, it is very easy to lose track of the value of these variables throughout your script, as well as which functions have access to them.

You may want to access these variables from multiple functions in your code, and in various scenarios, change the value of those functions. This is certainly possible, but there are better ways to achieve the same functionality.

Example # 2:

In this example, we create a custom object called “bankClient”. We then define the properties of this object.

In this example, there are two ways that we could access these variables:

Example # 2A

  • object.property
  • object[‘property’]

Example # 2B

Either one of the above approaches will work just fine.

Example # 3:

You can also define a method for your object.  A method would be a function that you define within the object, and then call by using the same name-spaced syntax.  In the example below, we expand our object by adding a method. This method returns the value of the client account number.  You may notice the use of the “this” keyword. In such a case, “this” refers to the object who’s context we are currently in, which would be “bankClient”. This is something you’ll see often when working with objects in JavaScript.

That value is hard-coded in the object definition, but then  notice how we change the value of the property, and then retrieve it. In the same manner, the property “name” is at first empty, but we assign a value to it, and then grab that value (i.e. “Roger Sterling”).

The output for Example # 3 would be:

123456
Account # changed to: 111-222-333
Client Name: Roger Sterling

Summary:

Creating your own custom object is a good way to avoid cluttering up the global namespace. It is also an improved method of keeping tabs on your variables as they become properties of the object. You can define methods for your object and access them the same way. In doing this, you create organized code that’s easier to read, maintain, and extend.

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