Monday, December 30, 2013

JavaScript: The Good Parts

This post is inspired and quotes from the book JavaScript: The Good Parts by Douglas Crockford. Douglas is well known in the community around JavaScript. Douglas, for example, created a tool JSLint.


With my bad English I first understood the title "The Good Parts" in the sense of JavaScript is good to be friends. After reading the introduction, I realized that it was something else.


“Most programming languages contain good parts and bad parts. I discovered that I could be a better programmer by using only the good parts and avoiding the bad parts. After all, how can you build something good out of bad parts?”


Numbers

The global NaN property is a number value representing Not-A-Number that is the result of an operation that cannot produce a normal result. NaN is not equal to any value, including itself.


Testing against NaN


Equality operator (== and ===) cannot be used to test a value against NaN. Use Number.isNaN() or isNaN() instead.


NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true


The value Infinity represents all values greater than 1.79769313486231570e+308.


String

The \u convention allows for specifying character code points numerically.

"A" === "\u0041"


Boolean

Here are the falsy values:

• false
• null
• undefined
• The empty string ''
• The number 0
• The number NaN


All other values are truthy, including true, the string 'false', and all objects.


Statements

It is usually necessary to test object.hasOwnProperty(variable) to determine whether the property name is truly a member of the object or was found instead on the prototype chain.


for (myvar in obj) {
if (obj.hasOwnProperty(myvar)) {
}
}


Expressions

The values produced by typeof are 'number', 'string', 'boolean', 'undefined', 'function', and 'object'. If the operand is an array or null, then the result is 'object', which is wrong.

Object Literals

The quotes around a property’s name in an object literal are optional if the name would be a legal JavaScript name and not a reserved word. So quotes are required around "first-name", but are optional around first_name.


var person = {
"first-name": "Jerome",
last_name: "Howard"
};


Retrieval

The undefined value is produced if an attempt is made to retrieve a nonexistent member:

stooge["middle-name"] // undefined
flight.status // undefined
stooge["FIRST-NAME"] // undefined


The || operator can be used to fill in default values:

var middle = stooge["middle-name"] || "(none)";
var status = flight.status || "unknown";


Attempting to retrieve values from undefined will throw a TypeError exception. This can be guarded against with the && operator:

flight.equipment // undefined
flight.equipment.model // throw "TypeError"
flight.equipment && flight.equipment.model // undefined


Enumeration

The for in statement can loop over all of the property names in an object. The enumeration will include all of the properties including functions and prototype properties that you might not be interested in so it is necessary to filter out the values you don’t want. The most common filters are the hasOwnProperty method and using typeof to exclude functions:


var name;
for (name in another_stooge) {
if (typeof another_stooge[name] !== 'function') {
document.writeln(name + ': ' + another_stooge[name]);
}
}


If you want to assure that the properties appear in a particular order, it is best to avoid the for in statement entirely and instead make an array containing the names of the properties in the correct order:


var i;
var properties = [
'first-name',
'middle-name',
'last-name',
'profession'
];
for (i = 0; i < properties.length; i += 1) {
document.writeln(properties[i] + ': ' +
another_stooge[properties[i]]);
}


Delete

The delete operator can be used to remove a property from an object. It will remove a property from the object if it has one. It will not touch any of the objects in the prototype linkage.


another_stooge.nickname // 'Moe'
// Remove nickname from another_stooge, revealing the nickname of the prototype.


delete another_stooge.nickname;
another_stooge.nickname // 'Curly'


Function Object

Functions in JavaScript are objects. Objects are collections of name/value pairs having a hidden link to a prototype object. Objects produced from object literals are linked to Object.prototype. Function objects are linked to Function.prototype.

Arguments

A bonus parameter that is available to functions when they are invoked is the arguments array.


var sum = function ( ) {
var i, sum = 0;
for (i = 0; i < arguments.length; i += 1) {
sum += arguments[i];
}
return sum;
};


document.writeln(sum(4, 8, 15, 16, 23, 42)); // 108

Exception

var add = function (a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw {
name: 'TypeError',
message: 'add needs numbers'
};
}
return a + b;
}


var try_it = function ( ) {
try {
add("seven");
} catch (e) {
document.writeln(e.name + ': ' + e.message);
}
}


Augment

For example, by augmenting Function.prototype, we can make a method available to
all functions:


Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};

Curry

Functions are values, and we can manipulate function values in interesting ways. Currying allows us to produce a new function by combining a function and an argument:


var add1 = add.curry(1);
document.writeln(add1(6)); // 7


Memoization

