I am attempting to change the value of an input into a different string, depending on if the inputed answer was "Yes" or "No". I have attempted to use ternary operators to clear up my code a little bit, but I keep getting original value ("Yes" or "No") instead of the value that the input should change into. I have the following code  function setYesNoValue(input, yes, no){   input = input == "Yes" ? yes : no; }; setYesNoValue(oneLInput, "517", "518");   The task I am attempting to perform works well when I use standard if else conditional statements, but I would like to implement this strategy to clear up the length code. Why isn't the value passed as the first argument changing when I reassign it?
330
The primitive types (number, string, etc.) are passed by value, but objects are unknown, because they can be both passed-by-value (in case we consider that a variable holding an object is in fact a reference to the object) and passed-by-reference (when we consider that the variable to the object holds the object itself).  Although it doesn't really matter at the end, I want to know what is the correct way to present the arguments passing conventions. Is there an excerpt from JavaScript specification, which defines what should be the semantics regarding this?
115517
I wanted to suggest an edit for  given to , but it was denied because "Edits must be at least 6 characters."  However, given the edit I was suggesting is very important to the syntax of the solution, I think it is relevant even though it contains only 3 characters. See the answer posted by knittl and notice the variable $value is used as both function input and in the foreach loop. I simply suggested changing the function parameter's name to $values in the 3 locations it is used, but was denied, leaving the post incorrect.  Note: I do realize I could have suggested an entirely different variable name thus allowing the edit, but similar situations have arisen in the past where a simple fix of just a few characters make a significant difference. After all, Stack Overflow is a coding website and syntax is very important.
32595
I need to set a constant value as true or false for the particular scenario not sure correct working or not const test = data.findIndex(d =&gt; d.Fname === '' &amp;&amp; d.Lname === '') &lt; 0 ? false : true;  if fname and Lname both are blank then i want to set test as false not sure what is happening here.
37382
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:  String s = new String("silly");   Because it creates unnecessary String objects. But instead it should be written like this:  String s = "No longer silly";   Ok fine so far...However, given this class:  public final class CaseInsensitiveString {     private String s;     public CaseInsensitiveString(String s) {         if (s == null) {             throw new NullPointerException();         }         this.s = s;     }     :     : }  CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); String s = "polish";    Why is the first statement ok? Shouldn't it be   CaseInsensitiveString cis = "Polish"; How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?
78724
This code in JS gives me a popup saying "i think null is a number", which I find slightly disturbing. What am I missing?    if (isNaN(null)) {   alert("null is not a number"); } else {   alert("i think null is a number"); }     I'm using Firefox 3. Is that a browser bug?  Other tests:    console.log(null == NaN);   // false console.log(isNaN("text")); // true console.log(NaN == "text"); // false     So, the problem seems not to be an exact comparison with NaN?  Edit: Now the question has been answered, I have cleaned up my post to have a better version for the archive. However, this renders some comments and even some answers a little incomprehensible. Don't blame their authors. Among the things I changed was:   Removed a note saying that I had screwed up the headline in the first place by reverting its meaning Earlier answers showed that I didn't state clearly enough why I thought the behaviour was weird, so I added the examples that check a string and do a manual comparison.
7905
What is the difference between == and ===?  How exactly does the loosely == comparison work? How exactly does the strict === comparison work?  What would be some useful examples?
20733
Why does the following code in C work?  const char* str = NULL; str = "test"; str = "test2";   Since str is a pointer to a constant character, why are we allowed to assign it different string literals?  Further, how can we protect str from being modified?  It seems like this could be a problem if, for example, we later assigned str to a longer string which ended up writing over another portion of memory.  I should add that in my test, I printed out the memory address of str before and after each of my assignments and it never changed.  So, although str is a pointer to a const char, the memory is actually being modified.  I wondered if perhaps this is a legacy issue with C?
24071
I'm trying to understand Python's approach to variable scope. In this example, why is f() able to alter the value of x, as perceived within main(), but not the value of n?  def f(n, x):     n = 2     x.append(4)     print('In f():', n, x)  def main():     n = 1     x = [0,1,2,3]     print('Before:', n, x)     f(n, x)     print('After: ', n, x)  main()   Output:  Before: 1 [0, 1, 2, 3] In f(): 2 [0, 1, 2, 3, 4] After:  1 [0, 1, 2, 3, 4]
41641
What is the most efficient way of testing an input string whether it contains a numeric value (or conversely Not A Number)? I guess I can use Double.Parse or a regex (see below) but I was wondering if there is some built in way to do this, such as javascript's NaN() or IsNumeric() (was that VB, I can't remember?).  public static bool IsNumeric(this string value) {     return Regex.IsMatch(value, "^\\d+$"); }
40928
How can you check whether a string is convertible to an int?  Let's say we have data like "House", "50", "Dog", "45.99", I want to know whether I should just use the string or use the parsed int value instead.  In JavaScript we had this  function. If the string couldn't be parsed, it would get back NaN.
26673
Switch statement fallthrough is one of my personal major reasons for loving switch vs. if/else if constructs. An example is in order here:  static string NumberToWords(int number) {     string[] numbers = new string[]          { "", "one", "two", "three", "four", "five",            "six", "seven", "eight", "nine" };     string[] tens = new string[]          { "", "", "twenty", "thirty", "forty", "fifty",            "sixty", "seventy", "eighty", "ninety" };     string[] teens = new string[]         { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",           "sixteen", "seventeen", "eighteen", "nineteen" };      string ans = "";     switch (number.ToString().Length)     {         case 3:             ans += string.Format("{0} hundred and ", numbers[number / 100]);         case 2:             int t = (number / 10) % 10;             if (t == 1)             {                 ans += teens[number % 10];                 break;             }             else if (t &gt; 1)                 ans += string.Format("{0}-", tens[t]);         case 1:             int o = number % 10;             ans += numbers[o];              break;         default:             throw new ArgumentException("number");     }     return ans; }   The smart people are cringing because the string[]s should be declared outside the function: well, they are, this is just an example.  The compiler fails with the following error:   Control cannot fall through from one case label ('case 3:') to another Control cannot fall through from one case label ('case 2:') to another   Why? And is there any way to get this sort of behaviour without having three ifs?
12905
How do you get the  of two variables in Python?  For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):  str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2):     print "ok" else:     print "bad"   The ^ operator seems to be bitwise, and not defined on all objects:  &gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str'
5329
I'm building a function to extend the Enum.Parse concept that  Allows a default value to be parsed in case that an Enum value is not found Is case insensitive  So I wrote the following: public static T GetEnumFromString&lt;T&gt;(string value, T defaultValue) where T : Enum {     if (string.IsNullOrEmpty(value)) return defaultValue;     foreach (T item in Enum.GetValues(typeof(T)))     {         if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;     }     return defaultValue; }  I am getting a Error Constraint cannot be special class System.Enum. Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the Parse function and pass a type as an attribute, which forces the ugly boxing requirement to your code. EDIT All suggestions below have been greatly appreciated, thanks. Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML) public static class EnumUtils {     public static T ParseEnum&lt;T&gt;(string value, T defaultValue) where T : struct, IConvertible     {         if (!typeof(T).IsEnum) throw new ArgumentException(&quot;T must be an enumerated type&quot;);         if (string.IsNullOrEmpty(value)) return defaultValue;          foreach (T item in Enum.GetValues(typeof(T)))         {             if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;         }         return defaultValue;     } }  EDIT: (16th Feb 2015) Christopher Currens has posted  below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page. EDIT 2: (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)
12352
I just came onto a project with a pretty huge code base.   I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic.    if (!!variable &amp;&amp; (!!api.lookup("some-string"))) {        do_some_stuff();  }                                      I know these guys are intelligent programmers, it's obvious they aren't doing this by accident.   I'm no seasoned C++ expert, my only guess at why they are doing this is that they want to make absolutely positive that the value being evaluated is the actual boolean representation. So they negate it, then negate that again to get it back to its actual boolean value.   Is this correct, or am I missing something?
92333
if ('text'.equals(str))   or   if ('text' == str)   Is there any difference? If yes, then what is it?   Added, after answered.  String q = 'teXt'; system.debug('teXt'.equals(q)); // true system.debug('teXt' == q);      // true system.debug('text'.equals(q)); // false system.debug('text' == q);      // true
6195
Using PHP, what's the fastest way to convert a string like this: "123" to an integer?  Why is that particular method the fastest? What happens if it gets unexpected input, such as "hello" or an array?
97576
I have this code that checks that the string contains only space and hash characters (“#”), if so it echos 'yes' if not echos 'no' string=&quot;###############         #             #         # #############         #             #         # ######### # #         #         # # #         # ### ##### # #         #   #     # # #         # # ###########         # #                     ###############&quot;                          confirm_variable=&quot;Yes&quot;  for (( i=0; i&lt;${#string}; i++ )); do     str=&quot;${string:$i:1}&quot;     if [ &quot;$str&quot; == &quot;#&quot; ] || [ &quot;$str&quot; == &quot; &quot; ] || [ &quot;$str&quot; == &quot;\n&quot; ] ;          then             continue         else             confirm_variable=&quot;No&quot;             break     fi  done echo $confirm_variable  I am not sure why this isn't working as if I make the string equal something like: string=&quot;## #### # #  #&quot;   it seems to work fine.