Monday, September 09, 2013

JavaScript: Slicing an Array

Have you ever wanted just a sub section of an array? Well, with slicing an array you can do just that.

Suppose I have an array

var myArray = [1,2,3,4,5];

and I want the first 3 elements, I can do the following

myArray.slice(0,3);

which return an array with the first 3 elements

[ 1, 2, 3 ]

This does not modify the original array in any way, it just returns a new array

The function slice has the following signature,

slice ( beginIndex, endIndex ) where the index is zero based i.e. the first element in a an array starts at index 0.

You could also access the array from the end using negatives indices for example,

myArray.slice(-3, -1);

returns

[ 3, 4 ]

Next we will look at splice......until next time!


Tuesday, July 23, 2013

Software Patents

I have always hated the patent system and think that it is abused and inhibits innovation. One of my favourite writers, Joel Spolsky has written a great blog on killing patents.

Monday, July 22, 2013

JavaScript: Length of Arrays

JavaScript arrays are dynamic and flexible with a few gotcha's. Today we will have an in-depth look at the length property, which is an unsigned 32 bit integer that specifies the number of elements in an array. Arrays have 0 based indices, therefore the length property will be the highest index + 1. Lets have a look at some examples

var a = [];

a.length   //return 0, a is an empty array

var b = [2,4,6];

b.length   //return 3

b[3] = 8;

b.length   //returns 4

b['a'] = 5;   //never a good idea to use an array as an associative array, instead use a plain object

b.length   //returns 4, non numeric indices are ignored in the length property

b[10000] = 50;

b.length   //returns 10001, the positions between 3 and 10000 are padded with undefined

Setting the length of an array will shorten it as well

b.length = 4

b.length   //returns 4, shortened the array from 10001 to 4

The safest way to empty an array is to set the length to 0

b.length = 0;   //empty's an array

Next, I will be looking at the slice and splice functions on an array, till next time.......

Friday, July 12, 2013

JavaScript: More on Arrays

So what else can you do with JavaScript Arrays? Arrays are like a swiss army knife, you can use it like an array, you can use it like an object, you can use it like a stack and like a collection, whatever suits your purposes. Arrays have the following functions available
  • length - return the total number of elements in the array
  • join - concatenates all the elements in the array into a single string separated by the parameter passed
  • concat - concatenates an array to the array and returns a new array
  • sort - sorts the array by character encoding by default or by a user defined function
  • reverse - reverses the elements of the array
  • slice - returns an array that is a subset of the original array
  • splice - can insert, remove or replace one or more array elements
  • push - adds an element to the end of an array
  • pop - it removes and returns the last element of an array
  • shift - it removes and returns the first element of the array shifting all other elements down
  • unshift - inserts elements at the beginning of an array shifting all the other element up
  • toString - converts all the elements to a string and concatenates them to a comma delimited string
  • toLocaleString - converts all the elements to a localised string and concatenates them to a comma delimited string
Pretty flexible stuff, next we will look at examples of each of these functions


Tuesday, July 02, 2013

JavaScript: Arrays

The JavaScript array construct is very flexible, and I especially love the fact that you can put anything into a JavaScript array. There is no type police breaking your code. Arrays in JavaScript are not true arrays, but an Object with special array like functionality. So how do we define an Array

var x = new Array (1, 5, "ten", "twenty");

or

var y = [1, 'a', true, 7.5, new Object()];

or

var z = [ [1, "hello"], [2, {name:"test"}]];


Array indexes are zero based and can be accessed as follows

var value = x[0]  //value will be 1

var anotherValue = z[1][1]['name']  //anotherValue will be test

Array indexes are generally integers greater than or equal to 0 and less than 232 - 1, anything else would be converted to a string and looked up as a string.

Arrays can also act as a dictionary with ease, using the x variable defined above, you could do the following

x['a'] = 12345

Yip the power of arrays in Javascript is terrifying, but liberating. I will look at some other array functionality in the next instalment

Thursday, June 13, 2013

JavaScript Primitives, The Imposters!!!

Allegedly the JavaScript universe contains 5 primitive types:
  • string - a sequence of unicode characters
  • boolean - represents a truth value of true or false
  • number - represents any number, even really big ones, between -253 and 253
  • undefined - indicates that a property or variable is unknown, does not exist
  • null - indicates no value
I say these primitives are imposters! They behave like objects but are not. JavaScript being a loosely typed language morphs the primitives into objects when used as objects. These primitives also have object wrappers.

var primitiveString = 'I am a primitive string';
var objectString = new String('I am a String object');  //using the object wrapper

primitiveString.length;   // 23, will work and return the correct value like an object


You could even do this

primitiveString.myvalue = 'test'     //like an object

which assigns the value 'test' to a hidden object property that you have no reference to, so you can't access the property from the primitive type thereafter.

null and undefined are also very strange, since they are just properties of the global object and can be redefined by you, but please, don't do that. More on this later.

Whether you use objects or their imposters, doesn't matter, just be consistent, so as to avoid hard to find bugs. Next, I play with JavaScript's awesome arrays, until then, may the code be with you.......

Part 3: JavaScript Object Oriented Fundamentals

Monday, June 10, 2013

Javascript Object Oriented Fundamentals

