In JavaScript there is such a thing called a prototype chain, which is essentially a way of creating objects where all of their children share the same methods.
In this example you are modifying the prototype of the String class in JavaScript. By doing so, you are giving this new method to each and every string that is created within this scope of your document.
Using only this does not work because this is a String object which sort of acts just like it is in reality, being an Array of characters. By using JSON.stringify you are changing the value of this to an actual string, thus allowing you to compare it to a version with the method toUpperCase() applied to it.
So the str variable that i assigned is a prototype of String after i did this “str.isUpperCase()” ?
When i console log “this”. it shows --> [String: ‘C’]
so basically the characters are in an array as you said and i tried this[0] but it only gives first character. i want the whole string so i guess JSON.stringify works since it turns the array into a whole string of the characters inside it.
You are correct to ensure its not the object wrapper, but
don’t use JSON.stringify unless it’s actually necessary, toString is fine. Or == instead of ===, which will perform the coercion automatically but it’s less obvious what is happening:
if (this == this.toUppercase()) {
Or
if (this.toString() === this.toUppercase()) {
Also, strings are not arrays of characters (thank god!), JS is not C
Sort of, it will do some conversion/coercion. You need to understand the rules surrounding it though: as a rule never use ==, always use === because if you don’t understand the difference it will cause errors in your code.
Also it’s not an array. For a fractionally small amount of time, strings get wrapped in objects when string methods are used (as in this case), you almost never ever have to think about it.
I dunno why my testing pushed me into using the JSON.stringify method. For some reason I wasn’t able to get true without it. I updated the code to reflect the change though.
I was up a bit late though maybe I was just super tired lol!
i get that strings are wrapped in objects when string methods are used. but if it isn’t an array then what is it? it shows as an array when no methods in used.
What specific thing are you talking about here? Because a string will be a string if no methods are used, not an array, only an array will show as an array.
when i console log “this”. it shows as an array. it shows ----> [String: “C”]
edit: also would u be so kind to help me out on “a string of sorts” that i just posted? i really need help on that… maybe u can tell the difference because i can’t