jQuery Utility Methods are helper functions provided by jQuery that simplify common JavaScript tasks such as array manipulation, object handling, type checking, and iteration. These methods are not tied to DOM elements and can be used independently.
$.methodName() syntaxUtility methods are static functions of the jQuery object. They do not require a selector.
General Syntax
// General syntax of a jQuery utility method
$.methodName(parameters);
// Loop through array values using $.each
var numbers = [10, 20, 30];
$.each(numbers, function(index, value) {
console.log(index + " : " + value);
});
// Detect the data type of a variable
var data = [];
console.log($.type(data));
// Check whether a variable is an array
var fruits = ["Apple", "Banana"];
console.log($.isArray(fruits));
// Remove extra spaces from a string
var text = " jQuery Utility ";
console.log($.trim(text));
$.each() iterates over arrays or objects.
$.type() gives a reliable data type.
$.isArray() checks if a value is an array.
$.trim() removes leading and trailing spaces.
Type something with extra spaces and see the utility methods in action!
// Demonstrate multiple jQuery utility methods together
function runUtility() {
var input = $("#userInput").val();
var items = [input, 123, ["a", "b"]];
var htmlResult = "";
$.each(items, function(i, value) {
var type = $.type(value);
var displayVal = (type === "string") ? "'" + $.trim(value) + "' (trimmed)" : JSON.stringify(value);
htmlResult += "Item " + i + ": " + displayVal + " | Type: " + type + "<br>";
});
$("#utilityOutput").html(htmlResult);
}
$.each() over traditional loops for readability$.each()$.type()