jQuery: $.type()

This post covers all about jQuery’s .type() method. You will learn what it does, see its’ usage examples and understand the difference between jQuery’s .type() and JavaScripts’ typeof operator.

Without further ado, let’s find an answer to the following question.

What does $.type() do?

jQuery.type() method returns internal JavaScript class name of the passed argument.

jQuery.type(1)       // "number"
jQuery.type("foo")   // "string"
$.type(true)         // "boolean"
$.type(undefined)    // "undefined"
$.type(function(){}) // "function"
$.type(new Date())   // "date"
$.type(/test/)       // "regexp"
$.type(null)         // "null"

You might argue, why should I use jQuery .type() function when JavaScript already has native typeof operator that does just that. Well, you are in luck. In our previous post I explained why JavaScript’s typeof operator fails in what it’s supposed to do and excels in something else. Take the time and read the article.

When would you need it?

The method is very handy when writing a jQuery plugin or a function that can receive different type of arguments (e.g. $.css(Array or String)) or take optional parameters (e.g. $.click([eventData], function)).

In the case of $.click() method above:

/* You can either check:
  - eventData's type
  - fn === undefined
*/
click: function(eventData, fn){

    if($.type(fn) === "undefined"){
      fn = eventData;
      eventData = {default: "value"};
    }

}

Notes and Caveats

I would like to leave you with some notes on $.type() method:

  • as of jQuery 1.9 $.type(new Error()) will return "error"
  • if the argument type is not one of the list below, method will return "object":
    • Boolean
    • Number
    • String
    • Function
    • Array
    • Date
    • RegExp
    • Object
    • Error

One doesn't simply drop support for oldIE

This weeks humor post is about dropping IE 6, 7 and 8 support in the next jQuery 2.0 version.

One of the advantages of using jQuery is to get on with your app logic and not worry about the cross-browser scripting issues. I don't think anyone would trade their website's IE support for a digit in their jquery.js file. Would you?

One does not simply drop support for oldIE

JavaScript: typeof & when should you use it?

In this post, we will talk about JavaScript’s typeof operator. We will start with its’ purpose. Then discuss its’ flaws and finally see when should you use it.

typeof's usage doesn’t happen to match its’ initial purpose.

What is typeof?

The typeof operator is used to identify the type of an object. It always returns a String value, so you should always compare return value to a string.

// Examples
typeof 37;        // "number";
typeof true;      // "boolean"
typeof undefined; // "undefined"
typeof {};        // "object"

// Call with parentheses
typeof(37);        // "number";

As you can see above, there are 2 ways to call the method. typeof is an operand and not a function, that is why, the second method is actually not a function call. Operation in parentheses are evaluated and then passed to typeof.

So far, so good, we know its’ purpose. Now let’s see its’ flaws.

Flaws and caveats

I’ll just say it: typeof is one of the biggest flaws in JavaScript. It had only one job, to return the type of an object. But let’s see the table below (source):

Value               Class      Type
-------------------------------------
"foo"               String     string
new String("foo")   String     object
1.2                 Number     number
new Number(1.2)     Number     object
true                Boolean    boolean
new Boolean(true)   Boolean    object
new Date()          Date       object
new Error()         Error      object
[1,2,3]             Array      object
new Array(1, 2, 3)  Array      object
new Function("")    Function   function
/abc/g              RegExp     object   (function in Nitro/V8)
new RegExp("meow")  RegExp     object   (function in Nitro/V8)
{}                  Object     object
new Object()        Object     object
alert               Function   function (object in IE 6, 7, 8)
null                null       object   (in future ECMAScript versions)

"Type" column lists the typeof‘s return values and "Class" column shows the actual class of the operand.

As you can see, in most of the case you end up with object string instead of the actual class name. A workaround for getting the class of an object is to use Object.prototype.toString method. Here is how:

Object.prototype.toString.call("foo")      // [object string]
Object.prototype.toString.call(new String) // [object string]

As you can see, this is not the ideal return value. Here is a JavaScript function that would help make your code more readable (source):

function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

is('String', 'test');             // true
is('String', new String('test')); // true

If you want to check the type of an object, use Object.prototype.toString method instead of typeof operator. This would make your code behave as expected.

NOTE:
ECMAScript 5 changes the Object.prototype.toString method’s return values for null and undefined from object to null and undefined.

When should you use typeof?

typeof is good for checking if variables are undefined. If you make use of an undefined variable in your code, you will get a ReferenceError. Using typeof will not cause your code to throw an error.

if( typeof foo !== "undefined") {
    // defined
}else {
    // undefined
}

To conclude, unless you are checking whether a variable is defined or not, you should avoid using typeof.

ReferenceError: $ is not defined

This post will explain the root cause of the Reference Error in your browser’s console log. Also, list most common cases with examples and solutions. Without any further ado, lets see what a reference error is.

This is a common JavaScript error that says: you are trying to access a variable or call a function that has not been defined yet.

