Saturday, September 12, 2015

Hand out - Javascript - quick facts and best practices

Introduction:
This post is to provide some quick refreshing facts and best practices for those folks who haven't worked on JavaScript for a while. For beginners, it's better to go through the basic/advance tutorials first and check back with this.

Some quick facts
  • External JavaScript Advantages
    • Separation of concerns HTML and code
    • HTML and JavaScript can be maintained and read easily
    • Cached JavaScript files can speed up page loads
  • JavaScript Display Possibilities
    • Writing into an alert box, using window.alert()
    • Writing into the HTML output using document.write()
    • Writing into an HTML element, using innerHTML
    • Writing into the browser console, using console.log()
  • JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments.
  • All JavaScript identifiers are case sensitive

  • JavaScript ignores multiple spaces. Add white space to script to make it more readable

  • A variable declared without a value will have the value undefined. If re-declare a JavaScript variable, it will not lose its value

  • JavaScript Objects - JavaScript objects are written with curly braces. Object properties are written as name:value pairs, separated by commas
    •  Example: var employee = {name:”Riaz”, address:”Ashland”};
    •  Accessing object properties:
      • objectName.propertyName
      • objectName[propertyName]
    • Accessing object method:
      • objectName.methodName();
      • calling objectName.methodName without () will return function definition
    •  Using an Object Constructor - Sometimes we like to have an "object type" that can be used to create many objects of one type.
      • Example: 
      • function person(first, address) {this.firstName = first;this.address = address;}
        var p1 = new person("Riaz", “Ashland”);
        var p2 = new person("Rahat", “Dhaka”);
    • Object prototype - All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the Object.prototype.
    • Adding Properties and Methods to Objects –
      • Add new properties (or methods) to an existing object
        • Example: p1.age = 20; This will add age property to p1 object (above example) but p2 will not have it.
      • Add new properties (or methods) to all existing objects of a given type. This can be done by adding property or method directly in the constructor function.  
      • Add new properties (or methods) to an object prototype - using prototype keyword on an object.
        • Example: p1.prototype.age = 20; This code will add age property to both p1 and p2 objects, though p1.age will have valid value only.
    • JavaScript Objects are Mutable, addressed by reference, not by value. var x = y; The object x is not a copy of y. It is y. Both x and y points to the same object. Any changes to y will also change x, because x and y are the same object
    • In JavaScript, all objects have the valueOf() and toString() methods
    • JavaScript for/in statement loops through the properties of an object
  • typeof operator to find the type of a JavaScript variable
    • typeof "Riaz"                // Returns string
    • typeof 10                      // Returns number
    • typeof false                  // Returns boolean
    • typeof [1,2,3,4]           // Returns object
    • typeof {name:”Riaz”, address:”Ashland”} // Returns object
  • undefined - a variable without a value, has the value undefined. The typeof is also undefined.

  • Null - is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object.
    • Difference Between Undefined and Null
      • typeof undefined             // undefined
      • typeof null                          // object
      • null === undefined          // false
      • null == undefined            // true

  • JavaScript Function
    • Function Invocation - the code inside the function will execute when "something" invokes (calls) the function using operator ():
      • When an event occurs (when a user clicks a button)
      • When it is invoked (called) from JavaScript code
      • Automatically (self invoked)

  • Javascript event
    • list of some common HTML event
      • onchange - An HTML element has been changed
      • onclick - The user clicks an HTML element
      • onmouseover - The user moves the mouse over an HTML element
      • onmouseout - The user moves the mouse away from an HTML element
      • onkeydown - The user pushes a keyboard key
      • onload - The browser has finished loading the page
      • etc...

  • Javascript Array
    • Create array
      • var arrayName = [“item1”, “item2”, ….];
      • var arrayName = new Array(“item1”, “item2”, ….);
    • Array can Have Different Objects in it
    • Array Methods
      • Join() – joins all array elements into a string
      • Push() – add element at the end
      • Pop() – removes last element
      • sort() –
      • reverse() –
      • concat() - creates a new array by concatenating two arrays
      • etc..

  • Javascript regular expression - (more on regular expression)
    • A regular expression is a sequence of characters that forms a search pattern.
    • Syntax
      • /pattern/modifier
    • Methods
      • search() - uses an expression to search for a match, and returns the position of the match.
      • replace() - returns a modified string where the pattern is replaced.
      • test() - searches a string for a pattern, and returns true or false, depending on the result
    • Modifier
      • i - Perform case-insensitive matching
      • g - Perform a global match (find all matches rather than stopping after the first match)
      • m - Perform multiline matching
    • Patterns
      • Brackets are used to find a range of characters
        • example: [abc] [0-9]
      • Metacharacters are characters with a special meaning
        • \d - find a digit
        • \s - find a whitespace character
        • \b - find a match at the beginning or at the end of a word
        • etc...
      • Quantifiers define quantities:
        • n+ - Matches any string that contains at least one n
        • n* - Matches any string that contains zero or more occurrences of n
        • n? - Matches any string that contains zero or one occurrences of n


Best practices:
  • Using document.write() after an HTML document is fully loaded, will delete all existing HTML
  • It is a good idea to place scripts at the bottom of the body element. This can improve page load, because HTML display is not blocked by scripts loading.
  • Avoid String, Number, and Boolean objects. They complicate code and slow down execution speed.
  • If a value assigned to a variable that has not been declared, it will automatically become a GLOBAL variable.
  • Avoid Global Variables - Global variables and functions can be overwritten by other scripts.
  • Always Declare Local Variables - Local variables must be declared with the var keyword, otherwise they will become global variables.
  • It is a good coding practice to initialize variables when you declare them
  • Use === Comparison - the == comparison operator always converts (to matching types) before comparison. The === operator forces comparison of values and type.
  • JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type. Numbers can accidentally be converted to strings or NaN.
  • Don't Use new Object()
    • Use {} instead of new Object()
    • Use "" instead of new String()
    • Use 0 instead of new Number()
    • Use false instead of new Boolean()
    • Use [] instead of new Array()
    • Use /()/ instead of new RegExp()
    • Use function (){} instead of new function()
  • If a function is called with a missing argument, the value of the missing argument is set to undefined. Undefined values can break code. It is a good habit to assign default values to arguments.
  • With JavaScript, null is for objects, undefined is for variables, properties, and methods. To be null, an object has to be defined, otherwise it will be undefined
  •  Only modify own prototypes. Never modify the prototypes of standard JavaScript objects
  • Reduce DOM Access - Accessing the HTML DOM is very slow, compared to other JavaScript statements. If a DOM element needs to access several times, access it once, and use it as a local variable
  • Global variables (or functions) can overwrite window variables (or functions). Any function, including the window object, can overwrite global variables and functions.

Resources:
  1. http://www.w3schools.com/js
  2. http://peerprogrammer.blogspot.com/2015/09/hand-out-javascript-regular-expression.html

No comments: