Saturday, June 6, 2015

JavaScript Operators

1. Arithmetic Operators

1.1 Basic Arithmetic Operators
The basic arithmetic operators are * (multiplication), / (division), % (modulo: remainder after division), + (addition), and - (subtraction).
division operator
JavaScript do not have integer, all numbers are floating-point. So division operations have floating-point results:
5/2 // 2.5 not 2.
addition operator
The addition operator adds numeric operands or concatenates string operands.
19  +  84  // 103   two numbers -> addition
"19" + "84" // "1984" two strings -> concatenation
In other cases the conversion which takes place gives priority to string concatenation: if either operand is a string or an object that convert to string, the other operand is converted to string and a concatenation is performed.
"2" + 2 // "2" + 2.toString() -> "22"
var person = {fName:'Joe', lName:'Bloggs'};
5 + person // 5 + person.toString() -> "5[object Object]"
1.2 Unary Arithmetic Operator
Unary plus (+)
The unary plus operator converts its operand to a number (or NaN) and returns that value.
Unary minus (-)
The unary minus operator converts its operand to a number and then changes the sign of the result.
Increment (++)
The increment (++) operator increments its operand, which must be a left value (variable, element or property)
Decrement (--)
The decrement (--) operator subtracts 1 to its operand, which must be a left value (variable, element or property)

2. Relational Operators

JavaScript’s relational operators test for a relationship between two values and return true or false depending on whether that relationship exists. Relational operators are:
2.1 Equality Operator
Equality Operator are: strict equality operator (===), equality operator (==)
strict equality
The strict equality operator checks whether its two operands are “identical”: same type and same value.
// boolean values
true === true // true
false === false // true
// NaN value is never equal to any other value, including itself
NaN === NaN // FALSE
// number values
20 === 20 // true
// string values
"bye bye" === "bye bye" // true
// two reference values are strictly equal if they refer to the same object, array or function
var ref_1 = {};
var ref_2 = ref_1;
ref_1 === ref_2 // true
equality
The equality operator checks whether its two operands are “equal” using a more relaxed definition of sameness that allows type conversions, the conversion to number is favorited.
Same type values are equal if they are strictly equal
// primitive types
30 == 30; // true;
"bye" == "bye"; // true
// reference types
{} == {}; // FALSE
new String("bye") == new String("bye"); // FALSE
For different type values the == operator attempts conversion to number to check for equality as follows:
// undefined equals null
undefined == null; // true
// true convert to 1, false convert to 0
true  == 1; // true
false == 0; // true
// string "13" convert to number 13
"13" == 13; // true
If one value is an object, the object is converted to number calling its valueOf() method. if this fails, the object is converted to string calling its toString() method
// new Number(30).valueOf() -> 30
new Number(30) == 30; // true
// new String("bye").valueOf() returns the object itself, new String("bye").toString() returns "bye"
new String("bye") == "bye"; // true
2.2 Comparison Operators
Comparison operators are: Less than (<), Greater than (>), Less than or equal (<=), Greater than or equal (>=)
The comparison operators test the relative order, numerical or alphabetics, of their two operands:
11 < 3  // false, numeric comparison
"11" < "3" // true, string comparison
Comparison operator converts any operand that is neither a string nor a number, number conversion is favorited
"11" < 3 // false, numeric comparison
2.3 Membership operators
Membership operators are: in, instanceof
The in operator evaluates to true if the left-side value is the name of a property of the right-side object:
var person = { firstName:"Joe", lastName:"Doe" };
"firstName" in person // true
"first_name" in person // false
The instanceof operator evaluates to true if the left-side object is an instance of the right-side class or construct function.
var array = [1, 5, 25]; // array with 3 elements
array instanceof Array; // true
array instanceof Object; // true
array instanceof Number; // false

3. Logical Operators

The logical operators &&, ||, and ! perform Boolean algebra
3.1 Logical AND (&&)
The && operator can be understood at different levels:
1) && used to perform the Boolean AND operation on two values. && is often used to join two relational expressions:
x == 0 && y == 0 // true if, and only if x and y are both 0
2) && operator used to conditionally return the rigth operand when the left operand is truthy
operator description:
evaluate left operand 
if ( left operand is falsy ) 
then 
  return left operand
if ( left operand is truthy )
then 
  evaluate and return right operand
