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

What is the difference between a back end and a front end web programming language?

Web Development

You may have heard the terms “back end” and “front end” with respect to web development languages. Some may find them confusing, but there is not too much mystery to it at all.

In the most basic terms, the moniker says it all: a back language runs on the server and does all its work before the page gets to you. By the time you see the web page, any back end  technology that was used to construct and then serve up the page is no longer involved. Conversely, a front end language operates on the client side. It works in your browser and does not do anything until the page and its associated assets comes over the wire.

Back End Programming Language

An example of a back end language is PHP, which is a scripting language. When a user requests a PHP page, the server parses the PHP code, which in most cases results in dynamically created HTML. A PHP page can simply contain HTML. It is not required to include any scripting code at all, but any code that is in the page will be parsed.  Consequently, the web page viewer never sees one line of PHP code. Assuming that the web server administrator has configured the server correctly, it will surely never show you the actual PHP code.  This is because the web server parses the PHP and then generates the page. This results in HTML. Although, a web developer can use PHP to serve up any other text-related asset. For example: JavaScript, JSON, CSS or XML.

Front End Programming Languages

In web-development, many people often use the terms “front-end” and “client-side” to express the same thing. Specifically, they refer to technology that the end user’s computer executes. That is to say, the browser understands these languages and is thus able to interpret the code.

Consequently, this is the exact opposite of a back-end programming language. Specifically, a web server does not understand HTML, CSS or JavaScript. It simply ensures that files that contain these languages can be downloaded . The web server cannot execute HTML, CSS or JavaScript. (There is an exception with regards to JavaScript, which will be discussed shortly.) But, browsers such as Internet Explorer, FireFox and Chrome do understand these languages, and are able to execute them on the front-end. Accordingly, this means that your computer parses HTML, CSS and JavaScript. In the case of JavaScript,  your computer executes that code.

JavaScript is probably the most commonly used front end web development programing language. Technically, it is a scripting language. Unless you explicitly disable JavaScript in your browser, you see and interact with it every day. When you request a web page, the JavaScript is either in the page, or is downloaded in a separate file. JavaScript runs in your browser, and most people only associate it with those annoying pop-up ads. This was true in the past, but today, JavaScript plays an integral part in creating rich user experiences.

Important Note: Although JavaScript has historically been a 100% front end technology, it is now a fully mature back end language as well. Thanks to the brilliant work and vision of Ryan Dahl, JavaScript can now be run server-side by using Node.js.

Helpful Links for Back End and Front End Languages

Front-End / Client-Side Languages & Technologies

JavaScript

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

http://blog.kevinchisholm.com/tag/native-javascript/

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

ActionScript

https://en.wikipedia.org/wiki/ActionScript

https://github.com/languages/ActionScript

http://www.adobe.com/devnet/actionscript.html

CSS

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

http://www.w3.org/Style/CSS/Overview.en.html

Kevin Chisholm – Blog – Posts about: CSS

Back-End / Server-Side Languages

PHP

http://www.php.net/

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

http://en.wikibooks.org/wiki/PHP_Programming

http://www.codecademy.com/tracks/php

