Introduction to JavaScript Default Parameters

JavaScript

JavaScript default parametersJavaScript functions can take arguments, but they are optional by nature. Default parameter syntax makes it easy to determine if one or more arguments have been provided and if not, initialize them.

While something like Typescript can make it easier to enforce certain practices, use is voluntary. Ultimately, you can’t force a consumer to provide one or more arguments to your function. There are ways to work around this problem, but solutions are not simple. As is often the case, for example, solutions sometimes introduce new problems. There’s good news on this front, though, and in this article, I will demonstrate the JavaScript default parameter syntax and how it solves the above-mentioned problem.

The JavaScript default parameter syntax is surprisingly simple; instead of specifying an argument in the parentheses, you initialize it. This may look a bit deceiving, and, in fact, some may think that by doing this you are absolutely setting that value. But quite the contrary: what you are saying is: “If argument X is not provided, then initialize it and set it equal to this value.” So, you’re providing a “default” value for that argument, and if that argument is provided when the function is executed, then the provided value is used.

Example # 1

See the Pen JavaScript Default Parameters – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

In Example # 1, the addBonus() function takes one argument: “bonus.” In that function, we had to write code that checks to see if the “bonus” argument was provided. If it was, then we use the provided value. Now, this code works just fine, but there’s a problem. If we accept this solution, that means that we’ll write code that is virtually identical to it any place else in our application where the same problem needs to be solved. So, of course, it’s worth remembering here that any time we have repeated code, we know that there’s a better way to solve a problem.

Example # 2

See the Pen JavaScript Default Parameters – Solution 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

Now, when you take a look at the approach in Example # 2, you’ll see an immediate improvement. We’ve leveraged default parameter syntax so that the “bonus” argument is now optional, thereby creating the biggest advantage of this approach, which is that there is no longer any repeated code. By simply initializing the “bonus” argument, we ensure that if not provided, that variable will have a value.

JavaScript Interview Questions – Functions

JavaScript

JavaScript LogoBefore you head into that interview, make sure you understand how functions work, and the various components of their behavior.

Functions play a major role in the JavaScript language. In addition to providing private scope, they allow you to organize blocks of code for later execution. While most front-end developers have used JavaScript functions many time, there are some core areas of knowledge that are important to know.

I consider the following topics to be the baseline for a decent understanding of JavaScript functions.


Q: What is the length of the above function named: “foo”?
A: 3

Hint: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length


Q: In a function, what does the word “arguments” refer to?
A:
It is a property of the function, and is an array-like list of the arguments that were actually passed into the function
Hint: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments


Q: What does the above function return?
A: “undefined” (without quotes)
Hint: If you do not specify a return value in a function, it returns undefined .

return – JavaScript | MDN

undefined – JavaScript | MDN


Q: Given the above code, what will be the console output when foo() is executed?
A: “hello there undefined”
Hint: When a function executes, any  arguments that are not passed-in have a value of: undefined.


Q: Given the code above, how would you programatically obtain a string representing the source code of the function?
A: foo.toString()
Hint:
Function.prototype.toString() – JavaScript | MDN


Q: Given the above code, how would you change the call to: “executeFunction” function, so that it will execute the “sayHello” function?
A:

Hint:

javascript pass function as parameter – Stack Overflow


Q: Given the above code, how would you change the call to the: “alertGreeting” function, so that it will alert the return-value of the “getGreetingText” function ?
A:

Hint:

Functional Programming — Eloquent JavaScript


Q: Given the code above, how would you change the “isFunction” function so that when it is passed a function, it returns true, and if not, it returns false?
A:

Hint:
Use the JavaScript “instanceof” operator:  instanceof – JavaScript | MDN


Q: Given the code above, how would you change the “sayHello” function so that it executes immediately after it id defined? (i.e. there is no need to call it, it executes right-away)

A:

Hint: You can turn that function into a self-executing or “immediate” function by wrapping it in parentheses, and adding a pair of parentheses after that: (yourFunctionHere)().

Immediate Functions in JavaScript – The Basics | Kevin Chisholm – Blog

Immediately-invoked function expression – Wikipedia, the free encyclopedia

JavaScript Interview Questions – Beginner

JavaScript

These are basic JavaScript questions that any front-end web developer should be able to answer.


Q: What is the keyword used when declaring variables that makes them private to a function?

A: “var”
Hint: http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript


Q: What is the one and only way to control variable scope in JavaScript?
A: Functions
Hint: http://blog.kevinchisholm.com/javascript/scope/


Q: What are the two possible values of a boolean type?
A: true and false
Hint: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Boolean


Q: Which web browser implements Document.attachEvent()?
A: Internet Explorer 8 and below
Hint: http://msdn.microsoft.com/en-us/library/ie/ms536343(v=vs.85).aspx


