[Cheat Sheet] Javascript – Operators

Note: This is part of Javascript learning roadmap.

Unary operators

  • operators that work only on one value
  • increment/decrement (++ / — ) 
  • these operators have 2 versions:
    • prefix
      • the operator is put before the variable
      • the increment/decrement is made before the rest of the operation is evaluated
    • postfix
      • the operator is put after the variable
      • the increment/decrement is made before the rest of the operation is evaluated

The full example here

var index = 1; 
++index; // equivalent with index = index + 1 
console.log(index); // 2
var preIndex = ++index + 10; // first, the extraction and then + 10
console.log(index);   // 3 
console.log(preIndex);   // 13
var postIndex = index++ + 10;   // first, the operation (2 + 10) and then
                                // index value is incremented
console.log(postIndex); // 13
console.log(index); // 4
  • all four operators – pre/post, increment/decrement –  works on any value, not just strings:
    • a string valid representation of a number (ex. “22”) -> convert to number + apply the operation
    • a string not a valid number (ex. “yo”) -> convert to NaN (which is of type number)
    • a boolean false  -> convert to 0 + apply the operation
    • a boolean true -> convert to 1 + apply the operation
    • an object -> call valueOf() method (which should return a primitive) and apply the rules above

 


Unary + and –

  • plus  +
    • doesn’t have any effect on numbers
    • applied to nonnumeric value -> conversion via Number()
  • minus –
    • changes the sign on number (negates the value)
    • same as plus on nonnumeric value – but also changes the value

 


Comparison

Counterintuitive things that you should know

  • string compared to string – they compared by ASCII code of each letter (!Capitalized letter have smaller ASCII code)
“casda” > “C” // true
“daft” > “caft” 
“John” < “john”
“a”    > “”
“aa”   > “a”
  • if one of the operants is NaN – always evaluates to false 
 3 < “a” // false 
 3 >= “a” // false - because 3 is number so it attempts Number(“a”) which is NaN and 3 >= NaN is false

 


Operator precedence

  • determines the order they are applied when evaluating an expression
  • can be overridden using parentheses ()
  • the table bellow with the complete order should be intuitive (starting from the top, each operators comes before the ones beneath it)

 

Thank you for your time!

Please subscribe for more weekly web wisdom!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s