jQuery Utility Methods
The jQuery utility methods are functions which start with $. and do not work on selected elements. They help with objects, arrays and strings.
<p>Page</p>
$.extend(): merge objects
$.extend() copies the properties of one or more objects into the first object. It is often used for default options.
var defaults = { color: 'red', size: 10, show: true };
var options = { size: 20 };
var settings = $.extend({}, defaults, options);
console.log(settings);
console.log(defaults);
{ color: 'red', size: 20, show: true }
{ color: 'red', size: 10, show: true }
We use an empty object {} as the first argument, so the defaults object is not changed.
Deep copy with $.extend(true, …)
var a = { name: 'A', info: { city: 'Delhi' } };
var shallow = $.extend({}, a);
var deep = $.extend(true, {}, a);
a.info.city = 'Pune';
console.log('shallow copy city: ' + shallow.info.city);
console.log('deep copy city: ' + deep.info.city);
shallow copy city: Pune
deep copy city: Delhi
A normal (shallow) copy shares the inner object. The deep copy (first argument true) makes a complete separate copy.
$.param(): make a query string
console.log($.param({ name: 'Anita Rao', age: 25, tags: ['a', 'b'] }));
console.log(decodeURIComponent($.param({ name: 'Anita Rao', tags: ['a', 'b'] })));
name=Anita%20Rao&age=25&tags%5B%5D=a&tags%5B%5D=b
name=Anita Rao&tags[]=a&tags[]=b
$.inArray(), $.grep() and $.merge()
var list = ['a', 'b', 'c'];
console.log($.inArray('b', list));
console.log($.inArray('z', list));
console.log($.merge([1, 2], [3, 4]));
console.log($.grep([1, 2, 3, 4, 5], function (n) { return n > 2; }));
1
-1
[ 1, 2, 3, 4 ]
[ 3, 4, 5 ]
$.inArray() returns the index, and -1 if the value is not found. In new code you can write list.includes('b') or list.indexOf('b').
Checking things
console.log($.isEmptyObject({}));
console.log($.isEmptyObject({ a: 1 }));
console.log($.isPlainObject({ a: 1 }));
console.log($.isPlainObject([1, 2]));
true
false
true
false
$.makeArray()
<ul><li>A</li><li>B</li></ul>
var arr = $.makeArray($('li'));
console.log(Array.isArray(arr));
console.log(arr.length);
true
2
Utility methods removed in jQuery 4
Many old helper functions were removed in jQuery 4.0, because JavaScript now has the same thing built in. Use the native versions, and your code works in both jQuery 3 and 4.
| Old jQuery method | Use this instead |
|---|---|
$.trim(text) | text.trim() |
$.isArray(x) | Array.isArray(x) |
$.isFunction(x) | typeof x === 'function' |
$.isNumeric(x) | !isNaN(parseFloat(x)) && isFinite(x) |
$.parseJSON(text) | JSON.parse(text) |
$.now() | Date.now() |
$.type(x) | typeof x, Array.isArray() |
$.nodeName(el, 'li') | el.nodeName.toLowerCase() === 'li' |
More in jQuery 4 and Upgrading.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |