Saturday, January 9, 2016

JavaScript Object: Introduction


There are 2 very important concept in JavaScript: Object and Function. This tutorial will cover JavaScript Object.

Object, in JavaScript, can be viewed as a container that stores a collection of values. Object can store both primitive values and object values.

The following are some characteristics of an object:
  • key-value pair
    • key can be either string or number
    • value can either be a primitive value or object value
    • key is known as "property"
  • mimic known data structure: "hash", "hashtable", "dictionary", "map"
  • dynamic
    • property can be added at any time
    • property can be removed at any time
There are 3 ways to create an object in JavaScript: 

Creating an object: object literal
var car = {
  make : "Honda",
  model: "Civic",
  attributes: {
     doors: 4,
     passengers: 5 // comma not needed here to end the key-value pair
  } // comma not needed here to end the key-value pair
};
Rules for object literal creation: 
  • Starts with { and ends with };
  • key followed by colon followed by its value and a comma (unless it is the last key-value pair)

Creating an object: new keyword
var car = new Object();
car.make = "Honda";
car.model = "Civic";
car.attributes = new Object();
car.attributes.doors = 4;
car.attributes.passengers = 5;
Rules for new keyword object creation:
  • Use the keyword new
  • Use a "special" function (in this case, Object) known as "constructor"
  • Add key-value pairs one by one
    • these pairs can also be initialized inside the constructor just like in mainstream Object Oriented programming languages

Creating an object: Object.create()
var car = Object.create(Object.prototype,{
  make: { value: "Honda" },
  model: { value: "Civic" },
  attributes: { 
    value: Object.create(Object.prototype,{
      doors: { value: 4 },
      passengers: { value: 5}
    })
  }  
});
Rules for Object.create() object creation:
  • Use "static" method "create()" of Object.
  • First parameter: the prototype object that the new object will be based on
  • Second parameter: an object that define the properties attributes, in this particular example, we initialized its "value" attribute (more detail in another blog post)

When to use each technique of Object creation

Use object literal technique when:
  • you need a one-off data structure (similar to C-struct) on-the-fly (not a template)
  • you need a simple singleton-like object (unfortunately a mutable singleton)

