Wednesday, November 19, 2014

JavaScript notes - Part 2

This post is in continuation of this one http://tunephp.blogspot.com/2014/11/javascript-notes-part-1.html. It will contain notes about JavaScript Inheritance, Arrays, Regular Expressions, Style, Beautiful Features, Awful parts and Bad Parts.

Inheritance

  1. JavaScript being a loosely typed never casts. What matters about object is what it can do, not what it is descended from.
  2. Every function gets a prototype object because the language does not provide a way of determining which functions are intended to be used as constructors. The constructor property is not useful, it is the prototype object that is important.
  3. If all of the state of an object is private then the object is tamper-proof. Properties in the object can be replaced or deleted, but the integrity of the object is not compromised.
  4. If we create object in functional style and all of the methods of the object make no use of "this" or "that" then the object is durable. A durable object is simply a collection of functions that act as capabilities. A durable object cannot be compromised.

Arrays

  1. JavaScript has an object that has some array like characteristics. It converts array subscripts into string that are used to make properties. It is significantly slower than a real array.
  2. Arrays have useful set of built in methods than objects.
  3. Arrays in JS can contain any mixture of values. example: var myArray = ['', 0, undefined, "hello", null, {'key': 'value'}, [0, 1, 2, 3]];
  4. Every array has a length property and length is not an upped bound. If you store an element with a subscript that is greater than or equal to the current length the length will increase to contain the new element. There is no array bounds error.
  5. The length is the largest property name in the array plus one, but not necessarily the number of properties in the array. example: var myArray = []; myArray[1000000] = true; myArray.length = 1000001; // myArray contains one property
  6. The length can be set explicitly. Making then length larger does not allocate more space for the array. Making the length smaller will cause all properties with a subscript that is greater than or equal to the new length to be deleted.   A better way to add new element is to use push() function.
  7. Arrays are objects so the delete word can be used to delete element in an array. That leaves a hole but you can use splice() method to cleanly remove it from an array or to replace it with new one.
  8. Since arrays are objects "for in" statement can be used to iterate over the elements. The order is not necessarily incremental, so properties from the prototype chain can be dredged up. Use "for" statement instead if the order is important.
  9. Common rule when property names are small sequential integers is to use array, otherwise use object. 
  10. JavaScript cannot differentiate between arrays and objects since arrays are objects. Also we can add custom functions to Array.prototype
  11. It is not useful to use Object.create() on arrays since it creates object but not array. It will not have the length property or other functions that have arrays. 
  12. You can use Array.prototype.slice() method to create shallow copy of a portion of an array into a new array object. example: var myNewArray = myOldArray; myNewArray is not new object containing the same values from myOldArray, it is just a reference to the same myOldArray in memory. That means, changes to myNewArray affect myOldArray. To create new array object with the same values of myOldArray use this command: var myNewArray = myOldArray.slice(0);

Regular Expressions

  1. Many JS features were borrowed from other languages. The syntax is from  Java, functions from Scheme, prototypal inheritance from Self. JS regular expressions were borrowed form Perl.
  2. Regular expressions have significant performance advantage over equivalent string operations in JavaScript.

Style

  1. If a program is able to clearly communicate its structure and its characteristics it is less likely to break when it is modified in the never too distant future. 
  2. JS code is often sent directly the the public. It should always be of publication quality.
  3. Put spaces around all infix operators except for dot (.) and square bracket ([) because they have higher precedence.
  4. Put space after every comma and colon. 
  5. Put at most one statement per line. If statement doesn't fit in one line break it after comma or binary operator.
  6. Always use blocks {} with structured statements like while and if because it is less error prone.
  7. With JS you should always use Kernighan and Ritchie style, putting the { at the end of a line instead of the front because it avoids a horrible design blunder in JS's return statement.
  8. Declare all variables at the top of each function. JS doesn't have a block scope but it has a function scope. 
  9. Never allow switch cases to fall trough to the next case.
  10. Use single global variable to contain one application or library. Every object has its own name-space. Use of closure provides information hiding increasing the strength of your modules.

 Beautiful Features

  1. JS good stuff includes: functions as first class objects, dynamic objects with prototypal inheritance, object literals and array literals.
  2. Features have a specification cost, a design cost and a development cost. There is a testing cost and a reliability cost. The more features there are the more likely one will develop problems or will interact badly with another.
  3. In software systems there is a storage cost which become negligible but in mobile is becoming significant again. (Ascending performance cost because Moor's Law doesn't apply to batteries). Features have documentation cost which increases training cost.

Awful Parts

  1. A global variable is a variable that is visible in every scope. Because global variables can be changed by any part of the program at any time they can complicate the behaviour of the program. Use of global variables degrades the reliability of the programs that use them.
  2. JS requires global variables. JS doesn't have a linker. All compilation units are loaded into a common global object.
  3. Always use var keyword before declaring a variable. It links the new variable with the global "this" if var is not present.
  4. Always out { after return since JS will try to add semi colon after return which can produce bugs. There is no warning, return will return undefined value.
  5. If you have a need to name properties or objects using reserved words use quotes or brackets {} like this object = {case: value}
  6. JS characters are 16-bit  wide. Today Unicode contains characters that can be 32-bit wide. JS considers them as two distinct characters.
  7. typeof null returns 'object'. A better check is my_value === null. null is falsy, all objects are truthy.
  8. typeof /a/ returns 'object' or maybe 'function', it should return 'regexp' but it doesn't.
  9. Always provide parseInt() with radix parameter. example: parseInt("08", 10); It stops when it sees nondigit so parseInt("16") and parseInt("16 tons") produce the same result 16.
  10. The plus (+) operator can concatenate and can add numbers. If you plan to add numbers make sure both operands are numbers.
  11. 0.1 + 0.2 is not equal to 0.3. This is a consequence to having adopted the IEEE Standard for binary  floating point arithmetic (IEEE 754). Fortunately integer arithmetic in floating point is exact, so decimal errors can be avoided by scaling.
  12. NaN is a special quantity defined by IEEE 754. It stands for Not a Number. If NaN is operand in arithmetic operation than NaN will be the result. NaN === NaN returns false while NaN !== NaN returns true.
  13. JS does not have real arrays. There is no need to give them a dimension and they never generate out of bound errors. But their performance can be considerably worse than real arrays. The typeof operator thinks that arrays are objects.
  14. The arguments array is not an array. It is an object with length property and it lacks the array specific methods.
  15. undefined and NaN are not constants. They are global variables and you can change their values. That should not be possible, yet it is. Don't do it. :D
  16. hasOwnProperty() of Object.prototype is a function and it can be replaced with different function or with value that is not a function. Don't do it :D

Bad Parts

  1. Don't use == and !=, use === and !== instead. == and != do a type coercion while === and !== do check the type of operands but don't do type coercion.
  2. "with" statement was intended to provide shorthand when accessing properties of an object. Its results can be unpredictable so avoid it.
  3. eval is evil, don't use it.
  4. Don't use continue
  5. Never leave a fall trough in switch statement.
  6. Avoid using ++ and --, use += and -= instead.
  7. JS is rarely used for bit manipulation. Bitwise operators are far from the hardware and their result is processed slower than in other languages.
  8. Avoid using "new Object" and "new Array", use {} and [] instead. Don't use "new Boolean", "new Number" and "new String"
  9. Avoid using "new" keyword. If you forget to create new object with "new" keyword, the new object will be bound to the global name-space, which is bad.
  10. Avoid using void keyword.

No comments:

Post a Comment