What is the extend() method in Underscore.js?

Overview

The extend() method in Underscore.jsUnderscore.js is a Node.js package that manipulates arrays and objects. is used to shallowly copy the properties of one object to another. It does not permanently copy these properties.

Syntax

_.extend(obj1, obj2)
Syntax of the extend() method in Underscore.js

Parameters

  • obj1: This is the object we want to copy the properties of.
  • obj2: This is the object we want to copy the properties of obj1 into.

Return value

The value returned is an object that contains the properties of both obj1 and obj2.

Example

// require underscore
const _ = require("underscore")
// create some objects
let obj1 = {one: 1, two: 2, three: 3, four: 4}
let obj2 = {name: "nodejs", package: "underscore", tag: "_"}
let obj3 = {a: "Apple", b: "Banana"}
let obj4 = {M: "Monday", T: "Tuesday", W: "Wednesday"}
// create other objects
let otherObj1 = {five: 5}
let otherObj2 = {method: "extend"}
let otherObj3 = {c: "Cherry"}
let otherObj4 = {Th: "Thursday"}
// get inverted objects
console.log(_.extend(obj1, otherObj1));
console.log(_.extend(obj2, otherObj2));
console.log(_.extend(obj3, otherObj3));
console.log(_.extend(obj4, otherObj4));

Explanation

  • Line 2: We require the underscore package.
  • Lines 5–8: We create some objects we want to shallowly copy the properties of.
  • Lines 11-–14: We create objects to copy the properties of the other objects we previously created.
  • Lines 17–20: With the extend() method, we shallowly copy the properties of some objects to other ones and print the results to the console.

Free Resources