Q: How do you create a DIV element using JavaScript?
A: document.createElement(‘div’)
Hint: https://developer.mozilla.org/en-US/docs/DOM/document.createElement


Q: if var foo = “hello”, how do I coerce foo to be a false value?
A: !foo
Hint: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators


Q: If I have var foo = document.createElement(‘img’), how do I set the “src” attribute of that image element to “someimage.jpg”?
A: foo.src = “someimage.jpg”
Hint: http://www.javascriptkit.com/jsref/image.shtml


Q: How would you check if the variable “foo” is equal to exactly 5 OR is equal to exactly 7?
A: if (foo === 5 || foo === 7){ // do something here…};
Hint: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators


Q: What is the difference between “=”, “==” and “===” in JavaScript?
A: “=” assigns a value, “==” checks for equal value, “===” checks for equal value and type
Hint: http://stackoverflow.com/questions/4846582/what-is-difference-between-and-in-javascript


Q: Does Internet Explorer Implement Event Capturing?
A: Only IE 9 and above
Hint: http://javascript.info/tutorial/bubbling-and-capturing

Validating JavaScript Function Arguments

Functions

JavaScript LogoGracefully handling corner cases is the key to writing more robust, error-free JavaScript.

If you work with JavaScript for a living, you write functions. There is just no way around this. So, if you write functions, then arguments are a part of your life. Now, if you are the only one who uses the JavaScript code you write, then life is pretty grand. But if you are writing code that will be consumed by others, then gracefully handling corner cases and errors becomes important; very important.

So, every time I write a function, I assume that someone else will call it. Even if I know no one will, I assume that someday, someway, someone will. Even if it never happens, I feel its a good habit to get into: write code that fails gracefully.

There are a zillion paths down which this conversation can go, but let’s focus on function arguments. When your function absolutely depends on an argument, and that this argument be of a certain type, and that it not be empty, or otherwise useless, you might have a recipe for disaster, if your hungry little function does not get what it needs.

Example # 1A

Example # 1B

In Example # 1A, we use an IF () block to make sure that the “arg” argument was passed-in before we attempt to do anything with it.

Good enough, right?

Not so fast…

Even though we have taken care to make sure we got the “arg” argument, what if our implementation code is a bit lengthy? Well, in Example # 1B we see how silly it is for all that implementation code to be wrapped in an IF () block. This kind of pattern breeds code that is annoying to maintain.

Example # 2

Ahhhhh, now that’s better!

So, as you can see in Example # 2, we simply say: “hey, if arg does not exist, then return.” This was accomplished using the JavaScript logical NOT operator. So, this means that if the argument “arg” does not exist, the function ends right there and none of the implementation code that follows is ever executed.

But…..

What if we need to be 100% sure that the argument “arg” is what we need it to be? What if it’s not enough to simply know that “arg” exists? What if we need to know that “arg” is an array and it has at least one element?

So many questions, so many darned questions.

Example # 3

Ahhhhh… that’s even better! In Example # 3 we’ve once again used the JavaScript logical NOT operator to say the following: “hey, if the argument someArray was not passed, OR if it is NOT an array, OR if it does NOT have at least one element, return.” This way, we can check for all the details we need in one neat little line and avoid a series of messy nested IF () blocks. We do our test, we feel good if none of the expressions evaluated to false, and then we proceed with confidence.

Summary

In this article we discussed function argument validation. We learned how to avoid wrapping our code inside of a large IF() block and validate the presence of the argument we need in one line. We also discussed how to test for the type of our argument, and the fact that it contains the minimum amount of data.

Helpful Links for the JavaScript Logical NOT Operator

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators

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

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

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 Scope in JavaScript

JavaScript

Although the ‘with’ statement creates a block-level scope effect, and recent implementations of the “let” statement have the same effect, these are fodder for another conversation. I’m not a big fan of the “with” statement, and at the time of this writing, you can’t be 100% sure that the “let” statement is fully supported by the user’s browser. The end result of this is the fact that there is no block-level scope in JavaScript. Scope is created by functions.

Example # 1

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

In Example # 1, we set the global variable “month” equal to “july”. But inside of the function “foo()”, we also create a variable named “month”, and give it a value of “august”. The second statement in foo() is a call to the console, telling it to output the value of the variable “month”.

So, why is it that in the global scope, “console.log(month)” outputs “july”, but executing “foo()” outputs “august” ?

The reason is that inside of the function “foo()”, we used the “var” keyword to create the variable “month”. When you use the “var” keyword, the variable you create becomes local to the function that you create it in. So, inside of “foo()”, the variable “month” is local, and equal to “july”. As a result, on the very next line, the statement: “console.log(month)” outputs “july”. Inside of “foo()”, we have no knowledge of the global variable “month”, because in the scope chain, the variable “month” is found locally, so the search for “month” ends within the local scope of “foo()”.

Example # 2

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

In Example # 2, we have added a function named “bar()”. Bar does not have a local variable named “month”. So, when “bar()” executes, the statement “console.log(month)” kicks off a search for the variable “month”. In the scope chain, there is no local variable named “month”, so the JavaScript engine looks to the next level of the scope chain, which happens to be the global scope. In the global scope, there is a variable named “month”, so the value of that variable is returned, and it is “july”.

So, “foo()” outputs: “august” and “bar()” outputs: “july”, because, although they both look for a variable named “month”, they find completely different values; in their respective scope chains, the value of a variable named “month” differs.

Example # 3

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

In Example # 3, notice a new statement in the “foo()” function: “window.season”.

In this statement, we are creating a global variable named “season”. Although we are within the context of the “foo()” function, we can reference the global scope by mutating the “window” object. “window” is essentially the global object. Creating a global variable while inside of the local scope of “foo()” is easily done by adding a property to the “window” object; in our case we name it “season” and give it a value of “summer”.

So once again, although we are in the local scope of “foo()”, we have just created a global variable named “season” and given it the value of “summer”, by adding a new property to the “window” object (e.g., window.season = ‘summer’).

Example # 4

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

In Example # 4, we create another global variable while within the local scope of “foo()”, named “weather”. This approach is different because when we say: weather = “hot”, the absence of the “var” keyword automatically makes the variable global. This is important to remember and make note of: If you omit the “var” keyword when creating a variable, no matter where you do it, that variable becomes global.

In general, this is something that you want to avoid, as it can lead to code that is hard to understand and even harder to maintain. But for the purpose of this discussion, it illustrates an important behavior in JavaScript: omitting the “var” keyword when creating a variable makes that variable global, no matter where you do it. I’m repeating this because it is an important detail to remember.

Example # 5

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

In Example # 5, we yet again create a new global variable from within the local scope of “foo()”. This variable is named “activity”. We demonstrate yet another way in which you can do this by saying: this.activity = ‘swimming’. This introduces another concept: the meaning of “this” inside a function (no pun intended).

Inside a function, the “this” keyword refers to the context in which the function is executed. In our example, “foo()” is executed in the context of the global object, so “this” referes to the global object, which means that “this.activity” adds a property to the global object named “activity”.

Make note: While “foo()” has it’s own “local” scope, the keyword “this” refers to the context in which “foo()” is executed. This is another important detail to remember. It will come up a lot when writing more advanced JavaScript.

Another (very) important note:  An “implied global” is what occurs when you omit the “var” keyword when declaring a variable. There is a subtle, yet important difference between that and a variable created using the “var” keyword in the global scope: an implied global is actually not a variable; it is a property of the “window” object. For the most part, it behaves very much like a global variable, but there are differences: for example, you cannot delete a global variable, but you can delete a property of the window object. This is a topic worth looking into when you have time, and at minmum, good to be aware of.

Summary

At first, the concept of scope in JavaScript can be a challenge to fully understand. But it is very much worth the effort. Once you understand scope, the JavaScript language becomes a sharp knife that can be used to sculpt elegant and expressive code. This tutorial discussed only the most basic concept of scope in JavaScript. I highly recommend exploring it in-depth.

Helpful Links for Scope in JavaScript

https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/

http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/

http://oranlooney.com/function-scope-javascript/

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

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

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/

 

 

Executing an Array of JavaScript Functions Using the shift() method

JavaScript

JavaScript Logo

Sometimes you have multiple JavaScript functions that you need to execute in a specific order, but do not know the details ahead of time

Both jQuery and Dojo offer their own flavor of “Deferred” functionality. This is a pretty deep topic that, while a bit challenging, offers tremendous power with respect to queuing up an invocation of multiple functions in an orderly manner. One concept that plays into this way of thinking is using the JavaScript array object’s shift() method. It easily fires off some functions in order, even when you don’t know ahead of time how many there will be.

Example # 1

var b = function(){ console.log(“this is function: b”) } var c = function(){ console.log(“this is function: c”) } var foo = [a,b,c]; while (foo.length){ foo.shift().call(); }

In example # 1, we define three functions. Then, we build an array with each element being a reference to one of our functions.  Now, using a while loop, we call each function. There is a cool interplay going on here. For the while loop, as long as foo has length (that is as long as the length of foo does not return a “falsy” value, such as zero), the loop will run. Inside the loop, the JavaScript shift() method not only removes the first element from the array, it also returns that element. So, we chain onto that return value, which is the function itself, and use the JavaScript .call() method, to actually invoke the function. With each iteration of the while loop, the array looses an element. It therefore becomes smaller and smaller until finally,  “foo.length” returns zero, which is “falsy,” and the loop no longer runs.

The end result here is that you can have a list of functions that you can execute, one at a time, in a specified order, and each function runs only once.  A much more practical use for this technique is when you are adding methods to the array (i.e. our “queue”), at run time. You don’t know how many you might add, or what they might do, but you know that you can line ’em up, and fire ’em off!

Summary

Because so much of what the Front End Web Developer deals with happens in the life of a page, there are many circumstances in which you are not sure how many of something will come along. But if you are able to get your hands around such dynamic events, you can handle some pretty cools scenarios. Invoking an unknown number of functions at runtime is such a case. This technique provides a fairly simple way to implement this approach.

Helpful links for the JavaScript Array Object’s shift() Method

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

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/shift

http://www.bennadel.com/blog/1796-Javascript-Array-Methods-Unshift-Shift-Push-And-Pop-.htm

http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/shiftMethod.htm

 

 

Writing Argument-Agnostic JavaScript Functions

JavaScript

JavaScript LogoThere is no need to tightly couple a function and the other function that might call it, by sweating the details of the arguments passed in. You can access the local “arguments” variable, examine it, and decide how to handle the situation

Somewhere, I still have the code from my first fairly serious JavaScript project. From time to time, I like to take it out and look it over. It’s riddled with functions that, while written in good spirit, clearly reveal my level of inexperience at the time. This is not something I am proud to discuss publicly, but it is the truth. And, I always tell myself that everything is relative; some day I will look back on code I wrote last week and recoil with the same horror. Programming is a never-ending learning process and while the initial learning curve is steep, the process never ends; we always strive to improve our skill set.

One of the things that really stood out in my mind was how many functions I wrote that looked something like this:

While I don’t think it’s completely insane that I would write a function that takes so many specific arguments, I’ve come to realize that this approach tightly couples the function with the other function that might call it. The reason I keep mentioning “…might” is that in many cases, we write functions that are probably called in the lifetime of the program, but as many JavaScript apps are event-driven, it is not unusual for events to sometimes not happen, which means that functions are sometimes not called.

The point here is that tightly-coupled functions are, of course, sometimes unavoidable, but to me, it always seems a shame to have to write a function that is tightly coupled to its caller, but may never be called. So, I started to think about decoupling these functions from each other as much as possible. Granted, a function like “updateRecord()” will likely only be called to… well… update a record, but we can make it a bit more generic so that we don’t have to worry so much about what arguments were passed in when we write our code. We can simply write the function as if all the arguments we need have been passed in, and then “handle” the corner cases where some arguments are missing. This also frees up the caller in that there is reduced stress, as well, from that end; the caller can pass-in all the expected arguments, some of them, or none of them. What happens in these cases is, of course, up to us, but it does not always have to be an “all or nothing” scenario.

 Example # 1

In Example # 1, we don’t assume any arguments are passed in. We first test to see if the local “arguments” variable has a length that is greater than 0. If it does, great; we can then do something with the arguments. Most likely, we will want to examine them and see if the ones we need are available.

It is important to note that the “arguments” variable is not a true JavaScript array. The subtle details of this are worthy of another post. But keep in mind, it is simply a local variable that is array-like, in that it is an indexed list that can be iterated over and it does have a “length” property.

 Example # 2

In Example # 2, we loop through all of the arguments. Inside the loop, we could examine each argument and see if it meets the needs of the function.

Example # 3

In Example # 3, we pass an object in as the argument to our “updateRecord()” function. What is helpful about this approach is that the “updateRecord()” function does not break or throw an un-handled exception if we pass in too many arguments, not enough arguments, or no arguments. The function simply covers the following:

  1. Were any arguments passed in?
  2. If more than zero arguments were passed in, let’s loop through each one
  3. On each loop, if the argument being examined is an object, let’s loop through its properties
  4. On each sub-loop, we can do something with each property

Granted, your function may be a bit useless unless the exact number of arguments are passed-in and they are named in some exact way. But, your function does not have to be completely useless. It can handle corner cases gracefully, return a useful error, or maybe even partially carry out its intended task. The assumption here is that you or someone on your team will write this function and the one that calls it, so in the end, you can implement your own logic to make this function useful, yet unbreakable.

Summary

This topic is more of a pattern than a specific implementation. I like to use it because I prefer to keep my functions as loosely coupled as possible. It may not always be possible to keep them 100% uncoupled, but I prefer a pattern in which I can pass a function the right, wrong, or partially right number of arguments, and that function can inspect what it gets and handle the situation gracefully. A big plus when passing in an object, is that you can at least not worry about the order of the arguments; you simply grab the passed-in object, and enumerate the properties. What you do with what you find is up to you.

Helpful links for the JavaScript arguments property

https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments

http://javascript.info/tutorial/arguments

 http://stackoverflow.com/questions/5303003/best-use-of-the-arguments-property-in-javascript

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