JavaScript tips

Here is some tips and tricks I use quite often.

Capitalize fist character in a string/sentence

Getting initals of a name. First method uses regex, and the second method uses split(),join() and map()

'George Washington'.replace(/\W*(\w)\w*/g, '$1').toUpperCase();  
'Abraham Lincoln'.split(' ').map(function(s){return s.trim().charAt(0); }).join('');  

Public, Private and Static variables

Deep Copy tricks

  #copy date object
  var now = new Date();
  var dt  = new Date(now);

  #deep copy array of names  
  var names = ['hebert','alice','scott','olga'];
  var cname = names.slice();

  #deep clone from native function  
  var user = new User() || { first : 'John', last : 'Doe' };
  var cuser = Object.create( user );

  #deep clone with JSON object    
  var expensive = JSON.parse( JSON.stringify( user ) );

Without using a word processor, this methods reveals handy when to "capitalize", "lowercase" or "uppercase" a string.

Lowercase

  1. Open Console right click > inspect element(Chrome Dev)
  2. Paste your text inside quotation marks.
  3. "TEXT GOES HERE".toLowerCcase()
  4. Press Enter, and done!

Uppercase

"damn text goes here".toUpperCase(); 

Capitalize

"dAMN tEXT gOES hERE".toCapital(); 

Counting elements on a webpage

A quick a dirty tip for counting down HTML tags on a web-page using JavaScript

document.getElementsByTagName('*').length  

Note:

Back in days, 700 HTML tags per page were a rule of thumb. This tip were initially published in "Best Practices for Speeding Up Your Web Site" section "Reduce the Number of DOM Elements".


Express+Socket.io initialization

var app = require("express");  
var server = require("http").Server(app);  
var io = require("socket.io")(server);

#function handleClient(socket){ };

io.on("connection", handleClient);

app.listen(8080);  

source


Tracing JavaScript function calls.
Thoughts: I have a problem similar to this.
In addition to asynchronous function calls. The truth is, there are too few JS function tracing tools around there similar to FireFlow. I tried and looks like it doesn't work anymore(designed in 2012 and unusable in 2016, internet is growing so fast!).

Then I found this A tracer utility in 2kb!


Cleaning a string with map-reduce

This function can be customized to remove bad text from a string.
In this case, string starting with #(likewise, blacklisted strings) are removed from initial string

var clean = '#fucking Abraham #Aloha Lincoln '  
    .split(' ')
    .map(function(str) {
          if (str.trim().indexOf('#') < 0) return str.trim();
    })
    .reduce(function(pre, cur) {
          if (pre) return [pre, cur].join(' ');
          return cur;
    });

#clean is now 'Abraham Lincoln'

Counting the number of functions an object

var count = (Object.keys(obj) || []).filter(function(key){ return typeof obj[key] === 'function';});  

source


Performance on loop

    var index = 20000;
    while(index--){}
    # instead of 
    for(var i = 0; i < index; index++){}

    # function perfoms better when b is a pure
    function a(){
        b(123);
        function b(value){ return value * value; }
    }

source -- performance tests: 1 and 2

I hope this will help you too :-)

Show Comments