We will keep our memoized results in a memo array that we can hide in a closure. When our function is called, it first looks to see if it already knows the result. If it does, it can immediately return it:


var fibonacci = (function ( ) {
var memo = [0, 1];
var fib = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fib(n - 1) + fib(n - 2);
memo[n] = result;
}
return result;
};
return fib;
}( ));


Array

The length property is the largest integer property name in the array plus one. This is not necessarily the number of properties in the array:


var myArray = [];
myArray.length // 0


myArray[1000000] = true;
myArray.length // 1000001
// myArray contains one property.


delete
Since JavaScript’s arrays are really objects, the delete operator can be used to remove
elements from an array:


delete numbers[2];
// numbers is ['zero', 'one', undefined, 'shi', 'go']


numbers.splice(2, 1);
// numbers is ['zero', 'one', 'shi', 'go']


isArray
JavaScript does not have a good mechanism for distinguishing between arrays and
objects. We can work around that deficiency by defining our own is_array function:


var is_array = function (value) {
return value && typeof value === 'object' && value.constructor === Array;
};


Unfortunately, it fails to identify arrays that were constructed in a different window or frame. If we want to accurately detect those foreign arrays, we have to work a little harder:


var is_array = function (value) {
return Object.prototype.toString.apply(value) === '[object Array]';
};


Bonus - Shuffle array
yourArray.sort(function() { return 0.5 - Math.random() });



Bad parts
JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. The rules by which they do that are complicated and unmemorable. These are some of the interesting cases:


'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true



Conclusion

The book has about 150 pages and is a fast reading. Perhaps you encounter language features that are at least strange and you will be able to avoid such parts.


It might interest you

  • JavaScript Garden - documentation about the most quirky parts of the JavaScript programming language.

Reference

  • CROCKFORD, Douglas. JavaScript: the good parts [online]. 1st ed. Sebastopol: O´Reilly, 2008, xiii, 153 s. [cit. 2014-01-04]. ISBN 978-0-596-51774-8.


Thursday, November 28, 2013

Become a freelancer

A freelancer does not have an easy life. Nobody does his work for him. Fighting against and with non-paying customers is exhausting. But there are significant advantages too. Your destiny is in your hands. You are free! And this is the most.

In this post I want to summarize advantages and disadvantages of work as freelance.

The most immediate impact on me when I decided to go out on my own was
that feeling of empowerment—that I was the one who got to determine my path.
That, in itself, was the biggest advantage for me—the feeling that I was in control
of my future, that I was the decision-maker.
Derek Featherstone

What do you need to become a freelancer?

Work hard

I think that gives a good job is the most important ability for freelancer. It's sad but it's true - you can not become a freelancer without honest, quality and hard work.

Self confidence

You must believe that you are God :) .That you are able to learn new things. Not only from your field, but also accounting, sales, marketing, social relations. Often you get the job you've never done before. Work with the new framework, a new technique. Your confidence and belief that you can do it is what will allow you to say yes. You know that you can do it.

Money stock

At the start you need to have saved up for about half a year in advance. It adds you confidence and peace of mind. You do not need to take every job.

A good place to work

This is very important. You need uninterrupted room. You can not work in the nursery, listen to children playing and his wife's roar. You need high-quality hardware and software and ergonomic chairs.

Fixed working hours

It sounds strange, but without a fixed order and mode can not be a freelancer. Sometimes it is necessary to work overtime, but it must not be the rule. How do you divide the working time is up to you. After your working time forget about work. Pay attention to your family, listen to music, read books, play sports …

Bookkeeping

It is very important to keep track of your finances. Prepare yourself for the fact that it sucks. Watch the payment, issue invoices, crave payments, argue, fight.

Marketing

Your working life is not just coding. Keep your website polished and add there every new reference to his last work. Respond to emails and phone calls. Handing out your business cards. Ask satisfied customers for references. If you have class organize a lecture, or go up to the local conference.

Stay up to date
There are a lot of good books and interesting articles on Internet. Set aside one hour a day to reading them. It is a a deposit to your future.

Good luck!

Wednesday, October 30, 2013

REST API

I recently read a new book RESTful Web APIs by Leonard Richardson and Mike Amundsen. A key notes about REST API I presented in this post.

REST

Representational State Transfer (REST) is not a protocol, a file format, or a development framework. REST is an architectural style. Another definition says that REST is a set of design constraints. REST was initially described in the context of HTTP, but it is not limited to that protocol. RESTful architectures may be based on other Application Layer protocols if they already provide a rich and uniform vocabulary for applications based on the transfer of meaningful representational state.

