javascript elementary

  1. values and objects
  2. variables tricks
  3. objects, types and equality
  4. aliasing : pro and contra

  5. operators
  6. ternary operation (aka cond)
  7. branches
  8. loops

  9. strings
  10. parseInt (x)
  11. parseFloat (x)
  12. Math methods
  13. Date methods
  14. Array methods

  15. HOF, user's functions
  16. HOF, map
  17. HOF, reduce (aka fold)
  18. HOF, filter
  19. HOF, some
  20. HOF, every

  21. for .. in ..
  22. try .. catch

values and objects

values:
  copied by passed by compared by
numbers by val by val by val
strings immutableimmutableby val
arrays by ref by ref by ref
objects by ref by ref by ref
booleans  
functions  

'falsy' values: false, 0, '', null, undefined, NaN
all other values are 'truthy'

objects are containers. they contain key/value pairs (key is always string, and all values are objects except null and undefined)

objects can be modified at any time

objects are passed by reference

an object can inherit from another object

simple object constructor:

   var x = {
      key1 : value1,
      key2 : value2,
   }
  $> js
  js> var a = { key1:"valueOne", key2:true, key3:10.2, key4:[1,2,3,4] };
  js> a.key1
   "valueOne"
  js> a.key2
   true
  js> a.key3
   10.2
  js> a.key4
   [1, 2, 3, 4]
  js> a    
   ({key1:"valueOne", key2:true, key3:10.2, key4:[1, 2, 3, 4]})
  js> a.key1 = "valueHundred";
   "valueHundred"
  js> a
   ({key1:"valueHundred", key2:true, key3:10.2, key4:[1, 2, 3, 4]})
  js> a.key4[2]=2000;
   2000
  js> a
   ({key1:"valueHundred", key2:true, key3:10.2, key4:[1, 2, 2000, 4]})


variables' tricks

most languages will stop you (or, at least, warn you) when you are defining a variable with a name that is already taken. not JavaScript

if you declare a new variable without the var keyword inside a function - it becomes global in scope

  js> var a = "goodbye hel";
  js> var f = function() { var a = "helo world"; print(a); };
  js> f();
   helo world
  js> print(a);
   goodbye hel
  js> var f = function() { a = "helo world"; print(a); };
  js> f();
   helo world
  js> print(a);
   helo world


objects, types and equality

  js> new String("abc") == new String("abc")
   false
  js> new String("abc") == "abc"
   true
  js> typeof "abc"
   string
  js> typeof new String("abc")
   object
so:
  js> var bar = "abc"
  js> bar.foo = true
   true
  js> bar.foo
  js> undefined
but:
  js> var baz = new String("abc")
   abc
  js> baz.foo = true
   true
  js> baz.foo
   true


aliasing : pro and contra

js> a = {foo:1, bar:2};
({foo:1, bar:2})
js> b = a;
({foo:1, bar:2})
js> a.foo = 100;
100
js> b
({foo:100, bar:2})

js> var a = { foo : "bar" };
js> var h = [];
js> h.push (a);
 1
js> a.foo = "fub";
 "fub"
js> h[0].foo = "baz";
 "baz"
js> print (a.foo);
 baz
and more:
js> var b = function (x) { return x * 2; };
js> var c = b;
js> var b = function (x) { return x * 3; };
js> var d = b;
js> print (c (2));
 4
js> print (d (2));
 6
in JS passing by value is used only for numbers (and for strings - only when they are compared)


operators

arithmetic +     -     *     /     %     ++     --     +(unary plus)     -(unary minus)
logic &&         ||         !    
string +
assignment =         +=         -=         *=     /=     %=     <<=     >>=     >>>=     &=     |=     ^=
bitwise &         |         ^         ~         <<         >>         >>>
comparison ==         ===         !=         !==         <         <=         >         >=
other
val1 , val2evaluates both of its operands (from left to right) and returns the value of the second
varX ? val1 : val2if-else-then
for, in, while, if 
try/catch/finally 
varX instanceof classY checks the class inheritance
typeof varX  
void varX evaluates the given expression and then returns 'undefined'
delete varX cuts off properties


ternary operation (aka cond)

  // file "tern.js"

  var foo = function (a, b) {
    return (
      a >= 0   ?   "a is not negative "            :
      b <= 0   ?   "a and b are negative "         :
                   "a is negative, b is positive"
    );
  };

$> js tern.js
js> print(foo(1,2));
 a is not negative
js> rint(foo(-1,2));
 a is negative, b is positive
js> print(foo(-1,-2));
 a and b are negative
js> print(foo(1,-2));
 a is not negative

branches

js> var f = function (x) {                         
    if      (x > 1)  { print ("more than one"); }      
    else if (x == 0) { print ("equal to zero"); }
    else             { print ("negative"); }
}
js> f (10);
more than one
js> f (0);
equal to zero
js> f (-10);
negative

loops

js> for (i = 0; i < 10; i++) { print (i); } 
0
1
2
3
4
5
6
7
8
9

js> var a = 10;
js> while (a) { a -= 1; print (a); }
9
8
7
6
5
4
3
2
1
0

js> var a = 10;
js> do { a += 1; print (a); } while (a < 20);
11
12
13
14
15
16
17
18
19
20

strings

string functions

slice (start, stop)
concat (y)
split (Char)
parseInt (String)
parseFloat (String)
substr (start, length)
substring (start, end)

string parsing

parseInt ("10.2")

parseFloat ("126.78")


Math object methods

random ()number between 0 and 1
abs (x) 
 
exp (x) 
log (x) 
 
