Creating a prototype function in JavaScript

I am attempting to create a JavaScript prototype function that replicates the Python syntax of 'a' in 'abc'.

The function works correctly in one example, but not in another. Can you help me identify what mistake I made?

String.prototype.in = function(input) {
  return input.indexOf(this) > -1
}

console.log('a'.in('abc'))
// equivalent of 'abc'.indexOf('a') > -1
// true

console.log('a'.in(['a']))
// equivalent of ['a'].indexOf('a') > -1
// false

Answer №1

In the world of Javascript, primitive values like numbers and strings do not have methods attached to them.

When a method is called on a primitive value, it gets converted into its object form, similar to how "boxing" works in languages like Java or C#.

Let's look at a simple example that highlights this difference:

// number primitive
let primitive = 12;
console.log(primitive);
// number object
let object = new Number(12);
console.log(object);

The object forms of primitives generally behave similarly to their primitive counterparts, but there are some differences, such as with equality comparisons:

console.log(12 == 12); // true
console.log(new Number(12) == new Number(12)); // false

// mixed comparisons
console.log(new Number(12) == 12); // true (boxed value will be unboxed)
console.log(new Number(12) === 12); // false (strict equality)

The reason why your second example 'a'.in(['a']) isn't functioning as expected is because Array.prototype.indexOf uses strict equality (===) when checking each element.

The string this is currently in its object form, while the 'a' in the array is in its primitive form, making them not equal.

To make the in() function work properly, you'll need to "unbox" the string value using the Object.prototype.valueOf() method, which returns the primitive value:

String.prototype.in = function(input) {
  return input.indexOf(this.valueOf()) > -1
}

console.log('a'.in('abc')); // true
console.log('a'.in(['a'])); // true

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 triggering ReactJS onClick function accurately

For the function to work correctly, I had to add e.preventDefault(). However, my goal is for it to redirect the user to '/' after submitting the form. Below is the function that I am attempting to trigger: onAddPoints = (e) => { e.prevent ...

Implementing JavaScript to Retrieve and Insert Full HTML Tags into a Textarea

I am currently trying to extract an HTML source code value and insert it into a specific textarea or div upon clicking a button. However, I am encountering issues where I am not receiving the entire HTML tags - it seems to begin with a Meta tag and is remo ...

JavaScript threw an error with message: 'Unexpected identifier' that was not caught

Upon launching Web Developer in Firefox: SyntaxError: missing } after property list note: { was opened at line 7, column 7 ...

The dilemma between installing Electron or installing Electron-Builder: which one

When it comes to installing Electron for an Electron app with React, the method can vary depending on the tutorial. Some tutorials use electron-builder while others do not, but there is little explanation as to why. First: npx create-react-app app cd app ...

I am encountering an issue with the return ( statement and I'm unable to comprehend the reason behind it

import { connect } from 'react-redux' import { Link } from 'react-router-dom' class MyFavoriteStories extends React.Component { markAsFavorite = (e) => { this.setState({ bgColor: "blue" }) } render () { con ...

What could be causing the issue of rows being undefined?

Need help creating a user registration feature with Passport(Local-Signup)? Check out the code snippet below: // config/passport.js // requiring necessary modules var LocalStrategy = require('passport-local').Strategy; // loading the user mode ...

The code inside the if statement is somehow executing even when the if statement is not true

Similar Question: Issue with jQuery function running at inappropriate times I've spent several hours trying to figure out why my function isn't working properly. I have a function inside an if ($window.width() < 1000) statement, but it se ...

Show Pop in relation to modified Text

When the user clicks on the text, a pop-up is displayed after the last word in the text.... https://i.stack.imgur.com/VWQCa.png The logic being used is : left = layer.width + layer.x Code : document.getElementById(lightId).style.left = layer.x + docume ...

Troubleshooting an issue in Chrome with animating the "d" value using Snap.svg

To uncover the issue, try opening in both Chrome and Safari browsers. The logo animation should animate one section at a time like it does in Safari, but in Chrome, the animation seems to freeze. Check out the Snap.svg function responsible for running th ...

How come the item I just inserted into a JavaScript array is showing up as undefined when I try to retrieve it immediately after adding it?

Apologies for the messy code, but I'm facing an issue with my JavaScript. I can't figure out why the specified child is not considered as a task to derive from: var childrenToOperateOn = []; for (var i = 0; i < $scope.der ...

Switch the text display by clicking on a different button in the list

I am currently dealing with an issue involving a list of boxes containing text/images and buttons for expanding/collapsing the text. Whenever I click on another item's button, the text box that was previously opened gets closed, but the button text re ...

Prevent content from occupying unnecessary space below a sticky div

When the "link" on the sticky header is clicked in this scenario, how can I ensure that the linked content item (#mypara) appears below the sticky div rather than directly underneath it where it may be hidden? $(document).ready(function() { $(window ...

Personalize the error message for throwing an exception in JavaScript

I've been working on customizing error messages for exceptions thrown in JavaScript. Despite my best efforts, I have not been successful so far. I'm currently attempting the following code snippet but it's not functioning as expected: f ...

"Learn how to implement a feature that allows for the acceptance of string input in discord

I am struggling to find the right solution for my issue. I am trying to implement a change_nick command but unsure about what type/number option to utilize. This is how I'm creating my command: commands.create ( { ...

The presence of an unauthorized token within the meteor/node module has been detected, specifically related

While following g00glen00b's tutorial on meteor/twitter integration (), I encountered a persistent error. Any assistance or clues would be greatly appreciated. Steps I've Taken Uninstall/reinstall npm Uninstall/reinstall twitter package Uninst ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

VueJS's approach to routing through modular components

I am currently working on a website where I need to set up different category pages using dynamic routes. To achieve this, I am utilizing vue-router and aiming for a single dynamic route that can switch between pages by loading different components. Here ...

Once chosen, zoom in on the map to view the results

I am facing an issue with multiple selects in my code, where one select depends on the result of another. The ultimate goal is to zoom in on the area that has been searched and found, but unfortunately, it is not functioning as expected. If you'd lik ...

Receiving a response from an XMLHttpRequest() within a function

I've come across a situation where I have a function called isOnline(), and here's how it looks: function isOnline() { var request=new XMLHttpRequest(); request.onreadystatechange=function() { if(request.readyState==4) { ...

Error: The 'filename' property of undefined cannot be read when attempting to upload a user profile photo using multer

I am facing an issue while attempting to upload a user profile photo using express.js server and Multer. I keep receiving the error message "TypeError: Cannot read property 'filename' of undefined." Below is the code snippets for both the server- ...