Can you override the truthy coercion of a JavaScript Object? The Next CEO of Stack OverflowLength of a JavaScript objectWhat is the most efficient way to deep clone an object in JavaScript?How can I merge properties of two JavaScript objects dynamically?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I check if an array includes an object in JavaScript?How do I test for an empty JavaScript object?How do I correctly clone a JavaScript object?How can I get query string values in JavaScript?Checking if a key exists in a JavaScript object?

How dangerous is XSS

How seriously should I take size and weight limits of hand luggage?

Calculate the Mean mean of two numbers

Identify and count spells (Distinctive events within each group)

Is it OK to decorate a log book cover?

"Eavesdropping" vs "Listen in on"

How should I connect my cat5 cable to connectors having an orange-green line?

Compensation for working overtime on Saturdays

Another proof that dividing by 0 does not exist -- is it right?

Is this a new Fibonacci Identity?

Gödel's incompleteness theorems - what are the religious implications?

Are British MPs missing the point, with these 'Indicative Votes'?

Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact

MT "will strike" & LXX "will watch carefully" (Gen 3:15)?

Can Sri Krishna be called 'a person'?

Why was Sir Cadogan fired?

Planeswalker Ability and Death Timing

Is a linearly independent set whose span is dense a Schauder basis?

How to pronounce fünf in 45

logical reads on global temp table, but not on session-level temp table

Calculating discount not working

Can I hook these wires up to find the connection to a dead outlet?

Man transported from Alternate World into ours by a Neutrino Detector

Why did the Drakh emissary look so blurred in S04:E11 "Lines of Communication"?



Can you override the truthy coercion of a JavaScript Object?



The Next CEO of Stack OverflowLength of a JavaScript objectWhat is the most efficient way to deep clone an object in JavaScript?How can I merge properties of two JavaScript objects dynamically?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I check if an array includes an object in JavaScript?How do I test for an empty JavaScript object?How do I correctly clone a JavaScript object?How can I get query string values in JavaScript?Checking if a key exists in a JavaScript object?










4















The string coercion can be overwritten using the toString function.



The number coercion can be overwritten using the valueOf function.



The boolean coercion can be also overwritten using the valueOf function.






var foo = 
toString: function()
console.log("To String");
return "bar";
,
valueOf: function()
console.log("Value Of");
return 5;

;

console.log(`$foo`);
console.log(+foo);
console.log(foo == true);
console.log(!!foo);





I haven't been able to find a function that gets called for when an object needs to get converted to a truthy. Since x == true and !!x have different behaviors, then I am guessing that there is no function that changes that. I instead tried extending types whose truthy is false but the only value that gets accepted by Object.create is null which is almost identical to an object literal (has none of the Object.prototype properties).










share|improve this question
























  • The short answer is JavaScript does not have actual operator overloading, so there is no way to modify certain behaviors in the language specification since it's essentially a hardcoded behavior. One such example is the negation operator.

    – Patrick Roberts
    Mar 8 at 19:40











  • you might be able to alter the way a window property coerces, but not the actual object.

    – dandavis
    Mar 8 at 19:43















4















The string coercion can be overwritten using the toString function.



The number coercion can be overwritten using the valueOf function.



The boolean coercion can be also overwritten using the valueOf function.






var foo = 
toString: function()
console.log("To String");
return "bar";
,
valueOf: function()
console.log("Value Of");
return 5;

;

console.log(`$foo`);
console.log(+foo);
console.log(foo == true);
console.log(!!foo);





I haven't been able to find a function that gets called for when an object needs to get converted to a truthy. Since x == true and !!x have different behaviors, then I am guessing that there is no function that changes that. I instead tried extending types whose truthy is false but the only value that gets accepted by Object.create is null which is almost identical to an object literal (has none of the Object.prototype properties).










share|improve this question
























  • The short answer is JavaScript does not have actual operator overloading, so there is no way to modify certain behaviors in the language specification since it's essentially a hardcoded behavior. One such example is the negation operator.

    – Patrick Roberts
    Mar 8 at 19:40











  • you might be able to alter the way a window property coerces, but not the actual object.

    – dandavis
    Mar 8 at 19:43













4












4








4


1






The string coercion can be overwritten using the toString function.



The number coercion can be overwritten using the valueOf function.



The boolean coercion can be also overwritten using the valueOf function.






var foo = 
toString: function()
console.log("To String");
return "bar";
,
valueOf: function()
console.log("Value Of");
return 5;

;

console.log(`$foo`);
console.log(+foo);
console.log(foo == true);
console.log(!!foo);





I haven't been able to find a function that gets called for when an object needs to get converted to a truthy. Since x == true and !!x have different behaviors, then I am guessing that there is no function that changes that. I instead tried extending types whose truthy is false but the only value that gets accepted by Object.create is null which is almost identical to an object literal (has none of the Object.prototype properties).










