JavaScript Interview Questions: Arrays

JavaScript

Q 1: Name two ways to dynamically add the value “bar” to the array “foo”

A:

Hint: Two Ways to Dynamically Append an Element to a JavaScript Arrayy


Q 2: Of what JavaScript type is an Array?

A: object

Hint: Associative Arrays in JavaScript


Q 3: What property tells you the length of a JavaScript array?

A: The “length” property

More Info on the JavaScript Array’s “length” property:

Why is a JavaScript Array’s Length Property Always One Higher Than the Value of the Last Element’s Index?


Q 4: If the array “foo” has a length of 10, what is the index of the first element in the array?

A: 0

Hint: JavaScript Arrays are zero-based


Q 5: If the array “foo” has a length of 10, what is the index of the last element in the array?

A: 9

Hint: JavaScript Arrays are zero-based


Q 6: What is the syntax you would use to assign the first element in the array “foo” to the variable “bar”?

A:


Q 7: True of False: An element in a JavaScript array can be another array

A: True

Hint: JavaScript Array elements can be arrays


Q 8: Given the following line of code, what is the length of the array “foo”?

A: 0

Hint: foo is an Array literal, but in this line of code, no elements have been defined.


Q 9: What does the array.shift() method do, and what does it return?

A: It removes the first element from the array and returns that element

More info on the JavaScript array.shift() method:

JavaScript Array Management with Push(), Pop(), Shift() and Unshift()/a>


Q 10: Given the following line of code, what would be the output of the console?

A:  [undefined, undefined, undefined]

Hint: When you instantiate the JavaScript Array() constructor, and pass in a single number, that number will indicate the length of the array, but the elements are still not initialized (i.e. they are all undefined)


Helpful Links for JavaScript Arrays

Kevin Chisholm – YouTube: Array

Kevin Chisholm Blog – Array

The JavaScript for…in statement – enumerating object properties

JavaScript

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

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

No problem dude.

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

Example # 1

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

The output of example # 1 would be:

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

Summary

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

Helpful links for the JavaScript “for in” statement

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

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

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

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

How to use the JavaScript indexOf() method to find the position of one string in another string

JavaScript

JavaScript LogoThe JavaScript indexOf() method allows you to find out if a string contains one or more characters, and if so, the starting position of that set of characters

If you’ve ever found yourself saying: “How do I figure out if one string contains a certain character or a sub-string?” then the JavaScript indexOf() method is for you. It returns the starting position of a string, even if it is one character. If that string does not exist, then it returns “-1”. So, if you want to know if a given string even exists at all in another string, simply test to see whether or not the JavaScript method indexOf() returns “-1”. If it does, then the sub-string does not exist. If the return value is “> -1” (i.e. more than -1), then the string does exist.

Example # 1

In Example # 1, we check for the starting position of “football” within the string “Hello world”. Because “football” does not exist in “Hello world”, the return value is “-1”

Example # 2

In Example # 2, we use an “if else” condition to test for the string “football” in “hello world”. In this case, it does not exist.

Example # 3

In Example # 3, we have included the string “football” in “hello world”, so the test returns the starting value of “football”, which is “6”. So, the test evaluates to “true”, the “true” text is displayed, and at the end of that text, we return the starting position of “football”.

Summary

The JavaScript indexOf() method is the best way to find out if one string exists inside of another. If it does, the starting position of that searched string is returned. If the sub-string does not exist, then “-1” is returned; this is  a reliable indicator of “does not exist”.

Helpful links for the JavaScript indexOf() method

http://www.w3schools.com/jsref/jsref_indexof.asp

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

http://www.tizag.com/javascriptT/javascript-string-indexOf.php

 

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

Two Alternatives to the jQuery Document Ready Function for JavaScript

jQuery

jQuery Logo

There are two alternatives to document ready that are a bit easier to type

Most JavaScript programmers are familiar with jQuery’s document ready function. There is no doubt that it is a very helpful way to wrap your JavaScript with a cross-browser compatible function that will not run until the document has achieved a “ready” state. While the syntax is fairly simple, there are two slightly less verbose alternatives to the exact same functionality.

Example # 1

 

In Example # 1, we have the standard syntax for the jQuery document ready function.

Example # 2

 

In Example # 2, we omit the “document / ready” portion of the equation, and simply insert our function in the following expression $().

Example # 3

