Skip to content

KidusMT/JavaScriptIdioms

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 

Repository files navigation

js logo

JavaScript Almanac

Best JavaScript Idioms and some shortcusts

Sites

Instead of this

if("foobar".indexOf("foo") > -1) 

Do this

if(~"foobar".indexOf("foo"))

Instead of this

var foo = Math.floor(2.333)

Do this

var foo = ~~2.333

Instead of this

var foo = parseFloat("12.4")
var bar = parseInt("12", 10)

Do this

var foo = +"12.4"
var bar = +"12"

Instead of this

if(isNaN(foo))

Do this

if(foo != foo)

Instead of this

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

Do this

!function(){ ... }()

Convert anything to a boolean by prefixing it with !!

var isFoo = !!foo

null vs undefined

Hoisting

Function Expression vs Function Declaration

  • Declaration: defining a function for later use
    • hoisted to the top
function foo(){
    console.log("foo here");
}

// called with the name of the function
foo();
  • Expression: storing a function in a variable
    • not hoisted to the top
var x = function (a, b) {return a * b};

// called using the vairable name
x(4,5);//20

[[Prototype]] vs __proto__ vs prototype

The new keyword in javascript

They all does the same thing: Tomato Potato

const abc = {
  salute: "",
  greet: function() {
    this.salute = "Hello";
    console.log(this.salute); //Hello
    const setFrench = function(newSalute) {
      this.salute = newSalute;
    };
    setFrench("Bonjour");
    console.log(this.salute); //Bonjour
  }
};

setTimeout(abc.greet.bind(abc));        // setTimeout + bind
setTimeout(()=> abc.greet.call(abc));   // setTimeout + call 
setTimeout(()=> abc.greet.apply(abc));  // setTimeout + apply

setInterval(abc.greet.bind(abc));        // setInterval + bind 
setInterval(()=> abc.greet.call(abc));   // setInterval + call 
setInterval(()=> abc.greet.apply(abc));  // setInterval + apply

(abc.greet)();                          // function wrap (only)
(abc.greet.bind(abc))();                // bind  + function wrap
(() => abc.greet.call(abc))();          // call  + function wrap
(() => abc.greet.apply(abc))();         // apply + function wrap

JQuery and Ajax

  • Document Ready Function: A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
$(document).ready(function(){})

Shorthand equivalent(alias):

$(function(){})

image

JavaScript equivalent of the JQuery code above

image

JS versions and release dates: source: greycampus

 - ES1 1997
 - ES2 1998
 - ES3 1999
 - ES4 Abandoned
 - ES5 2009
 - ES6 2015
 - ES7 2016
 - ES8 2017
 - ES9 2018

Releases

No releases published

Packages

No packages published