jQuery - Utilities in jQuery
Utilities in jQuery
Utilities are helper functions that jQuery provides to make working with data, arrays, strings, and objects easier. Unlike methods that act directly on elements (like .css() or .hide()), utilities are usually called with a $ (dollar sign) prefix and can be used globally.
1. $.each()
Iterates over arrays or objects.
var colors = ["red", "green", "blue"];
$.each(colors, function(index, value) {
console.log(index + ": " + value);
});
Output:
0: red
1: green
2: blue
2. $.trim()
Removes whitespace from the beginning and end of a string.
var text = " hello world ";
console.log("Before:", text);
console.log("After:", $.trim(text));
Output:
Before: " hello world "
After: "hello world"
3. $.isArray()
Checks if a variable is an array.
var list = [1, 2, 3];
console.log($.isArray(list)); // true
console.log($.isArray("hello")); // false
4. $.isFunction()
Checks if a variable is a function.
function greet() { return "Hi"; }
console.log($.isFunction(greet)); // true
console.log($.isFunction(123)); // false
5. $.inArray()
Finds the index of an item in an array (returns -1 if not found).
var fruits = ["apple", "banana", "cherry"];
console.log($.inArray("banana", fruits)); // 1
console.log($.inArray("mango", fruits)); // -1
6. $.extend()
Merges the contents of two or more objects into the first object.
var obj1 = {a: 1, b: 2};
var obj2 = {b: 3, c: 4};
var result = $.extend({}, obj1, obj2);
console.log(result); // {a: 1, b: 3, c: 4}
7. $.now()
Returns the current timestamp (milliseconds since 1970).
console.log($.now());
Simplified Explanation
-
Utilities = small helper tools in jQuery.
-
They don’t work on elements directly but help you handle arrays, objects, strings, or functions.
-
Examples: loop through arrays (
$.each), clean text ($.trim), check data type ($.isArray,$.isFunction), merge objects ($.extend), or find items in arrays ($.inArray).