In Example # 3, we chain a jQuery ready() function to the return value of the jQuery object: $().ready(). So, when the jQuery object is ready, so is our code.

Summary

There is no doubt that the jQuery document .ready() function is super-useful. There is however, more than one way to invoke this functionality.

Helpful links for the jQuery document .ready() function

http://api.jquery.com/ready/

http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

http://rpheath.com/posts/403-jquery-shorthand-for-document-ready

http://think2loud.com/653-jquery-document-ready-howto/

 

 

 

Why is a JavaScript Array Length Property Always One Higher Than the Value of the Last Element’s Index?

JavaScript

JavaScript Logo - Array Length

The “length” property of a JavaScript array is a very helpful tool, but why is array length
always one “off”?

Arrays in JavaScript are zero-based. This means that JavaScript starts counting from zero when it indexes an array. In other words, the index value of the first element in the array is “0” and the index value of the second element is “1”, the third element’s index value is “2”, and so on. This is not unusual in computer programming languages. The JavaScript array length property is given in a one-based context. So, a JavaScript array with one element will have a “length” of “1”. If a JavaScript array has four elements, then that array’s “length” property will have a value of “four”. But (and here is the point where many get confused), if a JavaScript array has four elements, the last element has an index of “3”. This is because, again, JavaScript arrays are zero-based.

The Array Length – Example # 1

In Example # 1, we have an array with five elements. The console.log() statement reflects this as well because the “length” property of this array is “5” (i.e. this is a one-based value).

So, even though the array has a length of 5, the first element has an index of 0, and the last element (the 5th element) has an index of 4. Now this is the most important point, and it’s what explains the “off” reference: the length of the array is always one higher than the index of the last array element because the array indexes are zero-based, but the length property is one-based.

One Less Than the Length – Example # 2

In Example # 2, we create a variable who’s value is one LESS than the length of our array. So, since our array’s “length” property is “5”, our “len” variable is equal to “4”. Our loop will start at 0, and run until it equals “4”. This IS five iterations, but we are starting at 0, not one. So, since JavaScript starts counting Arrays from Zero, our code successfully outputs the value of each element in the array.

This is a very common technique: when you want to iterate an array, you create a for-loop, and set the max iterations to “one less than” the length of the array. Now while this may seem tedious, it’s actually a rock-solid pattern to follow, because the array’s length will always (always) be one higher than the index of the last element in the array. So, it follows that if your loop iterates X times, and X equals “one less than” the length of the array, then your loop will always iterate over every element in the array. This takes a little getting used to, but once you do, it becomes second nature.

Console Output – Example # 3

Summary

JavaScript arrays are zero-based. The JavaScript array “length” property returns the number of elements in an array, but it is a one-based value. So whenever you want to use the “length” property to say “hey, start from the first element in an array and go until you reach the last element,” start from zero, and go until you reach the array’s “length” property value, but “minus one!”

Helpful Links for JavaScript Arrays

JavaScript Array Management with Push(), Pop(), Shift() and Unshift()

Two Ways to Dynamically Append an Element to a JavaScript Array

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

JavaScript

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


Object Literals

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

Example # 1

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

The output for example # 1 is:

foo
5
bar
baz
this is the say function

Instance Objects

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

Example # 2

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

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

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

Summary

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

Helpful links for JavaScript Objects

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

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

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

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

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

JavaScript

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

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

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

Example # 1

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

Example # 2

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

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

Summary

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

Helpful links for Immediate Functions in JavaScript

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

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

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

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

 

 

Understanding the difference between null and undefined in JavaScript

JavaScript

JavaScript LogoIt is quite common to confuse null and undefined, but there is an important difference between them.

null

Simply put, null is a JavaScript keyword that indicates the absence of a value. Surprisingly, if you run the following in your firebug console:  console.log( typeof null ), you will see “object”. Don’t be fooled though. This object is not mutable, has no properties, and there is at all times only one instance of it. It simply evaluates to “no value”. Although, this is a perfectly valid value in JavaScript. If you want to strip a variable of any value, assign it to “null”.

Example # 1

In Example # 1,  we created an object called “foo”. The console.log statements demonstrate the odd, yet perfectly valid behavior of “null”. At first, the type of foo is “object”. After we assign foo to null, it is still an “object” type, yet when we console.log the value of foo, it is simply “null”.

undefined

