$.each() in jquery
The $.each() function in jQuery is a versatile utility that allows you to iterate over arrays and objects. It executes a function for each element in the collection, making it useful for tasks like manipulating or accessing data within arrays or objects.
Syntax
For Arrays:
$.each(array, function(index, value) {
// Code to execute for each element
});
For Objects:
$.each(object, function(key, value) {
// Code to execute for each property
});
Parameters
- array/object: The array or object to iterate over.
- function(index/key, value): A callback function that is executed for each element or property.
- index/key: The index (for arrays) or key (for objects) of the current element or property.
- value: The value of the current element or property.
Return Value
$.each()always returns the original collection, which allows for chaining.
Examples
Iterating Over an Array
var fruits = ['apple', 'banana', 'cherry'];
$.each(fruits, function(index, value) {
console.log(index + ': ' + value);
});
Output:
0: apple
1: banana
2: cherry
Iterating Over an Object
var person = {
name: 'John',
age: 30,
city: 'New York'
};
$.each(person, function(key, value) {
console.log(key + ': ' + value);
});
Output:
name: John
age: 30
city: New York
Key Points
- Order of Iteration: For arrays,
$.each()iterates from index 0 to the end. For objects, it iterates over the properties in an arbitrary order. - Modification: You can modify the elements or properties directly within the callback function.
- Early Exit: To stop iteration early, you can return
falsefrom the callback function.
$.each(fruits, function(index, value) {
if (value === 'banana') {
return false; // Stops the iteration
}
console.log(index + ': ' + value);
});
Output:
0: apple
1: banana
The $.each() function is a powerful tool in jQuery for handling collections of data and is particularly useful for working with dynamic content.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