Use new keyword when:
  • you need an instance of an object (analogous with mainstream OOP language like Java or C#)
  • you need multiple instances of a type of an object with different values
  • more details will be covered in another article that covers "prototype" as well.

Use Object.create() when:
  • you need more control over the property attributes (will be covered in another article) of the newly created instance of an object
  • for example: set the car.make property to be read-only (can only read, but can't modify)

Accessing and Modifying properties

There are 2 ways to access/modify a property of an object (assuming the property can be accessed and modified): dot notation or square bracket notation.

Dot Notation example:
console.log(car.make); // "Honda"
car.make="Toyota";
console.log(car.make); // "Toyota"
Square Bracket example:
console.log(car["make"]); // "Honda"
car["make"]="Toyota";
console.log(car["make"]); // "Toyota"

When to use each technique of Accessing/Modifying properties

Use dot notation when:

  • any time you can
  • know the property name before hand

Use square bracket when:

  • property name is pre-computed or pre-calculated during run-time
  • creating an object that maps a range of keys/properties to a set of values
    • for example, mapping A-Z or 0-9 to a set of values

Using Number as Key/Property Name

Technically it is legal to use number or a string representation of number as the key/property name but in general, try not to as it may tricked people to think that the object type is an array.

For example:
var one = { 1 : "One" }; 
var two = { "2": "Two" };
console.log(one[1]);  // "One"
console.log(one["1"]); // "One"
console.log(two[2]); // "Two"
console.log(two["2"]); // "Two"

// The following will throw SyntaxError error,
// a number is not a legal identifier
console.log(one.1);
console.log(two.2);

Summary

An object is an aggregate of property-value pairs. There are 3 ways to create an instance of an object in JavaScript. Each technique is useful in certain situations. There are 2 ways to access or modify the property value. In JavaScript, the key/property name can be a number.

Tuesday, January 5, 2016

JavaScript Operators: Introduction


In this article, I'd like to cover briefly the JavaScript operators. JavaScript operators can be grouped into 3 categories: unary, binary, and ternary operator.

1 Unary Operator

The unary operator only requires 1 value in order to invoke it. The unary operator takes form of both symbols and word. Its members are as follows:
2. Binary Operator

The binary operator would need 2 values in order to evaluate its results: one value before the operator and one value after the operator. The members of the binary operator category can be grouped further by its capability:
3. Ternary Operator

The ternary operator works on 3 values and it only has one member, the question mark and colon operator:
 var answer = true ? "True" : "False";
The ternary operator is also known as the conditional operator.

I will discuss most of these operators in future posts.

Sunday, January 3, 2016

JavaScript Types



JavaScript has 6 basic data types per ECMAScript 5.1. These data types can be categorized into 2 groups: primitive value and object.

The six basic data types are:
0. Primitive values

Primitive values work like in any other programming languages: they are immutable (can't be changed) and can only store one value at any given time.

JavaScript only supports one type of Number: floating-point (other mainstream programming languages support integer, float, and double at least). 

Number has 3 extra special members: Infinity, -Infinity, NaN (Not a Number). 

In order to test positive and negative Infinity, a built-in Number.MAX_VALUE and Number.MIN_VALUE should be used. Anything greater than Number.MAX_VALUE is considered positive infinity while anything less than Number.MIN_VALUE is considered negative infinity. 

For example:
var positiveInfinity = Infinity;
if(Number.MAX_VALUE < positiveInfinity){
  console.log('Positive Infinity');
}

var negativeInfinity = -Infinity;
if(Number.MIN_VALUE > negativeInfinity){
  console.log('Negative Infinity');
}

Verifying that a number is NaN is slightly simpler: use the built-in Number.isNan() method.

2. Boolean

Boolean has exactly 2 values: true or false.

3. String

String represent text. JavaScript supports double (e.g.: "This is a string") and single quotes (e.g.: 'This is also a valid string') to denotes a string literal. String contains a series of characters in which each character is of 16-bit unsigned integer values (hence JavaScript string supports UTF-16).

NOTE: The common practice is to use single quote whenever possible.

4. Undefined

Undefined has exactly one value: undefined. Undefined is not the same with Null. Undefined refers to a state in which a variable is not even declared (i.e.: can't find where the variable has been declared with "var" keyword anywhere in your script).

5. Null

Null has exactly one value: null. Null is not the same with Undefined. Null refers to a state in which variable is declared (i.e.: var x;) but not initialized to a value (or initialized to null).

6. Object

Object in JavaScript is a collection of properties. By comparison with other mainstream programming languages, JavaScript object is more like a Dictionary or a Hash table or an Associative Array.

A function is a special type of Object that can be called and executed. Function contains additional property that act as a marker for the JavaScript interpreter to denote that this particular object is of a function.

Sunday, July 29, 2012

Ubuntu, PostgreSQL, pgAdmin

I've been interested to play with PostgreSQL for a while and it looks like now is the right time to have fun and go mad at it since my new work requires it.

My machine/initial setups is as follows:
  1. Ubuntu Server 12.04 64bit running on VirtualBox (love free stuff!)
  2. PostgreSQL 9.1 as part of Ubuntu Server installation
  3. pgAdmin installed in OSX
I've encountered a few hiccups when trying to connect the pgAdmin to the PostgreSQL server and here are the steps to avoid that in the future.

0. Configuration Files

The locations for the main configuration files specifically for Ubuntu Server is at:
/etc/postgresql/<version>/main 
For example, because at the time of this writing I installed the PostgreSQL 91, the configuration files are located at:
/etc/postgresql/9.1/main
The content of the configuration directory should contain the following files:
enathaniel@ubuntu:/etc/postgresql/9.1/main$ ls -la
total 52
drwxr-xr-x 2 postgres postgres  4096 Jul 29 00:34 .
drwxr-xr-x 3 postgres postgres  4096 Jul 28 23:50 ..
-rw-r--r-- 1 postgres postgres   316 Jul 28 23:50 environment
-rw-r--r-- 1 postgres postgres   143 Jul 28 23:50 pg_ctl.conf
-rw-r----- 1 postgres postgres  4693 Jul 29 00:28 pg_hba.conf
-rw-r----- 1 postgres postgres  1636 Jul 28 23:50 pg_ident.conf
-rw-r--r-- 1 postgres postgres 19250 Jul 29 00:24 postgresql.conf
-rw-r--r-- 1 postgres postgres   378 Jul 28 23:50 start.conf

1. Modify the PostgreSQL configuration file: postgresql.conf

Find the listen_address entry, uncomment if necessary, and modify its value to asterisk (*), which means to bind the PostgreSQL server service (daemon) to any IP Addresses of the server machine:
 listen_address = '*'
The default PostgreSQL installation does not bind itself to any particular IP Address of the server. One can also bind the PostgreSQL server service (daemon) to a specific set of IP Addresses if the server has more than one by using comma between values:
 listen_address = 'localhost, 192.168.0.114' # my server address is 192.168.0.114

2. Modify the PostgreSQL Client Authentication Configuration file: pg_hba.conf

Insert a line to pg_hba.conf file to grant client access to the database.
host    all             all             192.168.0.0/24          md5
In short, the above lines will do the following: grant client, via network connection TCP/IP with or without SSL (host), access to all (first) database for all (second) users from the IP addresses of 192.168.0.0 to 192.168.0.255 and use md5 password encryption.

3. Change password of the postgres user

Access PostgreSQL via command-line "psql" and update the password
enathaniel@ubuntu:/etc/postgresql/9.1/main$ sudo -u postgres psql postgres
psql (9.1.3)
Type "help" for help.

postgres=# \password postgres
Enter new password: 
Enter it again: 
postgres=# \q
The psql command must be run as postgres user (hence the sudo -u postgres) because that is the only user that has an account in the default installation of PostgreSQL.

4. Install adminpack extension

pgAdmin typically would give warning when it detects that the PostgreSQL instance does not have adminpack installed. To install the adminpack extension, the following psql command would do the trick
enathaniel@ubuntu:/etc/postgresql/9.1/main$ sudo -u postgres psql
psql (9.1.3)
Type "help" for help.

postgres=# create extension adminpack
postgres-# \q

5. Connect to PostgreSQL instance from pgAdmin
The following screenshot should give some idea how to connect to the PostgreSQL instance.


Voila, we're done!

PS: Yes, there's no food, fruits, or traveling story in this post.

Monday, July 16, 2012

Summer Freedom Week Day 1

This week will be my last week before I go back to the grind, so we decided to have fun whenever we can. Here are our destinations on the first day of our "Summer Freedom Week!"

1. Granville Island
Granville Island entrance
We  have not been to Granville Island for a while. Our main target here was to have our lunch at "Go Fish".

Unfortunately it wasn't meant to be since they have to go fishing on Monday. So instead of feeling sad and depressed, we took a few pictures since the weather was awesome.
Burrard Bridge at far
Granville Bridge across the other
Must be nice to have a waterfront view apartments, wondering how much a unit may cost your wallet.
Waterfront Apartments
Since we were hungry, we decided to leave Granville Island. Instead of going straight to the parking lot, we went through a few stores for a quick window shopping.
Kids Market
Freaky Eyes on top of Kids Market
Car stickers
We may have buy these stickers soon.

Sometimes Vancouverites amazed us, there are plenty of them enjoying their Monday as if money grows on their backyard. We can only guess what they do for a living.
Woofles & Meowz
Woofles & Meowz? The Z comes from the 90's? Kidding aside, too bad we don't have pets.
Weird Sign
Came across one shop that we have no idea what it sells because we couldn't find the entrance door nor we can see the inside. Who knows eh..?
Yes, I'm the Boss
Boss sleeps throughout the day, leaving us to enjoy to the fullest!

2. SalaThai

We went to SalaThai for our lunch because of the proximity and also ever since one of our favorite Thai restaurants near our home has closed due to a new apartment complex is about to be built there, we haven't had Thai.
A Bowl of Soup (No Name)
Wife ordered Beef Phanaeng Curry that comes with this unknown bowl of soup (a bit sour and slightly spicy).
Beef Phanaeng Curry
While I opted for my usual: Lard Na
Lard Na
The Lard Na was a bit unusual because typically Lard Na isn't that soupy. But it tastes good, so who am I to judge?
Calamari
The calamari was a late order because my stomach was not quite there yet and the Boss demanded his lunch as well: MILK PLEASE! Lucky we're prepared.

Overall the lunch was quite nice and the price was reasonable.
Roaming Dragon Food Truck
Came across one of those "hip" food truck. The last time I tried a food from a truck, it was okay but overpriced. Some of my friends have had similar experience. Speaking of food truck, have you ever watched the Eat St. TV show airing at the Food Network?

3. Vancouver Public Library
Vancouver Public Library
VPL was our last destination before heading for home. We had a few books of our interest that we wanted to borrow.

That's it for our Summer Freedom Week day one adventure. Day two is coming up tomorrow!