Example:
var o = { x : 1 };
var p = null;
o && o.x // 1: o is truthy, so return o.x
p && p.x // null: p is falsy, so return p and don't evaluate p.x
3.2 Logical OR (||)
The || operator can be understood at different levels:
1) || operator used to perform boolean OR with truthy and falsy operands
The || operator performs the Boolean OR operation on its two operands. If one or both operands is truthy, it returns a truthy value. If both operands are falsy, it returns a falsy value.
2) || operator used to conditionally return the rigth operand when the left operand is falsy
operator description:
evaluate left operand 
if ( left operand is truthy ) 
then 
  return left operand
if ( left operand is falsy )
then 
  evaluate and return right operand
As with the && operator, you should avoid right-side operands that include side effects, unless you purposely want to use the fact that the right-side expression may not be evaluated. An idiomatic usage of this operator is to select the first truthy value in a set of alternatives:
var div_width = width || preferences.width || 700px;

This idiom is often used in function bodies to supply default values for parameters:

// Copy the enumerable properties of p to o, and return o.
function copy(p, o) {
   o = o || {}; // If o is falsy, use a newly created object.
   for(prop in p) {
      o[prop] = p[prop];
   }
   return o;
}
3.3 Logical NOT (!)
The ! operator is a unary operator. It inverts the boolean value of its operand. Unlike other boolean operators, the ! operator converts its operand to a boolean value before inverting the converted value. This means that applying this operator twice you can convert any value x to its equivalent boolean value.

4. Evaluation Expression

eval() is a global function that evaluates a string of JavaScript source code. It returns the last expression/statement, it returns undefined if the last expression or statement had no value or throws SyntaxError if the string parsing fails.
var z = 1;
eval("var x=10; var y=10; x+y+z;"); // 21
eval("var x=10; var y=10; var k=x+y;"); // undefined
eval("var x=35s; x+10;"); // throws SyntaxError

5. Miscellaneus Operators

5.1 Conditional/Ternary Operator
The conditional operator has three operands. It is used like this:
x>0 ? x : -x // The absolute value of x
operator description:
evaluate the first operand as a boolean
if ( the first operand is truthy ) 
then 
  evaluate and return the second operand
if ( the first operand is falsy )
then 
  evaluate and return the third operand
the ternary operator is a shortcut to the if-else statement
var elm = document.getElementById('first_par');
elm.style.visibility==='hidden' ? elm.style.visibility='visible' : elm.style.visibility='hidden';
This is equivalent to, but more compact than, the following if statement:
var elm = document.getElementById('first_par');
if (elm.style.visibility==='hidden')
  elm.style.visibility='visible';
else
   elm.style.visibility='hidden';
5.2 The typeof operator
typeof is an unary operator. It returns a string that specifies the type of the operand.

Primitive Typestypeof
undefined "undefined"
null "object"
true or false "boolean"
any number or NaN "number"
any string "string"
Object Typestypeof
any function "function"
any nonfunction native object "object"
any host object an implementation-defined string

The typeof operator is only useful to distinguish objects from primitve types, to distinguish one class of object from another use: instanceof, class attribute or the constructor property
5.3 The delete operator
the delete operator remove a property/element from an object/array delete is a unary operator that attempts to delete the object property or array element specified as its operand.
var o = { x: 1, y: 2};
delete o.x; // delete a property
"x" in o // => false: the property does not exist anymore
Note: the deleted property is removed and not set to undefined
You cannot delete:
  • nonconfigurable properties
  • built-in core and client-side properties
  • variables declared with the var statement.
  • functions defined with the function statement
5.4 The void operator
The void is a unary operator evaluates its operand, then discards the value and returns undefined. The only use the void operator in a client-side javascript: URL
<a href="javascript:void window.open();">Open new window</a>
This HTML could be more cleanly written using an onclick event handler.
5.5 The comma operator
The comma operator is a binary operator. It evaluates its left and right operands and then returns the value of the right operand. A common situation in which the comma operator is used is with a for loop with multiple loop variables:
for(var i=0,j=10; i < j; i++,j--)
    console.log(i+j);

You may want to use the comma operator to perform two variable initializations on the same line

var person = {};
person.name="Joe", person.surname="Bloggs";
console.log(person); // Object {name: "Joe", surname: "Bloggs"}

No comments :

Post a Comment