Replace the indexOf() method to be called on a null value

I have discovered a way to override functions in JavaScript, such as indexOf(), like this:

var indexOf = String.prototype.indexOf;
String.prototype.indexOf = function(){
    //MY CUSTOM CODE HERE
    return indexOf.call(this, arguments);
};

By doing this, I was able to successfully override the indexOf() method called from a string. However, I began to wonder if it is possible to override the indexOf() method that is called from a null value.

For example, can we make null.indexOf("foo") return -1? Sounds mischievous, doesn't it?

Answer №1

Let's assign a value as null,
and another one as 'foobar'.
Then, we will convert null to a string and check if it contains 'foo'.
Next, convert 'foobar' to a string and check if it contains 'foo'. 

If you really need to use indexOf, concatenate null to a string first.

Answer №2

null and undefined do not allow property access using the dot operator, meaning that null.whatever will never work. Therefore, achieving what you are looking for is not possible. For more information, refer to this source.

In addition, most built-in methods, such as indexOf, do not support bindings with null. Hence, ''.indexOf.call(null,...) will also not work.

I understand the reasoning behind your query - having methods on null values can be beneficial in scenarios like "map-invoke" contexts, where:

 source.map(x => x.someMethod())

You may want to return a default value for nulls or undefineds that might appear in the source. Unfortunately, there does not seem to be a concise way of doing this; you will need to implement a safety wrapper for potential nulls:

 source.map(x => invoke(x, func))

Here, invoke could be something similar to

return x === null ? null : func.apply(x)

For example:

let isNull = x => x === null || typeof x === 'undefined';

let invoke = (func, ...args) => x => isNull(x)  ? null : func.apply(x, args);

a = ['foo', 'bar', null, 'bbaazz'];

// z = a.map(x => x.indexOf('a')) // this will fail

z = a.map(invoke(''.indexOf, 'a')); // this works

console.log(z);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Ajax form submission on one specific page

My form submission using JQuery AJAX is causing my page to redirect to submit.php instead of staying on the current page. I have tried various solutions but cannot pinpoint the issue... The PHP script seems to be working fine, with only one echo statement ...

Link Google Map Marker Click Event with Dynamic Binding

I'm currently working on binding a click event to a link that is positioned outside the Google Map Canvas. The goal is to open an "infowindow" on a map marker when this link is clicked. While I know how to achieve this for a specific point, I need a d ...

What is the best way to iterate over my JSON data using JavaScript in order to dynamically generate cards on my HTML page?

var data = [ { "name":"john", "description":"im 22", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c7d7e7f0c2b212d2520622f">[email protected]</a>" }, { "name":"jessie", ...

Using the `on` method of jQuery to make an Ajax request

I'm facing a challenge with using Jquery to load dynamic wall posts for followers. The issue arises when trying to work with dynamic content in the traditional click method. To solve this, I have implemented the on method for the response. However, I ...

Is there a way to resolve the scrolling problem on Google Maps?

When using the Google Maps V3 API, an issue arises where zooming out on the map using the scrollbar also causes the page to scroll along with it. This can be quite frustrating and so far I have not been able to find a way to disable this scrolling behavi ...

Combining arrays using JavaScript

I'm struggling to enhance the following code - it looks a bit messy: Here is my data format: date d1 d2 d3 d4 d5 d6 110522 5 1 3 5 0 7 110523 9 2 4 6 5 9 110524 0 0 0 0 1 0 110525 0 0 3 0 4 0 ... I am importing data from a text file using d3.j ...

Execute the function once the audio has finished loading

I need help running a function once an audio file has finished downloading. This is my JavaScript code: // https://freesound.org/people/jefftbyrd/sounds/486445/ var audioFile = "https://raw.githubusercontent.com/hitoribot/my-room/master/audio/test/test.m ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...

React.map does not retrieve the specific value

I am facing an issue with my list of items. I have implemented it using mui list, and I have also added a button for editing the list. However, when I click on an item, I am getting the value of the last item instead of the one I clicked on. Below is my f ...

The rule 'react-hooks/exhaustive-deps' does not have a defined definition

I received an eslint error message after inserting // eslint-disable-next-line react-hooks/exhaustive-deps into my code. 8:14 error Rule 'react-hooks/exhaustive-deps' definition not found I tried to resolve this issue by referring to this p ...

Use Javascript to create commands and variables specific to the domain or site of a webpage

Currently, I have implemented the code below to fetch the latest tweet. However, I am looking for a way to customize the TWITTERUSERNAME based on the domain where the template is being used. This template is shared across multiple domains. <script type ...

Using JQuery to extract information from a JSON file

Here is the code I am working on, where I pass input username and password values. The function I have written checks if the input matches the data in a JSON file. If there is a match, an alert saying "login correct" will be displayed, otherwise it will di ...

Invoke index functions within a component

I have a widget/component written in Angular 4 within the index.html file. Before and after this angular app, there are various HTML elements due to the nature of it being an additional component for the website. The head section of the index file include ...

When a single object is modified in a JavaScript array, all the elements are affected

I am working with an array of 71 objects: var data = [] This array is populated with data from a database, containing both static and dynamic elements for each object in the data. angular.forEach(returnData,function(value,index) { if(!Array.isArray(va ...

Filtering JSON objects in Vue when the API is only returning a limited number of items

Currently, I am retrieving a JSON Object from an API with a limit of 200. The process involves fetching the initial 200 like this: https://testapi.com/posts.json In our application, we have implemented pagination with 10 posts per page. When we reach pag ...

Retrieve all documents with a matching objectId field in MongoDB

I built an API that can fetch all data from a table, but within this table there is an object ID reference to a user. Table 1 - Story | Table 2 - User api.get('/all_stories', function(req, res) { Story.find({}, function(err, stories) { ...

What is the best way to duplicate an entire webpage with all its content intact?

Is it possible to copy an entire page including images and CSS using Selenium? Traditional methods like ctrl + a or dragging the mouse over the page do not seem to work. How can this be achieved with Selenium without requiring an element to interact with? ...

Unable to retrieve information from v-for as it returns null data

Currently facing an issue with retrieving data from the database using Axios in Vue.js. I am able to see the data in my database through Vue.js developer tools like this: https://i.stack.imgur.com/n7BRO.png However, when attempting to loop through the dat ...

Create and export a global function in your webpack configuration file (webpack.config.js) that can be accessed and utilized

Looking to dive into webpack for the first time. I am interested in exporting a global function, akin to how variables are exported using webpack.EnvironmentPlugin, in order to utilize it in typescript. Experimented with the code snippet below just to und ...

Tips for executing mocha tests using a reporter

Whenever I execute the command npm test, it displays this output: mocha ./tests/ --recursive --reporter mocha-junit-reporter All the tests are executed successfully. However, when I attempt to run mocha with ./tests/flickr/mytest --reporter junit-report ...