Before I can answer the question about  how object oriented is Javascript, maybe I need to dip my toe into the fundamentals of object orientation first. For something to be an object, it must combine data and behaviour into a coherent whole. Yes, it is as simple as that, but experience has shown me that simplicity is always more difficult than complexity. An object provides crisp abstractions with clear boundaries. Objects also support reusability through inheritance and/or composition of behaviour and data.

So Javascript is most certainly object oriented, but in my humble opinion, it's implementation is messy. The syntax and organisation have a very procedural feel about it, although it is not really possible to write procedurally, since all data and functions are combined within a global object

Javascript implements inheritance using prototype objects. Every object contains a prototype object and when a message is received by an object, Javascript will look for the property/function in the object first, then look for it in it's prototype object, if still not found it will look at the prototype's prototype object till it ultimately gets to the global object's prototype object. I will delve deeper into this in a later blog.

Last but not least Javascript also has constructors which are implemented as functions, and they can be implicitly or explicitly defined.

Enough on object orientation for now, till next time when we look at the few primitives that pollute the Javascript universe.....

See Part 2 - Objects, objects everywhere                           Part 4: JavaScript Primitives, The Imposters!




Wednesday, May 29, 2013

Diversity in the Linux Universe

Ubuntu has in recent months come under severe criticism over some of it's decisions with regards to the unity interface, Mir and last but not least, amazon search integration. Whether these decisions are right or wrong is a matter of perspective and I don't really want to get in to that at least not in this blog. I want to focus on the criticism that resources should not be wasted on re-inventing the wheel and that ubuntu should follow the community efforts. Progress is not made by conformance to old ways but in finding new and innovative ways.

One of the reasons I choose to use linux on a daily basis is because of its diversity, all the different flavors, configurations, options etc. It provides me with a plethora of choice, and if I don't like GNOME 3, I can change it to KDE or GNOME 2. When Ubuntu decided to build Unity, I was ecstatic, finally some fresh ideas, some new thinking, and yet another alternative but also skeptical. Although, I gave it a chance and have been loving it ever since. It works equally well on my 27" monitor as on my 11" netbook and gets better with every release.

So those who prefer a completely open source operating system have those options, those who want simple installations and ease of use have those options too, those who want a tiny operating system also have options and all within the Linux Universe. Diversity is wonderful, let us embrace and celebrate the diversity rather then inhibit it.........

Monday, May 27, 2013

Objects, objects everywhere.....

To a fish, water is everywhere and its whole world…….

I have spent my professional career developing software using object oriented development techniques, so when I started using Javascript the first thing I looked for was a way to express my objects. I looked for some kind of template/class syntax to define an object and declare it, but only found functions, variables, object instances and other language constructs. 

I constantly felt like objects were all around me and I just couldn't see them. Then suddenly like a slap to my face I awoke and could see them everywhere. So much so that in a web browser everything that you define is just an attribute of a global object, window

A name is not just a name, "function" is what created the confusion in my mind. I did not grasp that a function is the major expression of object oriented features in Javascript. Once I understood function = object, everything else just fell into place. 

Enough chat, how do we create these objects?

The simplest way is as follows

var myBlog = new Object();
myBlog.title = "Just Nonsense";
myBlog.author = "Da Doodler";

Each property of the object can contain any value, functions or objects.

You can also create objects using the object literal notation

var myBlog = {
    title: "Just Nonsense",
    author: "Da Doodler"
}

and then of course you can do the following as well

var myBlog = function blog(theTitle, theAuthor) {
    this.title = theTitle,
    this.author = theAuthor,
}

So many ways, so many choices, feel the liberation!!!

So just how object oriented is Javascript? Find out in the next episode....


Monday, May 20, 2013

Foray into the Javascript Universe


I have been developing software using static typed languages for 30+ years. However in recent years I have become very curious about dynamic, interpreted and untyped languages, so I dabbled a little with ruby, perl and javascript. They contained interesting concepts and they seemed like nice toys to play with. They provided powerful but yet quick and dirty ways of doing something in code.

As the web has developed over the last few years I began to see more and more javascript all over the internet and I can surely say it has become ubiquitous. 3 months ago I started a project for a client which motivated my serious foray in to the javascript universe. I found a language which is small and simple but yet large and complicated. I found the javascript universe without much standards, weak development tools and weak debugging tools and yet infatuated with its dynamism and expressive powers.

I love it, I hate it, I cannot ignore it and I cannot stay away from it. I am drawn to it like a bee to a flower.....Over the next few months I will capture my adventure....Watch this space!!!!

Tuesday, May 14, 2013

I miss blue screens.....

I have been using a windows machine in my day to day coding activities for many many years and it has served me well. We understand each other in esoteric ways, we love each other, hate each other but always depend on each other. But 3 years ago, I shamefully cheated my companion.

All around me people that I knew and trusted were moving on to newer and flashier Apple Mac machines, and I simply felt left out. I felt old and tired and stubbornly stuck in the past. My resolve slowly weakened and waned. I finally gave in and purchased a flashy 27" iMac machine.

Wow! It was like a whirlwind romance which slowly grew into a devastating tornado. As time went on slowly but surely the spinning balls kept spinning and I was never sure wether I should wait or reboot. One fine day while being mesmerised by the colorful spinning ball, I realised what I had lost. I miss blue screens......I miss blue screens...they were final, there was no false hope, no illusion of something happening, it was simple, honest and to the point.....I miss blue screenss.....