The REST architectural style describes the following six constraints applied to the architecture:

Client–server
Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable. Servers and clients may also be replaced and developed independently, as long as the interface between them is not altered.

Stateless
Each request from any client contains all of the information necessary to service the request, and session state is held in the client.

Cacheable
As on the World Wide Web, clients can cache responses. Well-managed caching partially or completely eliminates some client–server interactions, further improving scalability and performance.

Layered system
A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches. They may also enforce security policies.

Uniform interface
The uniform interface between clients and servers, simplifies and decouples the architecture, which enables each part to evolve independently.

Code on demand - optional
Servers can temporarily extend or customize the functionality of a client by the transfer of executable code. Examples of this may include compiled components such as Java applets and client-side scripts such as JavaScript.

Resources and representation

Individual resources are identified in requests, for example using URIs in web-based REST systems. The resources themselves are conceptually separate from the representations that are returned to the client. For example, the server does not send its database, but rather, some HTML, XML or JSON that represents some database records.

Although a resource can be anything at all, a client can’t do whatever it wants to a resource. There are rules. In a RESTful system, clients and servers interact only by sending each other messages that follow a predefined protocol.

The HTTP standard defines eight different kinds of messages.

GET
The client sends a GET request to ask for a representation of a resource, identified by a URL. The GET is defined as a safe HTTP method.  It’s just a request for information.

The most common response code to a GET request is 200 (OK). Redirect codes like 301 (Moved Permanently) are also common.

DELETE
The client sends a DELETE request when it wants a resource to go away. If a DELETE request succeeds, the possible status codes are 204 (No Content), 200 (OK); and 202 (Accepted).

If a client tries to GET a resource that has been DELETEd, the server will return an error response code, usually 404 (Not Found) or 410 (Gone).

DELETE is not a safe method. Once you delete a resource, it’s gone. The resource state has permanently changed. You can send another DELETE request, and you might get a 404 error, but the resource state is exactly as it was after the first request. The resource is still gone. That’s idempotence.

POST
Sending a POST request to a resource creates a new resource. When a client sends a POST request, it sends a representation of the resource it wants to create in the request’s entity-body. The most common response code to a POST request is 201 (Created). The Location header lets the client know the URL to this new resource. Another common response code is 202 (Accepted), which means that the server intends to create a new resource based on the given representation, but hasn’t actually created it yet.

The POST method is neither safe nor idempotent. Every POST create a new resource.

PUT
A PUT request is a request to modify resource state. The client takes the representation it got from a GET request, modifies it, and sends it back as the payload of a PUT request. If the server decides to accept a PUT request, the server changes the resource state to match what the client says in the representation, and usually sends either 200 (OK) or 204 (No Content).

PUT is idempotent, just like DELETE. If you send the same PUT request 10 times, the result is the same as if you’d only sent it once.

HEAD
HEAD is a safe method, just like GET. The server is supposed to treat a HEAD request exactly the same as a GET request, but it’s not supposed to send a an entity-body—only the HTTP status code and the headers.

Using HEAD instead of GET may not save any time (the server still has to generate all the appropriate HTTP headers), but it will definitely save bandwidth.

OPTIONS
OPTIONS is a primitive discovery mechanism for HTTP. The response to an OPTIONS request contains the HTTP Allow header, which lays out which HTTP methods the resource supports.

200 OK
Allow: GET PUT DELETE HEAD OPTIONS

PATCH
Representations can get really big. “Modify the representation and PUT it back” is a simple rule, but if you just want to change one little bit of resource state, it can be pretty wasteful. The PUT rule can also lead to unintentional conflicts with other users who are modifying the same document. It would be nice if you could just send the server the parts of the document you want to change.

The PATCH method allows for this. Instead of PUTting a full representation, you can create a special “diff ” representation and send it to the server as the payload of a PATCH request.

The best response codes for a successful PATCH are the same as for PUT and DELETE: 200 (OK) if the server wants to send data (such as an updated representation of the resource) along with its response, and 204 (No Content) if the server just wants to indicate success.

PATCH is neither safe nor idempotent.

Remember that PATCH is not defined in the HTTP specification. It’s an extension designed specifically for web APIs, and it’s relatively recent (RFC 5789 was published in 2010). This means that tool support for PATCH, and for the diff
documents it uses, is not as good as the support for PUT.

LINK and UNLINK
LINK and UNLINK manage the hypermedia links between resources. These methods are defined in an Internet-Draft, and until that draft is approved as an RFC, tool support for them will be even worse than for PATCH.

LINK and UNLINK are idempotent, but not safe.