Sponsored Links

December 5, 2017

Cool JavaScript Tricks

Today I would like to mention some of the JavaScript tricks that many JavaScript programmers do not know. They are cool to have in our code, but some are not practiced in real world. Here are few of them.
  1. Use of .call() function:
    If you want to iterate over the properties of object.
    var listitems = document.querySelectorAll('li'); 
    [].forEach.call(items, function(item) {
    //your code here
    })
    
    Above code does the same as the code below
    for (i = 0; i < items.length; i++) {
    var item= items[i];
    // your code here
    }
    Reversing a string:
    var js = 'hello javascript';
    var sj = [].reverse.call(hey.split('')).join(''); // "tpircsavaj olleh"
    console.log(sj);
  2. Always use var while declaring variable for the first time.
  3. Use === instead of == .
  4. undefined, null, 0, false, "", NaN are all false values.
  5. Use semicolon (;) for line termination.
  6. Get random item in an array.
    var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
    var random = items[Math.floor(Math.random() * items.length)];
    
  7. Verify that the given argument is number
    function isNumber(n){
        return !isNaN(parseFloat(n)) && isFinite(n);
    }
    
  8. Get min and max of the array of numbers:
    var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
    var maxInNumbers = Math.max.apply(Math, numbers);
    var minInNumbers = Math.min.apply(Math, numbers);
    
  9. Use the map() function method to loop through an array’s items
    var squares = [1,2,3,4].map(function (val) {
        return val * val;
    });
    
    // squares will be equal to [1, 4, 9, 16]
    
  10. Avoid using try-catch-finally inside a loop:
    The try-catch-finally construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable.
  11. If you want to know how much time is taken by a code, place console.time("time") and console.timeEnd("time") at beginning and end of the code respectively.
  12.  
  13. Converting decimal to binary and vice versa:
    Decimal to Binary
    (15).toString(2) // Will give 1111 
    Binary to Decimal
    parseInt('1111',2); // will give 15 

No comments:

Post a Comment