Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the input from prototype if false

Tags:

javascript

I'm trying to return the string that called the function.

But it doesn't return the string… it returns an array.

String.prototype.testing = function testing() {
  if (this === "what") {}
  return this //Should return - this is a string
}


x = "this is a string"

y = x.testing()

console.log(y)
like image 258
Allen Marshall Avatar asked Dec 14 '25 17:12

Allen Marshall


1 Answers

JavaScript has both String objects and string primitives. In a String.prototype method in loose mode, this is a string object. (In strict mode, it's whatever the method was called on, which is frequently a string primitive.) What you're seeing from console.log isn't an array, it's just how that particular console implementation outputs a String object rather than string primitive:

console.log(new String("hi"));

There is a bug in the code, though: this === "what" will never be true in loose mode, because "what" is a string primitive, but this is a String object, and === isn't allowed to coerce. You'd want this.toString() === "what" or this == "what". You'd probably also want to do something in the block attached to the if. And if you want to return a string primitive when returning this, you might want return this.toString(); at the end.

E.g., something like:

String.prototype.testing = function testing() {
  if (this == "what") {
    return "it was what";
  }
  return this.toString();
};

var x = "this is a string";
var y = x.testing();
console.log(y);
x = "what";
y = x.testing();
console.log(y);

Or using strict mode, something like this:

"use strict";
String.prototype.testing = function testing() {
  if (this == "what") { // Could still be either a primitive or object, depending
    return "it was what";
  }
  return this; // No need for toString here
};

var x = "this is a string";
var y = x.testing();
console.log(y);
x = "what";
y = x.testing();
console.log(y);
like image 198
T.J. Crowder Avatar answered Dec 16 '25 06:12

T.J. Crowder