In JavaScript, “undefined” is a global variable (a property of the global object), that is created at run time. This global variable represents something  that has not been initialized. It also represents an object property or array index that does not exist. Also, when you do not supply an argument for a function parameter, it will have the value of “undefined”. Furthermore, when a function does not return a value, it returns “undefined”. Have you ever wondered why sometimes when you execute a function in the FireBug console, you see “undefined” in the console? That is because while your function may actually do something wonderful, if it does not explicitly return a value, then it returns “undefined”.

Example # 2

In Example # 2, when we attempt to determine what type “undefined” is, we are told that it is of the type “undefined”.  Hence, there is only one instance of the “undefined” value, and it has the value of “undefined” (do you have a headache yet?). In the second line, we attempt to output the value of foo to the console, but we get a “ReferenceError”. This is because while asking what the type of an undeclared variable is does not harm anyone (it is the type “undefined”), attempting to access that variable causes an error because it essentially does not exist. But, if we assigned foo to “null”, and then tried to access it, no problem. This is because if we assign foo to “null”, it has a value, and that value is “null” (i.e. “no value”). But when something evaluates to “undefined”, it does not exist.

Summary

In JavaScript, “null” and “undefined” have different meanings. While “null” is a special keyword that indicates an absence of value, “undefined” means “it does not exist”.

Helpful links for JavaScript “null” and “undefined”

http://saladwithsteve.com/2008/02/javascript-undefined-vs-null.html

http://weblogs.asp.net/bleroy/archive/2005/02/15/Three-common-mistakes-in-JavaScript-_2F00_-EcmaScript.aspx

http://sharkysoft.com/tutorials/jsa/content/045.html

 

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

 

 

Building Dynamic HTML Markup with JavaScript – the Basics

JavaScript

JavaScript LogoWhen you need to iterate over a data set, and build markup using its elements, there are a few techniques that make this a snap

Sometimes you may need to build markup and insert it into the page, but perhaps you do not know what that markup will be. Actually, you would probably know most of what will happen: you have some markup that needs to be repeated one or more times, and in each iteration, the text in certain elements will change. A typical scenario is one in which you have multiple records in a data set, and you need to create a series of elements that will be similar, but each row in the data set will have it’s own copy of the markup and display its values. Same markup, but unique values with each iteration.

Example # 1

 

In Example # 1, we first created our data set (the variable “arr”), which is a JavaScript array. Each element of the array is an object literal, containing three fields. We then proceed to loop through all the elements of the array and for each one, we create a form. In each form, we mix the markup (which is the same with each iteration), but mix in the values from the data set so that when finished, each element in our data set has its own HTML form (think of it as rows in a table or records in a database). When we are finished creating the markup, we simply use the jQuery .html() method to insert our markup into the DOM, using the ID of a specific HTML element.

Two Quick Notes:

Variable Declarations – When declaring multiple variables, keep in mind that you can do so with one “var” statement, and separate each variable name with a comma. This makes things a bit easier to read and some argue that it is faster.

String Concatenation – Instead of one insanely long string, you can use the “+” operator, and break your assignments into multiple lines. Although this is JavaScript, it makes it look a bit more like actual markup.

Summary

There are, of course, much more elegant ways to do this; John Resig’s JavaScript Micro-Templating technique is a cool example. And there are plenty of others out there.  Here, I’ve simply covered the basic concept of working with data, and creating HTML on the fly to present that data in the page, regardless of the amount of data, or values it contains.

Helpful links for building dynamic HTML markup with JavaScript

http://markalexanderbain.suite101.com/an-introduction-to-dynamic-html-with-javascript-a74777

http://www.scriptingmaster.com/javascript/outputting-dynamic-HTML.asp

http://stackoverflow.com/questions/6106402/php-vs-javascript-for-dynamic-html-pages

Super Easy HTML Video Support with LongTail Video’s JW Player and JavaScript

JavaScript

JavaScript LogoThis video player makes it simple to present video in your HTML page, and configure a wide array of options

While the new HTML5 video element brings much promise to the concept of full native browser support, it can still be a bit of an effort to provide cross-browser consistency. LongTail Video’s JW Player offers a way to implement some fall-back support and very cool customization. This little puppy does a great job of auto-detecting which method of playback is supported by the user’s device, and presents accordingly. There is support for both Flash and HTML5, skinning, plugins and a very robust API. At the bottom of this post are a few links that will more than get you started. I’ll simply highlight how easy it is to get JW Player up-and-running in your web page.

