Q:

JavaScript ternary operator usage clarification

I'm working on a small script, using the ternary operator for short-hand 'if' statements. The code is below:
self.checked ? psswrd[z].type = 'text' : psswrd[z].type = 'password';

This essentially says, if the input is checked, make the input type 'text', else make it password. I have a feeling this is wrong in the sense I am repeating myself.
Ideally, I want to do something like this:
psswrd[z].type ? 'text' : 'password';

But how can I check the 'if' part of it being checked? I am new to this ternary method so explanations would go a long way, and thank you.
The full loop if needed:
for ( var j = 0; j < checkz.length; j++ ) {

            var self = checkz[j];
            self.onchange = function () {
                for ( var z = 0; z < psswrd.length; z++ ) {

                    self.checked ? psswrd[z].type = 'text' : psswrd[z].type = 'password';

                }
            }

        }

A:

Simply do
 psswrd[z].type = self.checked ? 'text' : 'password';

This is also much more readable. I would recommend to more generally avoid to use the ternary operator to replace a if statement unless the code appears to be clear enough.

A:

The ternary operator ?: used like [condition] ? [code1] : [code2] evaluates the condition and if it is evaluated to true it will return code1, otherwise code2. It will never happen that both code1 and code2 will be evaluated, just one of them. That´s why 
var abc = test == null ? "no" : test.something()
will work both if test is null or not.
The operator is generally used in assigments like a = condition ? code1 : code2, then it is equivalent to
if (condition)
  a = code1;
else 
  a = code2;

In your case you would have to use 
psswrd[z].type = self.checked ? 'text' : 'password'; 
which is euivalent to
if (self.checked)
  psswrd[z].type = 'text';
else 
  psswrd[z].type = 'password';

Little variations of the general use would be just condition ? code1 : code2 what would just cause either code1 or code2 to be executed and the return value would be discarded.
Or you can use it inside another assigment like var num = 17 + (test ? -17 : 25) which will set num to 0 if test is evaluated to true or to 42 if it is evaluated to false.