round (x)rounds x to the nearest integer
ceil (x)rounds upwards to the nearest integer
floor (x)rounds downwards to the nearest integer
 
sqrt (x) 
cbrt (x) 
pow (x, y) 
 
cos (x) 
sin (x) 
tan (x) 
acos (x) 
asin (x) 
atan (x) 
 
min (x, y, ...) 
max (x, y, ...) 


Date object methods

return valfunctionremarks
Numberparse (String date) 
StringvalueOf () 


Array object methods

return valfunction
Arrayx.concat (Array y)
Stringx.join (String delimiter)
Valuex.pop ()
Numberx.push (Value)
Valuex.shift ()
Numberx.unshift (Value)
Arrayx.reverse ()
Arrayx.sort (CompareFunction)
Arrayx.slice (Number startIndex, Number endIndex)


HOF, user functions

function as param:
  js> var f1 = function (x, y) { return x + y; };
  js> var f2 = function (f, x, y) { return f (x, y); };
  js> f2 (f1, 4, 5);
   9
  js> f3 (function (x, y) { return y - x; }, 4, 5); 
   1
  js>
function as return value:
  js> var f4 = function() { return function (x, y) { return x - y; } };
  js> (f4 ()) (4, 8);
   -4


HOF, map

  var result = array.map (callback [, thisObject]);

  'callback' is invoked with three arguments:
   - the value of the element
   - the index of the element
   - the array being traversed

  if a 'thisObject' parameter is provided, then it will be used as 
  the 'this' for each invocation of the 'callback'

  if it is not provided, or is 'null', then the global object
  associated with 'callback' is used instead

  js> var b = function(x) { return x * 2; };
  js> var c = [1, 2, 3, 4, 5];
  js> c.map(b);
   [2, 4, 6, 8, 10]
  js>


HOF, reduce (aka fold)

  var result = array.reduce (callback [, initVal]);

  'callback' receives four arguments:
    - the initial value 
    - the value of the current element
    - the current index
    - the array over which iteration is occurring

  the call would look something like this:

    array.reduce (function (prevVal, currVal[, index, array]) { ...  } );

  the first time the function is called, the 'prevVal' and 'currVal' can be one of two values:

  if an 'initVal' was provided in the 'reduce' call, then
      'prevVal' will be set to 'initValue'
      'currVal'  will be set to the first value in the array

  if no 'initVal' was provided, then
      'prevVal' will be set to the first value in the array
      'currVal' will be set to the second value in the array

  js> var c = [1, 2, 3, 4, 5];
  js> var d = function(x, y) { return x * y; };
  js> c.reduce(d, 1);
   120
  js> var p = function(x, y) { return x + y; }; 
  js> c.reduce(p, 0);                           
   15


HOF, filter

  array.filter (callback [, thisObject]);

  returns list of elements for which 'callback' returns 'true'.

  'callback' is invoked with three arguments:
   - the value of the element
   - the index of the element
   - the Array object being traversed

  if 'thisObject' parameter is provided to 'filter' call,
  it will be used as 'this' for each invocation of the 'callback'.

  if it is not provided, or is 'null', the global object
  associated with 'callback' is used instead.

  $> js
  js> var f = function(x) { return (x > 10); };
  js> var b = [1, 2, 12, 3, 4, 34, 5, 6];
  js> b.filter (f);
   [12, 34]


HOF, some

  array.some (callback [, thisObject]);

  executes the 'callback' function until it finds the element on which 'callback' returns 'true'
  if such element is found - immediately returns 'true', otherwise - returns 'false'

  'callback' is invoked with three arguments:
    - the value of the element
    - the index of the element
    - the Array object being traversed

  if 'thisObject' parameter is provided to some, it will be used as 'this' for 
  each invocation of the 'callback'

  if it is not provided, or is 'null', the global object associated
  with 'callback' is used instead

  $> js
  js> var f = function(x) { return (x >= 10) };
  js> var b = [2, 5, 8, 1, 4];
  js> b.some (f);
   false
  js> var c = [5, 8, 1, 12, 4];
  js> c.some (f);
   true
  js>


HOF, every

  array.every (callback [, thisObject]);

  executes 'callback' function until it finds the element where 'callback' returns 'false'
  if such element is found, immediately returns 'false'
  if 'callback' returnes 'true' for all elements, returns 'true'

  'callback' is invoked with three arguments:
   - the value of the element
   - the index of the element
   - the Array object being traversed

  if 'thisObject' parameter is provided 'every' call, it will be used
  as 'this' for each invocation of the 'callback'

  if it is not provided, or is 'null', the global object associated
  with 'callback' is used instead

  js> var f = function (x) { return (x >= 10); }
  js> var b = [12, 5, 8, 130, 44];
  js> b.every (f);
   false
  js> var c = [12, 54, 18, 130, 44];
  js> c.every (f);
   true
  js>

for .. in ..

js> var a = [1,2,3,4];           
js> for (x in a) { print (x); }; 
0
1
2
3

js> b
({key1:1, key2:"two", key3:true})
js> for (x in b) { print (x); }
key1
key2
key3

try .. catch

<html>
<head>
<script>

var fun1 = function (x)
    {
      if (x > 0) { prompt ("continue?") ; return x += 1 ; }
      else throw "x is not positive";
    }

var fun2 = function (x)
    {
      try       { confirm (fun1 (x)); }
      catch (e) { alert ("something went wrong: " + e); }
        //      no matter what happens, this code will be run
      finally   { document.write ("done!"); }
    }

</script>
</head>

<body>
    <input value="3" onchange="fun1 (parseInt (this.value))">
    <input value="2" onchange="fun2 (parseInt (this.value))">
</body>
</html>