I am not a JavaScript geek therefore I need cheat sheets:

Overview:

  • JavaScript IS case sensitive!

 

Scope of variables:

  • variables are not as isolated in scope as in PL/pgSQL!
    • if you use the same variable name in nested function or in other plv8 function and you forgot to declare it with “var” then it uses already existing variable from higher function!
    • and if this variable does not exist when we assign a value to it for the first time without “var” then this variable is created as global !
    • therefore never forget to use “var” for all variables !!!
    • and maybe it is a good idea to use function specific names of variables to avoid unexpected behavior

 

Declarations:

  • object: var variable = new Object(); / var variable = {};
  • array: var variable = new Array(); / var variable = [];

 

IF conditions:

  • if variable is not defined:
    • if (<variable> == undefined)
    • if (typeof(<variable>) === ‘undefined’)
  • inline IF:
    • ((…condition…) ? <result_yes> : <result_no> )
    • can be embedded also into string concatenation:
      • var mystr = “first part “+((condition) ? “string for true” : “string for false”) +” end of string”;

 

Conversions:

  • convert boolean into integer:
    • +(…condition…)
  • simply evaluate more conditions for check:
    • var result= +(cond1) + +(cond2) … etc.
    • gets integer sum of true (1) results

 

JSON operations:

  • convert JSON string into array:
    • var jsonarray = JSON.parse(jsonstring);
    • values are accesible:
      • var attribvalue = jsonarray.attribname;
      • var attribvalue = jsonarray[attribname];  //or directly name as string
  • convert JSON array into string:
    • var jsonstring = JSON.stringify(jsonarray);

 

Switch ( case ) statement:

switch (variable) {
case value1:
...
break;
....
default:
....
}

 

Error handling:

try {
    ......;
} catch (e) {
    plv8.elog(NOTICE, "Error: ", e);
}

 

Nested functions:

Classical declaration and usage:

function myfunc() {
....
};

myfunc();

;

Inline declaration and usage in one (cannot be called again on other place):

(function () {
.....
})();