Example # 1

In example # 1, just to demonstrate that the most current version of JW Player works with a two-year-old version of jQuery, we pull in jQuery 1.4, and what would be a local copy of the jwplayer.js. With that done, we simply call the jwplayer() method, passing in the ID of the element within which we’d like the video player to run, and chain the return value to the JW Player .setup() method. We pass a configuration object to that method, and away we go! The only two requirements here are the jwplayer.js file and the player.swf file.

Example # 2

In example # 2, we added an “events” property to the configuration object, and to that property, we added an onReady method, which starts the video once the player is ready.

Example # 3

In example # 3 there is a code snippet that demonstrates the ability to remove a video from the page. JW Player takes care of all the DOM cleanup, including removing any bound events. You can add the video back in real-time by simply running the original function that appeared in the document.ready() method.

Summary

There is plenty (and I do mean plenty) to sink your teeth into here. I’ve only scratched the surface of the surface. If you are looking for a plugin that makes video support easy and offers tons of options, JW Player is a serious contender. Non-commercial use requires no payment and the commercial licence is very reasonable.

Helpful links forJW Player

http://www.longtailvideo.com/players/

http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/12540/javascript-api-reference

http://wordpress.org/extend/plugins/jw-player-plugin-for-wordpress/

jQuery Under the Hood with Paul Irish

jQuery

jQuery Logo

If you’ve never poked around inside of jQuery, you should. Paul’s videos are a great way to get started

I decided to ring in the new year with two of Paul Irish’s videos that I had book-marked, but had not gotten around to viewing: 10 Things I Learned from the jQuery Source and 11 More Things I Learned from the jQuery Source.

In these two videos, you have Paul’s screen, so that you can follow his code, and a small sub-screen of his head while he talks, so that you can follow his hilarious commentary and thought pattern. My only complaint: there is so much good stuff here to dive into that it takes an hour to watch a 30 minute video because of the constant temptation to hit “pause” and then fire up JSFiddle and play around with the concepts that he discusses.

10 Things I Learned from the jQuery Source – YouTube

In general, exploring the un-minified version of jQuery is just plain ol’ good sense. There is a tendency to simply use jQuery and treat it as some magic black box that “just works, and works great…” But the fact of the matter is, there is only one thing going on inside of that giant self-executing function: JavaScript. That is it.

Everything that jQuery does for you, you could have done for yourself… but, jQuery is better, stronger and faster than the average bear. Fair enough. But, that does not mean that we should not lift up the hood, poke around and learn from the code inside… because what is going on in there is pretty dammed cool. The jQuery folks do things in some very interesting ways and there are tons (and I do mean tons) of neat stuff to learn from.

11 More Things I Learned from the jQuery Source – YouTube

Highlights of Paul’s videos include a brief discussion of jQuery’s “no conflict” feature,  his decision to hijack the .ready() method, and a hilarious discussion of how jQuery detects the presence of Internet Explorer (and the technique used is just so brilliantly creative that I had to once again pause the video, copy the code while squinting at the YouTube page, and try it in notepad myself… it just works).

If you are a JavaScript developer, you owe it to yourself to check out these videos. Paul Irish is pretty funny, and he is one of the top web developers out there. This combination makes all of his videos a pleasure to watch (and most importantly, to learn from).

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

Writing More Expressive and Readable jQuery Code with Method Chaining

jQuery

jQuery LogoYou can chain jQuery methods in a way that makes your code more readable, and allows you to be more expressive in the way that you traverse and manipulate DOM elements

Most of us are introduced to jQuery via the following scenario: when the user clicks an element, you want something to happen to that element. You Google the code, you copy the code, you edit the code so that it matches your DOM elements, it works, you are hooked, you add “jQuery” to your resume. An oft-told tale.

But, what about when the user clicks an element, and we want numerous thing to happen to elements that are in the neighborhood? Perhaps we want the parent element to turn blue, and then we want the <a> inside of the <span> that is a sibling to change it’s href attribute….etc. Sure, we can do all this using jQuery methods such as parent(), find() and end(). But the code starts to get a little verbose. One way in which we can write this kind of code in a slightly more elegant manner is by chaining method calls together. It makes the code more expressive and a little easier to read.

Example # 1

In example # 1, we query a specific selector, change its background color, use the parent() method to find the element’s parent, and then change the parent element’s background color to red. Pretty simple stuff. But, this code can be written better.

