From eBabel wiki
Jump to: navigation, search

Re-usable functions

Update on sorting with Javascript

[{id: 5, catName: 'Hara'}, {id: 2, catName: 'Ido'}, {id: 12, catName: 'Edwina'}, {id: 8, catName: 'Vitas'}]
  .sort((a, b) => {
    const aId =;
    const bId =;
    if (aId < bId) { return -1; }
    if (aId > bId) { return 1; }
    return 0;
.map(cat => cat.catName)


["Ido", "Hara", "Vitas", "Edwina"]

Code sample below is older and not so good

List properties of a Javascript object


Run Javascript in Terminal or Cmd

Mac OS

Write the following script:

<syntaxhighlight lang="javascript">

var person = {
   firstName: 'Nadjib',
   lastName: 'Amar'



Run the command in Terminal, assuming your script is called test.js and is in the current directory:

/System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Resources/jsc test.js



<syntaxhighlight lang="javascript">

var person = {
  firstName: 'Nadjib',
  lastName: 'Amar'



Command to run in cmd.exe:


Vector graphics made with Javascript

Duck typing

Display unicode characters with Javascript


Unicode character charts

Event bubbling and event delegation

What we should do is using event delegation thanks to the bubbling nature of the click event in the DOM tree. Event delegation idea is to put only one click handler on a parent wrapping HTML element. Then when the user click on a button, a click event is fired.

The event target is set to the HTMLElement button itself. Since we attached no click handler to each button nothing happen (yet). This click event will bubble up to the HTML parent container which have one click listener. We just need to check the original target of the click event and do something accordingly to this target.

<syntaxhighlight lang="html4strict">

   <input type='button' id='button1'>
   <input type='button' id='button2'>
   <input type='button' id='button3'>
   <input type='button' id='buttonN'>


<syntaxhighlight lang="javascript">

   $('buttonContainer').observe('click', function(e){
   var element =;
   switch(){ ... };
   // call popup using some attribute data encoded in class for example.


Event delegation in raw Javascript



On many articles about concatenation, it has been advised that using an array join is faster than using the plus operator.

This is no longer true because browsers since IE8 included have optimized the plus operator concatenation. Prior to IE8, it used to be true that var test = ["1", "2"].join(""); was faster than var test = "1" + "2";

I have run my own test to check plus operator vs array join concatenation performance.

Javascript objects

Recommended read: Best practice Javascript for developers who learnt C# first.

Based on an interesting Stackoverflow thread about Javascript namespacing:

<syntaxhighlight lang="javascript">

(function( skillet, $, undefined ) {
   //Private Property
   var isHot = true;

   //Public Property
   skillet.ingredient = "Bacon Strips";

   //Public Method
   skillet.fry = function() {
       var oliveOil;

       addItem( "\t\n Butter \n\t" );
       addItem( oliveOil );
       console.log( "Frying " + skillet.ingredient );

   //Private Method
   function addItem( item ) {
       if ( item !== undefined ) {
           console.log( "Adding " + $.trim(item) );
}( window.skillet = window.skillet || {}, jQuery ));


Then call this code and observe what happens in the Firebug console:

<syntaxhighlight lang="javascript">



Replace in a string

The built-in function replace will only replace one instance if written like this:

<syntaxhighlight lang="javascript">

document.write ( 'hello world'.replace( 'o', '8') );


To make sure that both 'o' instances are replaced by an '8', use a regular expression with the /g global instruction.

<syntaxhighlight lang="javascript">

document.write ( 'hello world'.replace( /o/g, '8') );


See jsfiddle of this code.

if ( you != eval() ) win++;

Or in plain English, "don't be eval!".

Pun set aside, eval is a security risk because it can be abused by hackers to inject their own javascript that will then run with the privileges of your domain. This opens the door to Cross Site Scripting attacks, malware and other unpleasantness.

On possible solution: use the square braket notation.

Bad code:

eval(someVariable + anotherVariable + ".Hide();");

Good code:

window[ someVariable + anotherVariable ].Hide();

Javascript best practice

Recommended reads:

  1. 24 Javascript best practices for beginners

Javascript code snippets


<syntaxhighlight lang="javascript">

   // Return an array of DOM elements that match a given className.
   mp.getElementsByClass = function (className) {

       var elements, 
           result = [];
       if (!className) {
           throw new Error("Required parameters are missing.");
       // Modern browsers only.
       if (document.querySelectorAll) {
           return document.querySelectorAll("." + className);
       // Fall-back for older browsers.
       elements = document.getElementsByTagName('*');
       for (index = 0; index < elements.length; index = index + 1) {
           if((" " + elements[ index ].className + " ").indexOf(" " + className + " ") !== -1) {
       return result;