Javascript Functions I didn’t know existed

Javascript Functions I didn’t know existed

We've all been there where we come across a function in Javascript we never knew existed. We will look for some workaround in StackOverflow and get the job done. I have nothing against StackOverflow, I think it has tremendously improved software development all across the world. But it definitely has reduced the way developers interact with documentation. Day by day, the interest in digging deep inside any sort of documentation has definitely been minimized.

I have had multiple instances where I have come across functions that I have never seen before but had helped me get the job done. In this article, we will see 10 of those and see how they can be useful. Let me preface this by saying that you might never use some of these but there's no harm in knowing them.

1. String.prototype.startsWith()

StartsWith() is a String method that will find whether a string starts with the characters you passed as parameters and returns true or false accordingly. You could also, pass the index as the second parameter where you want the function to start checking. If the index is not provided, then the function will start checking from 0.

const str1 = 'Sample String';

console.log(str1.startsWith('Sam'));
// expected output: true

console.log(str1.startsWith('Sam', 7));
// expected output: false

2. Object.isFrozen()

Object.freeze() is a well-known method to freeze an object. In case you are not aware, the freeze method will ensure that the object which is frozen can no longer be modified. But if you want to check whether a particular object has been frozen or not, then you can use the Object.isFrozen() method. Let's see this in action.

const customer = {
  name: "Jason"
};

console.log(Object.isFrozen(customer));
// expected output: false

Object.freeze(customer);

console.log(Object.isFrozen(customer));
// expected output: true

3. Object.seal()

Object.seal() is another great method that lets you prevent new properties from being added to an object. This doesn't mean that you cannot change values which you still can. The existing properties are not configurable. This method is useful because objects are generally extensible and if you don't want any properties to be added to the object.

const customer = {
  age: 42
};

Object.seal(customer);
customer.age = 29;
console.log(customer.age);
// expected output: 29

delete customer.age; 
console.log(customer.age);
// expected output: 29

4. Object.preventExtensions()

This works similar to Object.seal() as well. The Object.preventExtensions() method will prevent any new properties from ever being added to a particular object since Objects are generally extensible.

const customer= {};

Object.preventExtensions(customer);

try {
  Object.defineProperty(customer, 'name', {
    value: 'Jason'  });
} catch (e) {
  console.log(e);
  // expected output: TypeError: Cannot define property name, object is not extensible
}

5. Array.prototype.copyWithin()

copyWithin() will do a shallow copies of an array to another location in the same array and will return the same array without making a duplicate.

const array1 = ['a', 'b', 'c', 'd', 'e'];

// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]

// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]

6. Array.prototype.values()

In JavaScript, an iterator is an object which defines a sequence and potentially a return value upon its termination. The Array values() methods will return a new Array Iterator object which contains every element of the array with its index.

const numbers = ['1', '2', '3', '4', '5'];
const iterator = numbers.values();

for (const value of iterator) {
  console.log(value);
}

// expected output: "1"
// expected output: "2"
// expected output: "3"
// expected output: "4"
// expected output: "5"

7. globalThis

The global object can be accessed from anywhere in the application despite which block you are accessing it from. See the example below to understand this better.

function canMakeHTTPRequest() {
  return typeof globalThis.XMLHttpRequest === 'function';
}

console.log(canMakeHTTPRequest());

The globalThis works differently when it's in the browser, web worker, or even the node js environment.

8. RegExp.prototype.dotAll()

The dotAll property of RegExp object will indicate whether or not the "s" flag is used with the regular expression. dotAll is a read-only property of an individual regular expression instance.

const regex1 = new RegExp('foo', 's');

console.log(regex1.dotAll);
// expected output: true

const regex2 = new RegExp('bar');

console.log(regex2.dotAll);
// expected output: false

9. Date.prototype.toJSON()

The toJSON() method returns a string representation of the Date object. If you have ever worked with a REST API, then you know how useful this can be.

const event = new Date('August 19, 1975 23:15:30 UTC');

const jsonDate = event.toJSON();

console.log(jsonDate);
// expected output: 1975-08-19T23:15:30.000Z

console.log(new Date(jsonDate).toUTCString());
// expected output: Tue, 19 Aug 1975 23:15:30 GMT

10. Date.parse()

The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values.

const unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
const javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');

console.log(unixTimeZero);
// expected output: 0

console.log(javaScriptRelease);
// expected output: 818035920000

Since we used libraries like Moment, we often choose not to delve into the particulars of the Date Object but it's needless to say that you might not need to use somebody else's code to work with dates and times.

That's about it. I'm sure there are so many more functions that I don't know yet and could definitely be added to this list. If I come across another 10 of them, I'l be sure to write a follow up post.