Example # 2 A

Example # 2 B

In example # 2 A, because $(this) returns a jQuery object, we can avoid further queries by simply “chaining” subsequent method calls. Chaining refers to using the return value of one method to kick off another method call, and so on. The concept is like that of a “chain reaction” in that one return value drives the call to the next method, and so on. In example # 2 B, we have the exact same code, but we break each of the “chained” methods calls to a new line, which makes the code even more expressive and easier to follow (comments have been added as well). JavaScript does not care about this white space, so you are free to organize your code in any way you like, which allows you to “express” your thoughts, or “logic” in a way that you feel works best.

This next example is a bit long, but what I wanted to accomplish was:

  • Provide full page markup so that you can copy the entire code, paste it into notepad and run the file, or use jsfiddle.net
  • Create an example where we chain methods together that walk up and then down the DOM, mutating multiple elements, without ever having to create another query

Example # 3

 

In example # 3, we use the jQuery parent(), find(), and end() methods to move up and then back down the DOM, mutating elements along the way, without ever having to write a second query. The next example is the exact same code, but heavily commented, to make it easier to follow-along.

Example # 4

 

In example # 4, we have the exact same code as example # 3, with comments added.

Summary

When a jQuery method returns a jQuery object, you can take advantage of that behavior by “chaning” subsequent method calls to the return value of the previous method. When using this approach, you can execute multiple DOM statements from the result of one query. The end result is code that is more expressive and easier to read.

Helpful links for chaining jQuery methods

http://ejohn.org/blog/ultra-chaining-with-jquery/

http://paulirish.com/2008/sequentially-chain-your-callbacks-in-jquery-two-ways/

http://forum.jquery.com/topic/jquery-method-chaining-returned-object-something-i-don-t-get

http://www.jquery-tutorial.net/introduction/method-chaining/

 

Book Review: Professional JavaScript for Web Developers 2nd Edition

JavaScript

Professional JavaScript for Web Developers 2nd Edition CoverEven at nearly 3 years old, this book is surprisingly relevant and more importantly, it is an excellent resource for Front-End Web Developers

I came across Nicholas C. Zakas’ Professional JavaScript for Web Developers, 2nd Edition recently. As usual, my first instinct was to check the publication date; “hmmmm 2009… I was looking for something a little more current..” I flipped through a few pages, and the next thing I knew, a half-hour had flown by.

This title is an excellent resource for any front-end web developer who is new to JavaScript. While it does cover a few advanced topics such as Object-Oriented JavaScript, it does  a very nice job of discussing the language from the absolute basics, assuming no prior knowledge. Even if you are fairly familiar and comfortable with JavaScript, this book is time well spent. I particularly recommend it for those of you who feel a little out of place without the magic wand that is the jQuery dollar sign ($). Zakas leaves no stone un-turned with regards to native JavaScript DOM traversal and manipulation.

References to “….the new Internet Explorer ver 8…”” and a discussion of up-coming HTML5 features will feel a little out of date, but at the time of publication, the content was more than spot-on.

  • Title: Professional JavaScript for Web Developers, 2nd Edition
  • Author: Nicholas C. Zakas
  • Number of pages: 840
  • Publisher: Wrox
  • Published Date: January 14, 2009(2 edition)
  • Language: English
  • ISBN-10: 047022780X
  • ISBN-13: 978-0470227800

Summary

Professional JavaScript for Web Developers 2nd Edition by Nicholas C. Zakas is an exhaustive and comprehensive education in native JavaScript that is highly recommended. The writing style is easy-going and up-beat, and there is nothing left to the imagination.

Helpful links for Professional JavaScript for Web Developers 2nd Edition

http://www.amazon.com/Professional-JavaScript-Developers-Wrox-Programmer/dp/047022780X

http://www.wrox.com/WileyCDA/WroxTitle/Professional-JavaScript-for-Web-Developers.productCd-047022780X.html

http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118026691.html

 

 

 

 

Lynda.com – An Excellent Resource for Online Web-Development Tutorials

JavaScript

Finally, an affordable and high-quality online training web site that allows Web Developers to learn at their own pace

