How to return the input from prototype if false

Viewed 45

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)

2 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);

You have a ... not a bug but there is no need to add a function name when you assign it, here:

String.prototype.testing = function **testing**() {}

There is not necessarily something wrong with your code but you are not seeing what you expect :)

Fo example with what you have x == x.testing() even if console.log(x) looks different than console.log(x.testing()).

They are equal but different in type, one is a string object other is a string primitive, as T. J. nicely explained while I was posting :).

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


    x = "this is a string"

    y = x.testing()

    console.log(y)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related