Function Declaration in jQuery

Three ways to declare functions in jQuery include the simple function, get/set, and extending the jQuery object. I cover all three in this short post.

Three ways to declare functions in jQuery include the simple function, get/set, and extending the jQuery object. I cover all three in this short post.

The Simple Function

This is the simplest way to declare a function (method) in JavaScript and jQuery. This is a great way to test and is good for a throwaway method, but it isn’t good practice to code like this because it doesn’t encourage code recycling.

function sayHello(name) {
  alert("Hello, " + name);
}

Get/Set

This is a great way to get/set/delete model values. It’s very common and is not too far off from the simple method declaration.

//declaring
var sayHello = function(name) {
    return "Hello, " + name;
}
//using
console.log(sayHello("Jon")); // "Hello, Jon"

Create Your Own

Extending the jQuery object is a great way to abstract pieces of code that will be reused. It encourages developers to use method chaining, so this keeps your code clean, too!

jQuery.fn.extend({
  backwards: function() {
    var text = $(this).text();
    var backwardsText = '';
    var bits = text.split('');
    var x = text.length - 1;
    while (x >= 0) {
      backwardsText += bits[x];
      --x;
    }
    return backwardsText;
  }
})
$(document).ready(function() {
  console.log($("#testText").backwards());
  //given $("#testText") looks like <p id='testText'>racecar tacocat</p>
  //the result is => tacocat racecar
})

Here’s a CodePen that uses the above method (plus another one) to determine if an element’s text forms a palindrome:

See the Pen Extending the jQuery Object by Nate Northway (@the_Northway) on CodePen.

Leave a Reply

Your email address will not be published. Required fields are marked *