jQuery -

.extend()


Introduction to jQuery .extend()

The jQuery .extend() function is a powerful method for merging the contents of two or more objects into the first object. This method is particularly useful for combining settings, creating plugins, and extending objects with new properties. In this tutorial, we will explore the syntax, usage, and best practices for using .extend() with detailed examples.


1. What is jQuery .extend()?

The .extend() method in jQuery allows you to merge the properties of one or more objects into a target object. This method is often used to extend the functionality of objects and to create reusable code components.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>What is .extend() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var obj1 = { name: "John" };
            var obj2 = { age: 30 };
            var extendedObj = $.extend({}, obj1, obj2);
            console.log("Extended Object: ", JSON.stringify(extendedObj));
        });
    </script>
</head>
<body>
</body>
</html>
        
    

In this example, we demonstrate the basic usage of the .extend() method by merging two objects.


2. Syntax of jQuery .extend()

The syntax for the jQuery .extend() method is as follows:

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>.extend() Syntax Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var defaults = {
                name: "Default",
                age: 0
            };
            var options = {
                name: "John"
            };
            var settings = $.extend({}, defaults, options);
            console.log(JSON.stringify(settings));
        });
    </script>
</head>
<body>
</body>
</html>
        
    

This syntax allows you to pass a target object followed by one or more source objects whose properties will be merged into the target object.


3. Merging Objects

You can use $.extend() to merge objects. This is useful for combining multiple settings objects into one.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Merging Objects Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var obj1 = { name: "John", city: "New York" };
            var obj2 = { age: 30, city: "Los Angeles" };
            var mergedObj = $.extend({}, obj1, obj2);
            console.log("Merged Object: ", JSON.stringify(mergedObj));
        });
    </script>
</head>
<body>
</body>
</html>
        
    

In this example, we merge two settings objects into one combined object.


4. Deep Copy with .extend()

The .extend() method can perform a deep copy if the first argument is true. This means that nested objects will also be copied rather than referenced.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Deep Copy Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var obj1 = { name: "John", details: { age: 30, city: "New York" } };
            var obj2 = { details: { age: 40 } };
            var deepCopy = $.extend(true, {}, obj1, obj2);
            console.log("Deep Copy: ", JSON.stringify(deepCopy));
        });
    </script>
</head>
<body>
</body>
</html>
        
    

This example demonstrates how to perform a deep copy using .extend().


5. Extending Default Settings

One common use of .extend() is to extend default settings with user-provided options. This is particularly useful in plugin development.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Extending Default Settings Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var defaults = {
                color: "blue",
                size: "medium"
            };
            var options = {
                color: "red"
            };
            var settings = $.extend({}, defaults, options);
            console.log(JSON.stringify(settings));
        });
    </script>
</head>
<body>
</body>
</html>
        
    

In this example, we extend default settings with user-provided options to customize a plugin.


6. Avoiding Overwrites

The .extend() method will overwrite properties in the target object if they exist in the source object. You can avoid this by carefully controlling the order of the arguments.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Avoiding Overwrites Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var obj1 = { name: "John", age: 30 };
            var obj2 = { age: 25 };
            var result = $.extend(true, {}, obj2, obj1);
            console.log(JSON.stringify(result));
        });
    </script>
</head>
<body>
</body>
</html>
        
    

This example shows how to merge objects without overwriting existing properties.


7. Combining with Other Methods

You can combine .extend() with other jQuery methods to perform complex object manipulations.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Combining with Other jQuery Methods Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $('div').each(function(){
                if ($(this).text().includes('special')) {
                    $(this).css('background-color', 'lightblue').addClass('highlight');
                }
            });
        });
    </script>
</head>
<body>
    <div>Normal Div 1</div>
    <div>Special Div 2</div>
    <div>Normal Div 3</div>
</body>
</html>
        
    

This example demonstrates how to use .extend() along with $.each() to merge and manipulate objects.


8. Best Practices for Using .extend()

When using .extend(), it is important to follow best practices to ensure efficient and maintainable code.


9. Real-World Use Cases

The .extend() method is widely used in real-world applications. Here are a few scenarios where it can be particularly useful:

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Real-World Use Cases Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $('form').each(function(){
                $(this).find('input').each(function(){
                    if ($(this).val() === '') {
                        $(this).css('border', '1px solid red');
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form>
        <input type="text" name="name" placeholder="Name">
        <input type="text" name="email" placeholder="Email">
    </form>
    <form>
        <input type="text" name="name" placeholder="Name">
        <input type="text" name="email" placeholder="Email">
    </form>
</body>
</html>
        
    

In this example, we extend a plugin's default settings with user-provided options.


10. Comparing .extend() with Other Methods

The .extend() method is often compared with other methods like Object.assign() in vanilla JavaScript. While both methods perform similar tasks, .extend() offers additional features such as deep copy and better compatibility with jQuery objects.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Comparing with Other Methods Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var obj1 = { name: "John" };
            var obj2 = { age: 30 };
            var extendedObj = $.extend({}, obj1, obj2);
            var assignedObj = Object.assign({}, obj1, obj2);
            console.log("Extended Object: ", JSON.stringify(extendedObj));
            console.log("Assigned Object: ", JSON.stringify(assignedObj));
        });
    </script>
</head>
<body>
</body>
</html>
        
    

This example compares the usage of .extend() with Object.assign() in different scenarios.


11. Performance Considerations

While using .extend(), it is important to consider performance, especially when dealing with large objects or deep copying.

To maintain performance:

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Performance Considerations Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            // Example with a large array
            let largeArray = new Array(1000000).fill(0).map((_, i) => i);
            console.time("Filtering even numbers");
            let evenNumbers = $.grep(largeArray, function(value){
                return value % 2 === 0;
            });
            console.timeEnd("Filtering even numbers");
            console.log("Number of even numbers: " + evenNumbers.length);
        });
    </script>
</head>
<body>
</body>
</html>
        
    

In this example, we demonstrate how to optimize .extend() for performance.


12. Debugging .extend() Operations

Debugging .extend() operations can be challenging. Here are some tips for effective debugging:

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Debugging .extend() Operations Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var obj1 = { name: "John", age: 30 };
            var obj2 = { age: 40, city: "New York" };
            console.log("Before Extend: ", JSON.stringify(obj1), JSON.stringify(obj2));
            var result = $.extend({}, obj1, obj2);
            console.log("After Extend: ", JSON.stringify(result));
        });
    </script>
</head>
<body>
</body>
</html>
        
    

In this example, we use console logging to debug an .extend() operation.


13. Conclusion

The jQuery .extend() method is a powerful tool for merging objects and extending their properties. By following best practices and considering performance, you can effectively utilize .extend() to simplify and optimize your code.