A-Z of JavaScript
Join the DZone community and get the full member experience.
Join For Free Here is an A - Z list of some Javascript idioms and patterns. The idea is to convey in simple terms some features of the actual Javascript language (rather than how it can interact with DOM). Enjoy...
Array Literals
An array literal can be defined using a comma separated list in square brackets.
Arrays in javascript have a wide selection methods including push() and pop(). Suppose the world got taken over by a dictator who wanted to get rid of the last month of the year? The dictator would just do...
And of course, the dictator will eventually want to add a month after himself when everyone will have to worship him:
Callbacks
Since functions are objects, they can be passed as arguments to other functions.
In the example above, the chanceCivilisationCallback callback function is invoked by peakOil. Logic could be added to check if the energy returns from solar panels and wind farms were sufficient in which case another callback, other than changeCivilisationCallback could be added.
Configuration Object
Instead of passing around a bunch of related properties...
Use a configuration object
The use of a configuration object makes it makes it easier to write clean APIs that don't need to take a huge long list of parameters. They also means you are less likely to get silly errors if parameters are in the wrong order.
Closures
There are three ways to creats objects in Javascript: using literals, using the constuctor function and by using a closure. What closures offer that the other two approaches do not is encapsulation. Closures make it possible to hide away functions and variables.
Note: The closure is the object literal returned from annoymous function. It "closes" over the count variable. No-one can access it except for the closure. It is encapsulated. The closure also has a sense of state. Note also how the it maintains the value of the counter.
Constructor Functions (Built in)
There are no classes in Javascript but there are construtor functions which use the new keyword syntax similar to the class based object creation in Java or other languages. Javascript has some built-in constructor functions. These include Object(), Date(), String() etc.
Constructor Functions (Custom)
When a function is invoked with the keyword new, it is referred to as a Constructor function. The new means that the new object will have a hidden link to value of the function's prototype member and the this keyword will be bound to the new object.
The convention is that constructor functions should begin with a capital letter. Note: if the new keyword is not used, then the 'this' variable inside the function will refer to the global object. Can you smell a potential mess? Hence why the capital letter convention for constructor functions is used. The capital letter means: "I am a constructor function, please use the new keyword".
Currying
Currying is the process of reducing the number of arguments passed to a function by setting some argument(s) to predefined values. Consider this function.
Suppose, we want a similar function with a fixed "begin" value. Let's say the "begin" value was always 1. We could do:
And then define a variable to be this new function...
Delete Operator
The delete operator can be used to remove properties from objects and arrays.
You cannot delete global variables or prototype attributes.
Dynamic Arguments
Arguments for a function do not have to be specifed in the function definition
The arguments parameter is an array available to functions and gives access to all arguments that were specified in the invocation.
for-in iterations
for-in loops (also called enumeration) should be used to iterate over nonarray objects.
Function declaration
In a function declaration, the function stands on its own and does not need to be assigned to anything.
Function expressions
When function is defined as part of something else's definition, it is considered a function expression.
In the above example, the function is named. It can also be anonymous, in which case the name property will be a blank string.
Functional Inheritance
Functional inheritance is mechanism of inheritance that provides encapsulation by using closures. Before trying to understand the syntax, take an example first. Suppose we want to represent planets in the solar system. We decided to have a planet base object and then several planet child objects which inherit from the base object. Here is the base planet object:
Now for some planets. Let's start with Earth and Jupiter and to amuse ourselves let's add a function for Earth for people to leave and a function to Jupiter for people arriving. Sarah Palin has taken over and things have got pretty bad!!!
Array Literals
An array literal can be defined using a comma separated list in square brackets.
Arrays in javascript have a wide selection methods including push() and pop(). Suppose the world got taken over by a dictator who wanted to get rid of the last month of the year? The dictator would just do...
Callbacks
Since functions are objects, they can be passed as arguments to other functions.
function peakOil(callback) {
//... code
callback(); // the parentheses mean the function is executed!
}
function changeCivilisationCallback(){
//...
}
// Now pass the changeCivilisationCallback to peakOil.
// Note: no changeCivilisationCallback parentheses because it is not
// executed at this point.
// It will be excuted later inside peak oil.
peakOil(changeCivilisationCallback);
Configuration Object
Instead of passing around a bunch of related properties...
Closures
There are three ways to creats objects in Javascript: using literals, using the constuctor function and by using a closure. What closures offer that the other two approaches do not is encapsulation. Closures make it possible to hide away functions and variables.
var counter = function(count) {
console.log(">> setting count to " + this.count);
return {
getCount: function(){
return ++count;
}
}
}
mycounter = counter(0);
console.log(mycounter.getCount()); // outputs 1
console.log(mycounter.getCount()); // outputs 2
console.log(mycounter.getCount()); // outputs 3
console.log(mycounter.getCount()); // outputs 4
// Same again with offset this time.
mycounterWithOffset = counter(10);
console.log(mycounterWithOffset .getCount()); // outputs 11
console.log(mycounterWithOffset .getCount()); // outputs 12
console.log(mycounterWithOffset .getCount()); // outputs 13
console.log(mycounterWithOffset .getCount()); // outputs 14
Note: The closure is the object literal returned from annoymous function. It "closes" over the count variable. No-one can access it except for the closure. It is encapsulated. The closure also has a sense of state. Note also how the it maintains the value of the counter.
Constructor Functions (Built in)
There are no classes in Javascript but there are construtor functions which use the new keyword syntax similar to the class based object creation in Java or other languages. Javascript has some built-in constructor functions. These include Object(), Date(), String() etc.
Constructor Functions (Custom)
When a function is invoked with the keyword new, it is referred to as a Constructor function. The new means that the new object will have a hidden link to value of the function's prototype member and the this keyword will be bound to the new object.
Currying
Currying is the process of reducing the number of arguments passed to a function by setting some argument(s) to predefined values. Consider this function.
function outputNumbersFixedStart(start) {
return function(end) {
return outputNumbers(start, end);
}
}
Delete Operator
The delete operator can be used to remove properties from objects and arrays.
You cannot delete global variables or prototype attributes.
Dynamic Arguments
Arguments for a function do not have to be specifed in the function definition
for-in iterations
for-in loops (also called enumeration) should be used to iterate over nonarray objects.
Function declaration
In a function declaration, the function stands on its own and does not need to be assigned to anything.
Function expressions
When function is defined as part of something else's definition, it is considered a function expression.
In the above example, the function is named. It can also be anonymous, in which case the name property will be a blank string.
Functional Inheritance
Functional inheritance is mechanism of inheritance that provides encapsulation by using closures. Before trying to understand the syntax, take an example first. Suppose we want to represent planets in the solar system. We decided to have a planet base object and then several planet child objects which inherit from the base object. Here is the base planet object:
var earth = function(spec) { var that = planet{spec}; // No need for new keyword! that.peopleLeave = function() { // ... people leave } return that; }
var jupiter = function(spec) { var that = planet(spec); that.peopleArrive = function() { // .. people arrive } return that; }Now put the earth and jupiter in motion...
- There is code reuse.
- There is encapsulation. The name and numberOfMoons properties are encapsulated.
- The child objects can add in their own specific functionality.
- The base object planet accepts some data in the spec object.
- The base object planet creates a closures called that which is returned. The that object has access to everything in the spec object. But, nothing else does. This provides a layer of encapsulation.
- The child objects, earth and jupiter, set up their own data and pass it to base planet object.
- The planet object returns a closure which contains base functionality. The child classes receive this closure and add further methods and variables to it.
No matter where var's are declared in a function, javascript will "hoist" them meaning that they behave as if they were declared at the top of the function.
mylocation = "dublin"; // global variable
function outputPosition() {
console.log(mylocation); // outputs "undefined" not "dublin"
var mylocation = "fingal" ;
console.log(mylocation); // outputs "fingal"
}
outputPosition();
Immediate Function Expressions
Immediate function expression are executed as soon as they are defined.
JSON
JavaScript Object Notation (JSON) is a notation used to represent objects. It is very similar to the format used for Javascript Object literals except the property names must be wrapped in quotes. The JSON format is not exclusive to javascript; it can be used by any language (Python, Ruby etc). JSON makes it very easy to see what's an array and what's an object. In XML this would be much harder. An external document - such as XSD - would have to be consulted. In this example, Mitt Romney has an array describing who might vore for him and an object which is his son.
Loose typing
Javascript is loosely typed. This means that variables do not need to be typed. It also means there is no complex class hierarchies and there is no casting.
Memoization
Memoization is a mechanism whereby functions can cache data from previous executions.
Method
When a function is stored as a property of an object, it is referred to as a method.
Modules
The goal of modules is to enable javascript code bases to more modular. Functions and variables are collated into a module and then the module can decide what functions and what variables the outside world can see - in the same way as encapsulations works in the object orientated paradigms. In javascript we create modules by combining characteristics of closures and immediate function expressions.
- The function expression moduleScope has its own scope. The private variable balance and the private function doSomethingPrivate, exist only within this scope and are only visible to functions within this scope.
- The moduleScope function returns an object literal. This is a closure which has access to the private variables and functions of moduleScope. The returned object's properties are "public" and accesible to the outside world.
- The returned object is automatically assigned to bankAccountModule
- The immediate function ()) syntax is used. This means that the module is initialised immediately.
Namespace Pattern
Javascript doesn't have namespaces built into the language, meaning it is easy for variables to clash. Unless variables are defined in a function, they are considered global. However, it is possible to use "." in variables names. Meaning you can pretend you have name spaces.
Object Literal Notation
In javascript you can define an object as collection of name value pairs. The values can be property values or functions.
Prototype properties (inheritance)
Every object has a prototype object. It is useful when you want to add a property to all instances of a particular object. Suppose you have a constructor function, which representent Irish people who bought in the boom.
Returning functions
A function always returns a value. If return is not specified for a function, the undefined value type will be returned. Javascript functions can also return some data or another function.
this keyword
The this keyword in Java has different meanings, depending on the context it is used. In summary:
- In a method context, this refers to the object that contains the method.
- In a function context, this refers to the global object. Unless the function is a property of another object. In which case the this refers to that object.
- If this is used in a constructor, the this in the constructor function refers to the object which uses the constructor function.
- When the apply or call methods are used the value of this refers to what was explictly specified in the apply or call invocation.
typeof is a unary operator with one operand. It is used to determine the types of things (a bit like getClass() in Java). The values outputted by typeof are "number", "string", "boolean", "undefined", "function", "object".
Self-redefining functions
This is a good performance technique. Suppose you have a function and the first time it is called you want it to perform some set up code that you never want to perfom again. You can execute the set up code and then make the function redefine itself after that so that the setup code is never re-excuted.
Scope
In javascript there is a global scope and a function scope available for variables. The var keyword does not need to be used to define variable in the global scope but it must be used to define variable in the local function scope. When a variable is scoped to a local function shares the name with a global variable, the local scope takes precedence - unless var was not used to declare the local variable in which case any local references are pointing to the global reference. There is no block scope in javascript. By block we mean the code between {}, aka curly braces.
Single var pattern
You can define all variables used by a function in one place. It is ensures tidy code and is considered best practise.
Strict Equality
In javascript it is possible to compare two objects using ==. However, in some cases this will perform type conversion which can yield unexpected equality matches. To ensure there is strict comparison (i.e. no type conversions) use the === syntax.
Truthy and Falsey
When javascript expects a boolean, you may specify a value of any type. Values that convert to true are said to be truthy and values that convert to false are said to be falsey. Example of truthy values are objects, arrays, functions, strings and numbers:
// This will out put: 'none of them were true'
if (!("" || undefined || null || 0)) {
console.log("none of them were true");
}
Undefined and null
In javascript, the undefined value means not initialised or unknown where null means an absence of a value.
References
- JavaScript patterns Stoyan Stefanov
- JavaScript, The Definitive Guide David Flanagan
- JavaScript, The Good Parts Doug Crockford.
JavaScript
Object (computer science)
Property (programming)
Published at DZone with permission of Alex Staveley, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments