Object Oriented Programming in JavaScript Part Two

This is the second series of Object Oriented Programming in JavaScript. This post discusses about the Objects built into JavaScript. Once you have gone through this post you will have an understanding of the various Objects in JavaScript. If you have not read the first series read it first as this is a continuation.

The "extensible" attribute

Before we dive into the concept of Objects, new in ES5 is the "extensible" attribute for the Object. If you don't know what an attribute bit is, read the first part of OOP in JavaScript.

"extensible" is a boolean attribute. You can use the following functions to know more about this attribute and also to use it.

Object.isExtensible(testObject) - Test weather a Object can be extended.

var testObject = {
 propOne: 'testPropertyOne',
 propTwo: 234
};

// will return true.
Object.isExtensible();
  

Object.preventExtensions(testObject) - This method turns the "extensible" bit "off". Once this is set to off, this can never be turned on. What this means is that when this bit is turned off, you can not add properties to that object. If you try to add one you'll get an error.

var testObject = {
 propOne: 'testPropertyOne',
 propTwo: 234
};

Object.preventExtensions(testObject);

// Now, this will return false
Object.isExtensible(testObject);

// but still, you can delete a property
delete testObject.propTwo;

// and change the property value
testObject.propOne = 'I am changed now';

console.log(testObject);
// {propOne: "I am changed now"}
  

Object.seal(testObject) - This does the same as above method, but this method also loops through all the object properties and turns their "configurable" bit to "off".

var testObject = {
 propOne: 'testPropertyOne',
 propTwo: 234
};

Object.seal(testObject);

// will return false
Object.isExtensible(testObject);

// this will also return false, you cannot delete a property of this object
delete testObject.propOne;

// but you can still change the value of the property
testObject.propOne = 'I can still be changed :)';

console.log(testObject);
// {propOne: "I can still be changed :)", propTwo: 234}
  

Object.freeze(testObject) - This function also does the same thing as above method, along with that it makes all the property read only. It turns "off" every properties "writeable" bit.

var testObject = {
 propOne: 'testPropertyOne',
 propTwo: 234
};

Object.freeze(testObject);

// will return false
Object.isExtensible(testObject);

// will return false, you cannot delete a property of this object
delete testObject.propOne;

// and you cannot change the value.
testObject.propOne = 'I can not be changed :(';

console.log(testObject);
// {propOne: "testPropertyOne", propTwo: 234}
  

This is a very powerful feature. We can make immutable Objects using this property. You can make object that cannot be changed. Before this only the system objects like Number, Boolean etc. were immutable, but now we can also make one.

Types in JavaScript


Every types in JavaScript is based on the global object and each of them are them self objects - Number, Boolean, Array, Date, String etc. We will see about them in detail.

Number


Unlike many languages, JavaScript has only one number type. It is 64bit floating point sized. In other languages there may be many type of Numeric types like int, long, short, double and so on. But in JavaScript every numeric representation is of type "number". There are a handful of methods available for the number objects.

var num = 234,
 decim = 234.343,
 expo = 2e+3;

// we can use the typeof to identify the type.
typeof num; // "number"
typeof decim; // "number"
typeof expo; // "number"

// toString() - will return a string representation of the number.
typeof num.toString(); // "string"
  

Mysterious "NaN"


NaN (Not a Number) is a special type that represents a result of undefined or erroneous operations.

(0 / 0); // will return NaN
(233/'string'); // will also return NaN
  
Warning:
(NaN === NaN); // will yield "false"

(Nan !== NaN); // will yield "true"
    

Math


Math is like a Utility object which provides us with some useful methods that we can use to operate on numbers. This Math Object is similar to the Math library available in Java Language. here are some useful methods from Math.

Math.floor(1.5); // 1
Math.ceil(1.5); // 2
Math.round(234.34); // 234
Math.sqrt(16); // 4
  

Boolean


Boolean has only two possible values "true" and "false".

var bool = true;

if (bool) {
 console.log('Passed through the conditional statement');
}

var boolFalsy = false;

if ( !(boolFalsy || /** other false values */ '' || 0 || null || undefined) ) {
 console.log('we are the falsy values');
}
  

String


String are a sequence of 0 or more Unicode characters in JavaScript. Strings are immutable in JavaScript(Once defined cannot be modified). The String Object in JavaScript provides very handy methods for us to work with strings. This is one of the Good Parts about JavaScript.

var num = 23;
// Convert a number into string.
str = num.toString(); // But instead you must use String(num);
console.log(str);
str += 'hi there';
console.log('Number joined with string - "' + str + '". But i need only the number?');

// Convert string into a number
var convNum = parseInt(str);
console.log('That is awesome. I converted a string to a number - ' + convNum);
  

The "parseInt" function works by scanning the Characters in the string for digits, once it finds any character other than a digit it stops scanning and returns the number until it has scanned.

The string object has the "length" property. It gives you the length of the string, which is the number of characters in the string.

'This is a long string'.length; // will print 21
'hello'.length; // will print 5
  

String have a lots of methods. You can examine all of them by going into a browsers console and testing them. I will show you some of the commonly used methods here.

// Combine two string values. Use "concat" method.
'Moon and '.concat('star');

// Replace a part of the string.
'This is John Speaking'.replace('John', 'Scott'); // 'This is Scott Speaking'

// Search a string using "search". 
// search method will return the index of the starting character
// remember, index in string starts from 0 to n-1.
'This is John Speaking'.search('John'); // 8

// Split a string with the specified character
// "split" method splits the string with the given character and 
// returns the array of splitted strings.
'John,Scott,Juliet'.split(','); // ["John", "Scott", "Juliet"]

// get a substring. "substring" method.
// substring(startingIndex, endingIndex);
// If endingIndex is not provided will retrieve till the end.
'A Long Sequence of Characters'.substring(7); // 'Sequence of Characters'
'A Long Sequence of Characters'.subString(7, 15); // 'Sequence'

// trim spaces in a string. "trim" method
'    I am Trimmed  '.trim(); // 'I am Trimmed'

// Convert string to Upper Case.
'JOHN'.toLowerCase(); // "john"

// Convert string to Lower Case.
'john'.toUpperCase(); // "JOHN"
  

Array


Array in JavaScript is also an Object. Arrays are numerically indexed. Array index starts from 0 to the end. Unlike Arrays in Java, you need not specify the length of the array. Arrays in JavaScript can by dynamically expanded.
Creating An Array

Arrays in JavaScript can be created using the "Array Literal" notation and the "Array" Construct.

names = new Array('John', 'Scott');
console.log(names);
// or
names = ['John', 'Scott'];
console.log(names);
  

Arrays have the "length" property just like string, which determines the number of elements in the array.

names.length; // will return 2
  

You can loop through the elements in the array using the "for" loop. Do not use "for in for looping through array elements. You can access the array elements using the array literal notation.

names[0]; // 'John'
names[1]; // 'Scott'
  

Arrays in JavaScript have a lot of methods similar to strings.

// Combine two arrays
name = ['Juliet'];
names = names.concat(name); 
console.log(names); // ["John", "Scott", "Juliet"]

// use "join" to Join the elements in the array using a separator glue.
// string.join(separator)
names.join(','); // "John,Scott,Juliet"

// "map" method can be used to call a method for each of the element in the array

function greet(name) {
 console.log('Hello there Mr.' + name);
}

names.map(greet);
// Hello there Mr.John
// Hello there Mr.Scott
// Hello there Mr.Juliet
  

Date


Date Object is same as the Java's Date Class. It is pretty much simple to use.

console.log(Date()); // will return the current date string.
  

The Date Object also provides some usefull methods to get the information about the date. You can always check the methods available in an Object in a Browser web console.

// Create a new Date Object using the Date() construct
var today = new Date();

// get the local date string
today.toLocalString(); // will return the string as per the systems date.

// get the UTC Year
today.getUTCFullYear(); // will return 2014
  

As you saw, pretty much everything in JavaScript is an Object. Next series will contain in detail about the connections between these objects and about prototype inheritance.

If you need to know more about the method signatures of the Objects in JavaScript download the JavaScript Reference Manual.