In the past, whenever I have done a search for online video tutorials, I’ve usually been disappointed by what I found. Microsoft has some pretty good free tutorials, but of course, that covers only Microsoft Technologies, and mostly Microsoft Office, or their software development products. On a number of occasions, I was more than willing to spend money for a web site with tutorials that were well-produced and offered an acceptable menu of topics. Amazingly, I cannot remember too many sites I found that matched this kind of search.

And then, I somehow stumbled across lynda.com.

While I cannot remember how I came across lynda.com, I do remember my reaction after browsing the site for about an hour: I was impressed. The tutorials on lynda.com are well-produced and cover an excellent range of software-related topics.  Unlike some other software-education-related web sites, there are few tutorials that I found to be more than a few years old, and there is a strong focus on providing updated versions of topics that detail the most recent version of a software application.

For front-end web developers, this site is a particularly helpful resource. They offer a solid range of topics from core concepts such as HTML, CSS and JavaScript, to more advanced areas like Photoshp and jQyuery. There is also plenty of back-end web-development technologies covered such as PHP, MySQL and ASP.NET.

Cost: At $37.50 per month, their “Monthly Premium Subscription” is worth its weight in gold. I do not think you can find a more reasonable price for this kind of content.

Recommended Lynda.com tutorials:

HTML

XHTML and HTML Essential Training

Web Accessibility Principles

CSS

CSS Fundamentals

CSS for Developers

JavaScript

JavaScript Essential Training (2011)

Practical and Effective JavaScript

jQuery

jQuery Essential Training

Create an Interactive Photo Gallery with jQuery and Dreamweaver

PHP / MySQL

PHP with MySQL Essential Training

Installing Apache, MySQL, and PHP

PHP with MySQL Beyond the Basics

WordPress

WordPress 3 Essential Training

WordPress 3: Developing Secure Sites

WordPress: Creating Custom Widgets and Plugins with PHP

ASP.NET

ASP.NET Essential Training

Visual Studio 2010 Essential Training

Summary

lynda.com is a web site that has well-produced video tutorials, covering an impressive range of software technologies. While a number of technology profiles are serviced (i.e. designers, coders, business analysts, etc..), both front-end web development and back-end web development technologies are covered well. With regards to the bottom line, the cost of their membership is very reasonable. I am a customer and cannot recommend this product enough. If you are looking to improve your skill set in a software-based technology, there is a good chance that the topic you are looking for is included. You can browse the site and sample all of the videos for free before signing up. This is a no-brainer; lynda.com is an excellent resource for self-managed software training.

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

JavaScript

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

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

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

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

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

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

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

Example # 1

The output for Example # 1 would be:

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

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

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

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

Example # 2

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

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

Summary

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

Helpful links for the JavaScript “for…in” statement

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

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

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

How to return an object literal from a JavaScript constructor

JavaScript

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

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

or…

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

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

Example # 1 – Return a simple object

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

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

Example # 2 – Return an object with a privileged method

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

Finally, we can do the following:

Summary

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

Helpful Links about JavaScript Objects

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

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

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

How to Show the Source Code of Another Web Page, in Your Page, using JavaScript

JavaScript

JavaScript LogoEveryone knows you can view the source code of any web page. But you can also use JavaScript to grab the source code of a different page, and show it in yours

If for some odd reason, you wanted to view the source code of another page without having to actually browse to that page and click “page view source,” you can use JavaScript to do so. In the example below, I use the “window.prompt()” function, to prompt the user for a web page whose source code they would like to see. That function returns the value of the input. We then use the “window.location” method to open up that URL in the browser, but we pre-pend the URL with ‘view-source:’, which achieves the same result as manually browsing to that page, and clicking:  “page view source”.

(Note: As of this writing, this only works in Chrome and FireFox)

As  you can see, the second argument to the window.prompt() method is the default text that we want to appear in the text box. But what if the user accidentally deletes “http://” or simply ignores it, entering something like “google.com”? No problem. We first use the JavaScript  “substring()” method to check to see if the first seven characters of the return value are:  “http://”. If so, great; we just use the return value as is. If it is not, we pre-pend that value with “http://”, and we are all set.

Example # 1:

 

 

 

 

 

 

 

 

Summary

There may not be too many scenarios in which you need to do this, but it is handy to know now. You never know if, down the road, you might need some kind of variation on this functionality.

Helpful Links

http://www.w3schools.com/jsref/obj_location.asp

http://www.w3schools.com/jsref/met_win_prompt.asp

http://www.w3schools.com/jsref/jsref_substring.asp