Friday, 6 September 2013

Using a function with ternary operand as the new value parameter in Javascript replace function

Using a function with ternary operand as the new value parameter in
Javascript replace function

I'm chaining together a handful of .replace calls, and want to be able to
offer default replacement values via an inline function. Here's some
example code
bar = {};
foo = "test";
foo = foo.replace("test", function(){typeof bar.baz !== 'undefined'?
bar.baz : "default_text"});
In this example, foo is set to "undefined" instead of "default_text"
if I provide a similar function that simply returns:
bar = {}
foo = "test"
foo = foo.replace("test", function(){ return "something" });
foo is set to "something". What about the ternary operand, OR my code in
general is preventing the expected behavior in this case? Are there any
possible alternative solutions that would allow me to set default text,
inline (I understand I can wrap the replaces in an if..then, checking that
the object property exists, but for the use case it would not be optimal)
Thanks for the help

No comments:

Post a Comment