share|improve this question
















The string coercion can be overwritten using the toString function.



The number coercion can be overwritten using the valueOf function.



The boolean coercion can be also overwritten using the valueOf function.






var foo = 
toString: function()
console.log("To String");
return "bar";
,
valueOf: function()
console.log("Value Of");
return 5;

;

console.log(`$foo`);
console.log(+foo);
console.log(foo == true);
console.log(!!foo);





I haven't been able to find a function that gets called for when an object needs to get converted to a truthy. Since x == true and !!x have different behaviors, then I am guessing that there is no function that changes that. I instead tried extending types whose truthy is false but the only value that gets accepted by Object.create is null which is almost identical to an object literal (has none of the Object.prototype properties).






var foo = 
toString: function()
console.log("To String");
return "bar";
,
valueOf: function()
console.log("Value Of");
return 5;

;

console.log(`$foo`);
console.log(+foo);
console.log(foo == true);
console.log(!!foo);





var foo = 
toString: function()
console.log("To String");
return "bar";
,
valueOf: function()
console.log("Value Of");
return 5;

;

console.log(`$foo`);
console.log(+foo);
console.log(foo == true);
console.log(!!foo);






javascript object coercion






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 19:37







nick zoum

















asked Mar 8 at 19:33









nick zoumnick zoum

2,58611539




2,58611539












  • The short answer is JavaScript does not have actual operator overloading, so there is no way to modify certain behaviors in the language specification since it's essentially a hardcoded behavior. One such example is the negation operator.

    – Patrick Roberts
    Mar 8 at 19:40











  • you might be able to alter the way a window property coerces, but not the actual object.

    – dandavis
    Mar 8 at 19:43

















  • The short answer is JavaScript does not have actual operator overloading, so there is no way to modify certain behaviors in the language specification since it's essentially a hardcoded behavior. One such example is the negation operator.

    – Patrick Roberts
    Mar 8 at 19:40











  • you might be able to alter the way a window property coerces, but not the actual object.

    – dandavis
    Mar 8 at 19:43
















The short answer is JavaScript does not have actual operator overloading, so there is no way to modify certain behaviors in the language specification since it's essentially a hardcoded behavior. One such example is the negation operator.

– Patrick Roberts
Mar 8 at 19:40





The short answer is JavaScript does not have actual operator overloading, so there is no way to modify certain behaviors in the language specification since it's essentially a hardcoded behavior. One such example is the negation operator.

– Patrick Roberts
Mar 8 at 19:40













you might be able to alter the way a window property coerces, but not the actual object.

– dandavis
Mar 8 at 19:43





you might be able to alter the way a window property coerces, but not the actual object.

– dandavis
Mar 8 at 19:43












1 Answer
1






active

oldest

votes


















3














foo == true actually converts foo to a number, that's why valueOf works, but it's misleading.
You can try == true here to see which steps of the comparison algorithm are executed (disclaimer: I made that).



!foo however calls ToBoolean, which explicitly always returns true for an object. There is no way to override that behavior.



enter image description here






share|improve this answer























  • So if you do var obj = valueOf: function() return true; ; console.log(obj == true), true will be converted to 1 and then back to true?

    – nick zoum
    Mar 8 at 21:17











  • Both trues will be converted to 1.

    – Felix Kling
    Mar 8 at 21:18












  • so the expression is coerced to 1 == 1?

    – nick zoum
    Mar 8 at 21:19











  • Yep. You can try it on the page I linked to.

    – Felix Kling
    Mar 8 at 21:20











  • Isn't obj supposed to be coerced to the same type as the true though?

    – nick zoum
    Mar 8 at 21:21











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55069857%2fcan-you-override-the-truthy-coercion-of-a-javascript-object%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














foo == true actually converts foo to a number, that's why valueOf works, but it's misleading.
You can try == true here to see which steps of the comparison algorithm are executed (disclaimer: I made that).



!foo however calls ToBoolean, which explicitly always returns true for an object. There is no way to override that behavior.



enter image description here






share|improve this answer























  • So if you do var obj = valueOf: function() return true; ; console.log(obj == true), true will be converted to 1 and then back to true?

    – nick zoum
    Mar 8 at 21:17











  • Both trues will be converted to 1.

    – Felix Kling
    Mar 8 at 21:18












  • so the expression is coerced to 1 == 1?

    – nick zoum
    Mar 8 at 21:19











  • Yep. You can try it on the page I linked to.

    – Felix Kling
    Mar 8 at 21:20











  • Isn't obj supposed to be coerced to the same type as the true though?

    – nick zoum
    Mar 8 at 21:21















3














