Wednesday, February 25, 2015

Overview

Table of content

  1. String
  2. Callbacks
  3. Promises
  4. Context
  5. Sorting
  6. Bit Manipulation
  7. Math
  8. Latest Version




1. String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"A string  "
.toLowerCase()        // "a string  "
.toUpperCase()        // "A STRING  "

//takes a delimiter
.split("")            // ['A', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', ' ']

//with split ^
.join()               // "A string  "

//takes startPos endPos
.substring(2, 4)      // "st"

.indexOf("str")       // 2

.trim()               // "A string"

.replace("string", "blah"); // "A blah  "

.match(/a str.*/i)    // "A string  "

//takes in a position
.charAt(0)            // "A"
.charCodeAt(0)        // 65

//takes in base
4.toString(2)         // 110




2. Callbacks

Callbacks are a big part of javascript.

1
2
3
4
5
6
7
8
9
function callFuncOnFive(cb){
  return cb(5);
}

var returnedValue = callFuncOnFive(function(num){
  return num * num;
});

console.log(returnedValue); // 25 (5*5)




3. Promises

Promises allow you to flatten a callback pyramid

1
2
3
4
5
6
7
8
9
10
11
12
13
//using callbacks
function one() {
  function two() {
    function three() {
      
    }
  }
}

//using promises
promiseOne()
  .then(promiseTwo)
  .then(promiseThree);

A popular promise library for nodejs is Q

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//it allows you to do many awesome things like
var Q = require("q");


//chain promises
promiseOne()
  .then(promiseTwo)
  .then(promiseThree)
  .then(function() {
    //normal anonymous function
  })
  .fail(function(error) {
    //can handle error
  })
  .done();
  
  
//Create promises from async methods
Q.ninvoke(obj, "asyncMethod", {
    param1: "parameter"
  })
  .then(function(resultFromAsyncMethod) {
    //do stuff
  });
  

//Use callbacks and promises together
function async(err, val){
  //this is a async callback
  var deferred = Q.defer();
  
  if (err) {
    deferred.reject(new Error(err));
  } else {
    deferred.resolve(val);
  }
  return deferred.promise;
}


//A value can be turned into a promise
Q({ x:5 })
 .then(function(val){
  //val == 5
 });




4. Context

Hoisting

Javascript hoists variable declarations

1
2
3
4
5
6
7
8
9
10
function blah() {
  var a = 1;
}

//is the same as

var a;
function sameBlah() {
  a = 1;
}

It also hoists up function declarations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function outerFunc() {
  //How did it work?? I called innerFunc before initialization it!
  innerFunc();

  function innerFunc() {
    console.log(5);
  }
}

//is not the same as
function outerFunc() {
  x(); //won't work

  var x = function() {
    console.log(5);
  }
  
  x(); //will work
}

Bind method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//instead of doing something like this
obj = {
...
  render: function () {
    var that = this; //have to do this every time...
    this.getAsyncData(function () {
      that.specialFunction();
      that.anotherSpecialFunction();
    });
  }
...
};


//We do
obj = {
...
  render: function () {
    this.getAsyncData(function () {
      this.specialFunction();
      this.anotherSpecialFunction();
    }.bind(this)); 
    //This bind means that when getAsyncData gets called
    //this === obj
  }
...
};




5. Sorting

Sorting in javascript is easy

1
2
3
4
5
6
7
8
9
10
var sorted = [4, 3, 5, 2, 1].sort(function(a, b) {
  return a-b;
});
console.log(sorted) // [1, 2, 3, 4, 5]


var reversed = [4, 3, 5, 2, 1].sort(function(a, b) {
  return b-a;
});
console.log(reversed) // [5, 4, 3, 2, 1]




6. Bit Manipulation

Bit operators

Operation name Javascript symbol Example Result Explanation
AND & 7 & 5 5 111 & 101 = 101
OR | 8 | 3 11 1000 | 0011 = 1011
XOR ^ 15 ^ 5 10 1111 ^ 0101 = 1010
Right Shift >> 7 >> 1 3 111 >> 1 = 011
Not ~ ~0 -1 ~000 = 111 which is 2's complement -1




7. Math

1
2
var x = Math.random() // float [0, 1[
Math.floor((Math.random() * 100) + 1); // int [1, 100[




8. Latest Version

The latest javascript is ECMA6 check out the features.


Random Posts