Skip to content

Global Methods

Biswajit Sundara edited this page May 1, 2023 · 2 revisions

ES6 introduced several new global methods that can be used in JavaScript:

  1. Object.assign(): This method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It returns the target object.
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const obj3 = { c: 3 };
const result = Object.assign(obj1, obj2, obj3);
console.log(result); // { a: 1, b: 2, c: 3 }
  1. Array.from(): This method creates a new, shallow-copied array instance from an array-like or iterable object.
const str = "hello";
const arr = Array.from(str);
console.log(arr); // ["h", "e", "l", "l", "o"]
  1. Array.of(): This method creates a new array instance with a variable number of arguments.
const arr = Array.of(1, 2, 3);
console.log(arr); // [1, 2, 3]
  1. Array.prototype.fill(): This method fills all the elements of an array from a start index to an end index with a static value.
const arr = [1, 2, 3, 4];
arr.fill(0, 1, 3);
console.log(arr); // [1, 0, 0, 4]
  1. Array.prototype.find(): This method returns the value of the first element in the array that satisfies the provided testing function.
const arr = [1, 2, 3, 4];
const result = arr.find((element) => element > 2);
console.log(result); // 3
  1. Array.prototype.findIndex(): This method returns the index of the first element in the array that satisfies the provided testing function. If no elements pass the test, it returns -1.
const arr = [1, 2, 3, 4];
const result = arr.findIndex((element) => element > 2);
console.log(result); // 2
  1. Math.trunc(): This method returns the integer part of a number by removing any fractional digits.
const num = 3.14;
const result = Math.trunc(num);
console.log(result); // 3
  1. Number.isNaN(): This method determines whether a value is NaN (Not-A-Number).
const num = NaN;
const result = Number.isNaN(num);
console.log(result); // true
  1. Number.isFinite(): This method determines whether a value is a finite number.
const num = 5;
const result = Number.isFinite(num);
console.log(result); // true
  1. String.prototype.includes(): This method determines whether one string may be found within another string, returning true or false as appropriate.
const str = "hello world";
const result = str.includes("world");
console.log(result); // true

Clone this wiki locally