Reproducing the error:

// VARIABLES
foo; // ReferenceError: foo is not defined
var foo;
foo; // No more errors

// FUNCTIONS
bar(); // ReferenceError: bar is not defined
bar = function(){};
bar() // No errors

By now, you might have guessed the reason behind the "ReferenceError: $ is not defined" error. It is exactly the same as the bar() example above, but the name of the function is $ instead of bar this time. So, what it means is that we are trying to access the method $ that has not been defined yet. When is it possible? Only when jquery.js file has not been loaded successfully before we tried to call $().

Some common cases when error may occur

  1. Problem: Path to your jquery.js file is broken and it can not be found (Error 404).

    <script src="/wrong/path-to/jquery.min.js"></script>

    Solution: fix your path to jquery.js file. If your project is a public website, you better use Google hosted jQuery file.

    <script src="/correct/path-to/jquery.min.js"></script>
  2. Problem: jQuery plugin is included before jQuery file.

    <script src="/path-to/jquery.plugin.js"></script>
    <script src="/path-to/jquery.min.js"></script>

    Solution: Include jquery.js file before any jQuery plugin files.

    <script src="/path-to/jquery.min.js"></script>
    <script src="/path-to/jquery.plugin.js"></script>
  3. Problem: You are including jQuery file without the protocol in the URL and accessing the page from your local file system.

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

    Solution: Temporarily add HTTP protocol (http:// instead of //) in the URL while you are developing.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
  4. Problem: jQuery file is included from the web, but you don't have an internet connection. It is a silly mistake, but you would be surprised how ofter it happens.

    <script src="http://www.example.com/js/jquery.min.js"></script>

    Solution: Include local jquery.js file copy or connect to the internet :)

    <script src="/js/jquery.min.js"></script>

If the above cases do not solve your case, try to figure out why jQuery is not loaded before the line where this error is thrown.

jQuery: Test/check if checkbox is checked

Testing if certain checkbox is checked using jQuery is pretty simple task. But I, just like many other developers, keep forgetting the exact syntax. So I decided to carry on a little research on the subject and gather all related information including small caveats and write this article for the future reference.

This post covers 4 methods to check if checkbox is checked. All methods especially do the same thing: test if checkbox has checked property set. But depending on the version of jQuery you are using, the methods may vary. Lets consider we have the document setup below and see how to test checkbox checked using different versions of jQuery.

<input id="checkbox"  type="checkbox" name="one" value="1" checked="checked">
<input id="checkbox2" type="checkbox" name="two" value="2">
<input id="checkbox3" type="checkbox" name="thr" value="3">

Using jQuery version 1.6 or newer

As I mentioned above, we need to check the checked property of an element and correct way of doing it is to use .prop() method. So if other methods do not add any value to your code’s readability, please use the first method below.

// First method - Recommended
$('#checkbox').prop('checked')  // Boolean true

// Second method - Makes code more readable (e.g. in if statements)
$('#checkbox').is(':checked')  // Boolean true

// Third method - Selecting the checkbox & filtering by :checked selector
$('#checkbox:checked').length  // Integer >0
$('#checkbox:checked').size()  // .size() can be used instead of .length

// Fourth method - Getting DOM object reference
$('#checkbox').get(0).checked  // Boolean true
$('#checkbox')[0].checked      // Boolean true (same as above)

Earlier version of jQuery (up to v1.5)

jQuery version 1.6 introduced .prop() method to get HTML/DOM element’s property instead of an attribute. Prior to version 1.6 we had to use .attr() method instead. Read more about the difference between .prop() and .attr().

// First method - Recommended
$('#checkbox').attr('checked')  // Boolean true

// Second, Third & Fourth methods – The same as for version 1.6. See above.

Caveats & problems

What if your jQuery selector has a set of more than one checkbox? This is how the methods above will behave?

Case 1:
<input class="check" type="checkbox" name="one" checked="checked">
<input class="check" type="checkbox" name="two">

Case 2:
<input class="check" type="checkbox" name="two">
<input class="check" type="checkbox" name="one" checked="checked">
// Case 1:
$('#checkbox').prop('checked') // true
$('#checkbox').is(':checked')  // true
$('#checkbox:checked').length  // 1
$('#checkbox')[0].checked      // true

// Case 2:
$('#checkbox').prop('checked') // false
$('#checkbox').is(':checked')  // true
$('#checkbox:checked').length  // 1
$('#checkbox')[0].checked      // false

jQuery attribute selector $('elem[name]') does not return updated property value. So use other methods instead.

$('#checkbox[checked]').length;        // Integer 1
$('#checkbox').prop('checked', false); // Uncheck the checkbox
$('#checkbox[checked]').length;        // Still returns 1, not 0

Select all checked checkboxes on the page or within a container.

$("input[type=checkbox][checked]"); // All checkboxes in the document that are checked

This is all I could find on the subject. Please bookmark or share the article so that it is easier to find it later.