ASP.NET (C# / VB.NET)

http://www.asp.net/

http://en.wikipedia.org/wiki/ASP.NET

http://msdn.microsoft.com/en-us/library/vstudio/4w3ex9c2(v=vs.100).aspx

ASP.NET Overview

ASP.NET and Visual Studio for Web

Java

http://www.java.com/en/

https://en.wikipedia.org/wiki/Java_(programming_language)

Node.js (Server-Side JavaScript)

http://nodejs.org/

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

http://blog.kevinchisholm.com/tag/node-js-2/

http://stackoverflow.com/questions/2353818/how-do-i-get-started-with-node-js

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

What is the difference between GET and POST?

JavaScript

Depending on what you are trying to accomplish, GET and POST are used in different ways.

What is a GET?

In short, a GET is appended to the URL while a POST is embedded in the body of the request. Maybe from time to time, you have noticed something similar to this in your address bar: ?name=something&choice=something-else&category=something-more. This is a GET. Everything after the question mark is a query string. The page that processes this request strips out these values, parses them and acts upon them. The most notable thing here is that your request is public: it appears in the address bar of the browser.

A GET is very simple and easy to implement and parse, but it is 100% not secure. Also, each browser imposes its own limit on the length of an URL. There is no limit specified by a W3C RFC, but it is best to avoid depending on URLs that exceed 255 characters. So, there is a limit to how much data you can pass using a GET. Also you must take care in how you handle special characters. One advantage of a GET is that you could actually save the complete URL, including query string for later retrieval, or you could send that URL to a friend. At times, this can be useful.

What is a POST?

A POST is embedded in the actual body of the message. While not 100% secure, this is more secure than using a GET because the data passed does not appear in the address bar. Also, there is no limit to the amount of data passed. One downside to a POST request is that a page refresh looses the POST data and you cannot save or send a saved URL to a friend.

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

AJAX Can Have a Negative Impact on your SEO

JavaScript

You heard the term, you asked your front-end web developer to implement it on your site, and then you bragged to your peers at cocktail parties about it: AJAX. While the upside is in many cases, a more pleasant UX, there could be a negative impact on your SEO.

There are many different scenarios where one might implement AJAX, but one to watch out for is when you are delivering content that is pertinent to your page. Imagine this scenario:

  • You have a page that offers a brief yet useful description about each of the 50 US states
  • Instead of making users wait for a full page refresh, you have your front-end developer implement AJAX so that when the user selects a state, the brief description is fetched from the server and displayed. No page refresh, just a quick GET that returns the information.

The good news is: Your user has a better experience than one that would have to wait for 50 page refreshes if they wanted to know about every state.

The bad news is: Your content is not being indexed but any search engines.

If you are scratching your head, think about the scenario we described above. Each time the user selects a state, the data is fetched from the server via AJAX. This means that the requested content is not part of the page. Search bots do not understand or interact with AJAX, they simply scrape the page and index the content that is contained in the markup at their discretion.  This means that when a search bot arrives at your page, it never sees the 50 descriptions about the various states.  So, while you have created a richer UX, you are doing so at the price of your SEO, which has in theory, diminished.

Summary:

This is not the end of the world. It is simply a good dynamic to be aware of. There is a way to work around this. Inside of a set of <NOSCRIPT> tags, you could have the content that includes the brief descriptions on all 50 states. This way the search bots will see the content when indexing your page. Also, visitors who use screen readers will have access to that content as well. It’s a “best of both worlds” approach that allows you to continue creating a richer browsing experience for your visitors who have JavaScript enabled, but also cater to those who do not have JavaScript enabled, or use a screen reader, and also keep your SEO… well… “Optimized” !

Kevin Chisholm

 

High Performance Web Sites: Essential Knowledge for Front-End Engineers

JavaScript

High Performance Web Sites Essential Knowledge for Front-End Engineers By Steve Souders

This is a short book with a long title, but don’t let the number of pages fool you. This title packs a ton of useful information for font end web developers.

Steve Souders lays out his rules for high-performance websites and not a character is wasted. Inside these 14 rules are the street-smarts from which any front end developer can seriously benefit.  Some of these rules may be less newsworthy than others. For example, using CSS Sprites and making fewer HTTP GET requests may not be a complete revelation to some. But there are more high-performance techniques that you may not be aware of. There is particularly detailed coverage of Expires Headers and ETags, the surprising subtleties of which can greatly affect performance. Other notable areas of interest are reducing DNS lookups, minifying javascript and the advantages of CDNs.

An impressive aspect of this book is the use of graphic performance reports, with detailed explanations. Steve Souders does not just spew theory. In most cases, he uses the top 10 websites and performs speed tests using recent tools of the trade. In each case, there is an easy-to-understand graphic that makes it very simple to see how a particular website performs, with respect to component downloads and page rendering. With every graphic report there is a full play-by-play that leaves nothing to the imagination.

Summary: For even the most casual web developer, this knowledge truly is essential.

  • Title: High Performance Web Sites: Essential Knowledge for Front-End Engineers
  • Author: Steve Souders
  • Number of pages: 176
  • Publisher: O’Reilly Media
  • Published Date: September 18, 2007 (1st edition)
  • Language: English
  • ISBN-10: 9780596529307
  • ISBN-13: 978-0596529307