foo == true actually converts foo to a number, that's why valueOf works, but it's misleading.
You can try == true here to see which steps of the comparison algorithm are executed (disclaimer: I made that).



!foo however calls ToBoolean, which explicitly always returns true for an object. There is no way to override that behavior.



enter image description here






share|improve this answer























  • So if you do var obj = valueOf: function() return true; ; console.log(obj == true), true will be converted to 1 and then back to true?

    – nick zoum
    Mar 8 at 21:17











  • Both trues will be converted to 1.

    – Felix Kling
    Mar 8 at 21:18












  • so the expression is coerced to 1 == 1?

    – nick zoum
    Mar 8 at 21:19











  • Yep. You can try it on the page I linked to.

    – Felix Kling
    Mar 8 at 21:20











  • Isn't obj supposed to be coerced to the same type as the true though?

    – nick zoum
    Mar 8 at 21:21













3












3








3







foo == true actually converts foo to a number, that's why valueOf works, but it's misleading.
You can try == true here to see which steps of the comparison algorithm are executed (disclaimer: I made that).



!foo however calls ToBoolean, which explicitly always returns true for an object. There is no way to override that behavior.



enter image description here






share|improve this answer













foo == true actually converts foo to a number, that's why valueOf works, but it's misleading.
You can try == true here to see which steps of the comparison algorithm are executed (disclaimer: I made that).



!foo however calls ToBoolean, which explicitly always returns true for an object. There is no way to override that behavior.



enter image description here







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 8 at 19:38









Felix KlingFelix Kling

562k131871936




562k131871936












  • So if you do var obj = valueOf: function() return true; ; console.log(obj == true), true will be converted to 1 and then back to true?

    – nick zoum
    Mar 8 at 21:17











  • Both trues will be converted to 1.

    – Felix Kling
    Mar 8 at 21:18












  • so the expression is coerced to 1 == 1?

    – nick zoum
    Mar 8 at 21:19











  • Yep. You can try it on the page I linked to.

    – Felix Kling
    Mar 8 at 21:20











  • Isn't obj supposed to be coerced to the same type as the true though?

    – nick zoum
    Mar 8 at 21:21

















  • So if you do var obj = valueOf: function() return true; ; console.log(obj == true), true will be converted to 1 and then back to true?

    – nick zoum
    Mar 8 at 21:17











  • Both trues will be converted to 1.

    – Felix Kling
    Mar 8 at 21:18












  • so the expression is coerced to 1 == 1?

    – nick zoum
    Mar 8 at 21:19











  • Yep. You can try it on the page I linked to.

    – Felix Kling
    Mar 8 at 21:20











  • Isn't obj supposed to be coerced to the same type as the true though?

    – nick zoum
    Mar 8 at 21:21
















So if you do var obj = valueOf: function() return true; ; console.log(obj == true), true will be converted to 1 and then back to true?

– nick zoum
Mar 8 at 21:17





So if you do var obj = valueOf: function() return true; ; console.log(obj == true), true will be converted to 1 and then back to true?

– nick zoum
Mar 8 at 21:17













Both trues will be converted to 1.

– Felix Kling
Mar 8 at 21:18






Both trues will be converted to 1.

– Felix Kling
Mar 8 at 21:18














so the expression is coerced to 1 == 1?

– nick zoum
Mar 8 at 21:19





so the expression is coerced to 1 == 1?

– nick zoum
Mar 8 at 21:19













Yep. You can try it on the page I linked to.

– Felix Kling
Mar 8 at 21:20





Yep. You can try it on the page I linked to.

– Felix Kling
Mar 8 at 21:20













Isn't obj supposed to be coerced to the same type as the true though?

– nick zoum
Mar 8 at 21:21





Isn't obj supposed to be coerced to the same type as the true though?

– nick zoum
Mar 8 at 21:21



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid …


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55069857%2fcan-you-override-the-truthy-coercion-of-a-javascript-object%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Posting a File and Associated Data to a RESTful WebService preferably as JSON2019 Community Moderator ElectionREST URI convention - Singular or plural name of resource while creating itUploading both data and files in one form using Ajax?How do I upload a file with metadata using a REST web service?REST API - file (ie images) processing - best practicesSpring: JSON data and file in the same requestREST API Put large dataPosting a file and JSON data to Spring rest serviceRESTful Web Service Upload/Download Large Data With JSONREST API Design sending JSON data and a file to the api in same requestPost JSONArray to REST servicePUT vs. POST in RESTParsing values from a JSON file?JavaScript/jQuery to download file via POST with JSON dataHow do I upload a file with metadata using a REST web service?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?Separate REST JSON API server and client?what's the correct way to send a file from REST web service to client?How do I write JSON data to a file?What is “406-Not Acceptable Response” in HTTP?REST API - file (ie images) processing - best practices

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page