Monday, February 29, 2016

Summary - JavaScript in Work

1. Get keys of an object
Object.keys(<object>); //return an array,  no order guarantee, needs to be sorted when need

2. JSON <-> String
   JSON.parse(<string>);
   JSON.stringify(<json obj>);

3. Loop array
<array>.forEach(function(element, index, array){
//xxxx
});

4. Rename keys in an object

for(var key in object){
    object[newKey] = object[key];
    delete object[key];
}

Friday, February 12, 2016

Detecting Properties

The "if" condition evaluates to false if the value is falsy (null, undefined, 0, NaN, '')

Thus, when checking if a property exists, could use "in" method (check both own and prototype properties) to check:

var person = {};
console.log("name" in person); //false;

If only wants to see if it is its own property, using hasOwnProperty();

Function

The "length" property of a function indicates the function's arity (the number of parameters it expects)

function reflect(value){
       return value;
}

console.log(reflect.length) //1

Primitive and Reference Types

Primitive Types:
1. number
2. string
3. boolean
4. null -> don't have methods
5. undefined -> don't have methods

Built-in Reference Types:
1. Array
2. Date
3. Error
4. Function
5. Object
6. RegExp

* for all reference types except for Function (return "function"), typeof returns "object".