In JavaScript all functions and variables are often ‘hoisted’ to global scope, effectively making them global variables. This is potentially bad, as the following demonstrates:

if (true) {
    var x = 0;
}

alert(x); //alerts "0"

Here, even though ‘x’ is defined in a block, it is given global scope, and hence accessible outside the block. (For a demo, see http://jsfiddle.net/vRmLL/)

If we define our variable within a function, however, the scope is retained within the function. So the following will not work:

function SomeTest() {
    var y = 0;
}

alert(y); //undefined – a scoped variable - just what we want!

So, by using functions we can introduce scoping into JavaScript:

(function() {
    var z = 0;
})();

alert(z); //undefined – just what we want!

The last () executes everything in the body of the anonymous function. This pattern is called a closure.

This is a very simplistic overview of them. A more comprehensive one can be found in Morris Johns’ article JavaScript Closures for Dummies.

, , ,

DO NOT REPLY EITHER WAY – THIS IS A SCAM

Get yourself DEBT FREE this Year! Reply “info” to this number for details. Government backed scheme. Free to reply. Get a fresh start. £1000 plus. PER Ltd

I just recieved a new one today. Received from: +447786207081 / 07786207081

Landline text messaging

Image via Wikipedia

This is one of many messages that are circulating as originally highlighted in my article Debt Settlement Order Spam Text Message. If you ever receive anything that remotely fits this template then delete it.

Again, DO NOT REPLY

And, if you can, post the number in the comments below. This will help people searching by that number alone find this article and avoid any potential trouble arising from replying.

I’d be interested to hear of any variants on this message that surface.

If you want to read more, can I recommend the above link. It contains a list of articles that I’ve written regarding this whole scam and its setup. I found the research both fascinating and appalling at the same time.

Are You a Victim?

Screenchannel Television is making a new series about debt and loans and are looking for people to share their experiences. If have been a victim of this scam, or have even considered responding and are interested in taking part, then you can read more in this article.

Reporting

You may be report these messages to your provider. The following links may help:

Vodafone – How do I report spam text messages? Forward the spam message to VSPAM (87726).

Orange – Stop spam text messages. If you are on Orange and get spam messages, please forward them to 7726 free from your Orange phone. By doing this you are helping Orange to collate information to help reduce spam messages being sent to you and others.

02 also allow you to report on 7726. See: SPAM and unwanted subscription texts

I would also try forwarding the message onto 7726 if you are with T-Mobile or Three.

You can also try NumberCop and DoNotCall.gov

Back in May 2009, the Guardian newspaper wrote an article Spam to go – the new mobile menace. It recommends a number of organisations you can contact.

To complain about an inappropriate text, call the Advertising Standards Authority 020 7492 2222 or go to www.asa.org.uk/asa/contact/

To resolve continual mobile spam despite texting “stop”, contact the ICO on 01625 54 57 45 or go to www.ico.gov.uk/complaints.aspx

For help with premium rate text spam, call PhonepayPlus on 0800 500 212 or log on to www.phonepayplus.org.uk/output/Make-a-complaint.aspx

, , , ,

I’ve been playing around with delegates and lambda expressions, and thought I would note down what I had learned (this is a programming notebook, after all).

    class Program
    {
        delegate int IntFunc(int a, int b);

        static void Main(string[] args)
        {
            IntFunc add = new IntFunc(delegate(int a, int b) { return a + b; });
            Console.WriteLine(add(1, 2));
        }
    }

I am particularly interested in how we can improve the following line with lambda expressions and a little syntactic sugar:

IntFunc add = new IntFunc(delegate(int a, int b) { return a + b; });

So, let’s start by turning it into a lambda-expression:

IntFunc add = new IntFunc((a, b) => { return a + b; });

Here, we say “parameters a and b of our deletegate ‘go to’ (=>) our block of functionality, which is defined in the {} braces.

But we don’t actually need the curly braces, or the return for that matter, as the lambda expression will infer this. So, we can reduce the expression down to the following:

IntFunc add = new IntFunc((a, b) => a + b);

However, looking at the original statement, we realise that the new IntFunc isn’t necessary either. It could have read:

IntFunc add = delegate(int a, int b) { return a + b; };

So, our lambda expression reduces down even further:

IntFunc add = (a, b) => a + b;

Marvellous! It also explains to me quite nicely how lambda expressions syntax derives from the equivalent delegate syntax.

But, we’ve not finished here. Take our delegate type:

delegate int IntFunc(int a, int b);

C# already has an in-built type func<> to save us from such declarations. We can dispense with the delegate line completely when we recognise that we have two inputs of type int and one output of type int.

Our final class looks like this

    class Program
    {
        static void Main(string[] args)
        {
            Func add = (a,b) => a + b;
            Console.WriteLine(add(1, 2));
        }
    }

Lovely!

, , ,

Have you ever wondered where C#, BASIC (yes, it’s an acronym), or C++ came from? What about Ruby, Python or PHP? And whatever happened to Algol, Ada or Pascal. And where exactly is Delphi at these days?

Well, you can see a timeline of these and forty or so other languages here at levenez.com.

Fascinating!

, ,

An incorrect placement of the ‘break’ statement within a loop will yield this error message. As shown in the following example:

function MyFunc(){
    var x = 0;
    for (x=0; x<10; x++){
        //do something
        break;
    }
}

Here, we will never reach the second iteration of the loop.The ‘break’ statement will kick us out at the end of the first time around. Break statements used in this way should always be wrapped in a conditional statement.

At best this is redundant code that was never cleared up properly, and, at worst, this is some sort of bug that is yet to be identified.

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, , ,

I had cause today at lunch to unleash random bletherings upon a colleague of mine regarding some subjects I had not considered since university. I realised soon after that I could probably write-up my rants in a series of articles.

This is the first of two articles, and it surrounds my thoughts on the true ‘heroes’ of computing.

Charles Babbage

Charles Babbage

My colleague and I were talking about how computing and programming is often overlooked as a scientific discipline. A career physicist will be well aware of the key contributory figures to their discipline; names such as Einstein, Newton, and Hawking are practically ubiquitous, and are easily recognisable names far outside the community. In chemistry, the names Curie, Nobel, and Rutherford stand out, whilst mathematicians can look towards Fermat,  Archimedes, Newton (again), and, more recently, Andrew Wiles, famed with proving the former’s “Last Theorem“.

In computing, however, it appears we have few such “household” names recognisable outside the profession. Charles Babbage and Alan Turing are probably amongst the most mentioned, but it is likely they only remain in the public consciousness due to the ignominy of their final demise.

When Babbage Died in 1871 he was virtually unknown. The Times newspaper ridiculed him and the Royal Society did not publish an obituary. In 1878, a committee of the British Association for the Advancement of Science recommended against constructing the Analytical Engine. Eventually, in 1991, the London Science Museum commissioned a fully working specimen from Babbage’s specification of Babbage’s Difference Engine No. 2.

Turing in slate at Bletchley Park. People who ...

Alan Turing

It is impossible sum up Alan Turing in a single paragraph. He is regarded by many as the father of computing formalised the concepts of ‘algorithm’ and ‘computation’. During the 2nd Word War he played a pivotal role in the breaking of German cyphers, most famously Enigma. He devised the concept of the ‘Turing Test’ which is a test of a machine’s ability to exhibit intelligent behaviour. This idea is now prominent in internet CAPTCHAs – the funny obscured text you are often asked to type on a form order to confirm you are human!

In 1952, Turing was arrested and charged with gross indecency after admitting having had a homosexual relationship. He elected to undergo hormonal treatment as a punishment (for being homosexual) instead of imprisonment, and accepted chemical castration via oestrogen hormone injections. He was found dead two years later having  ingested a lethal dose of cyanide. An inquest determined that he had committed suicide, though this is subject to much speculation.

So what of the practice of our scientific disciplines?

A career physicist will almost certainly have a degree in physics, and likewise for a professional mathematician or chemist. Programming, however, is so accessible to the masses that such no, such prerequisite exists. Anyone with a browser and a text editor can write an executable program (in JavaScript) that can theoretically be run by anyone else that has a browser.

It is therefore no surprise that a seminal list of recognised industry pioneers is not mainstream, not even within the industry itself.

I conducted a short poll around the office for two others that I felt should be instantly recognisable, Donald Knuth and Ada Lovelace. This selection was based on whatever I was reading at the time, and indicates no perception of seniority or significance over any other name I could have chosen.

For those that are unfamiliar, Donald Knuth (pronounced Ka-NOOTH, according to his website) is the author of a volume of books entitled The Art of Computer Programming. American Scientist included this title its list of the top 12 physical-sciences monographs of the century, in the company of works by Russell and Whitehead, Einstein, Dirac, Feynman, and von Neumann.

Ada Lovelace, 1838

Ada Lovelace

Ada Lovelace is credited by many as writing the very first computer algorithm between 1842 and 1843, designed as a program to operate on Charles Babbage’s analytical engine. For this, she is often portrayed as the world’s first programmer! She also met a tragic end, dying at the age of 36 from uterine cancer and bloodletting by her physicians. Her name lives on today in computing in the Ada Computing Language

The result of my totally unscientific straw-poll was that while they were familiar with Babbage and Turing, no-one I asked had heard of either Knuth or Lovelace (apart from Malcolm and Ron, who I fully expected would).

There are others I could have mentioned, from John von Neumann who devised the von Neumann architecture that underpins most modern computers to Edsger Dijkstra who won the Turing Award (the Nobel Prize of Computing) in 1972 for his  contributions to developing programming languages. Even Noam Chomsky, one of the fathers of modern linguistics, can be cited. His Chomsky language hierarchy is said to describe a fundamental part of any modern language compiler.

This state of unawareness is maybe unsurprising. Douglas Crockford commented when interviewed for Peter Seibel‘s book Coders at Work

I think we’re tragically unaware of our history, and I’m often really disappointed to see that people who are now practicing this craft having no intellectual curiosity about where this stuff came from…

Continuing on the same theme, in the same book, Donald Knuth was asked if he felt that programmers and computer scientists were aware enough of the [pretty short] history of the field. He responded:

I was reading in American Scientist last week about people who had rediscovered an algorithm that Boyer and Moore had discovered in 1980. It happens all the time that people don’t realize the glorious history that we have. The idea that people knew a thing or two in the ’70s is strange to a lot of young programmers.

It’s inevitable that in such a complicated field that people will be missing stuff. Hopefully with things like Wikipedia, achievements don’t get forgotten the way they were before.

One could argue that the age of the discipline has not been sufficient to afford computing its pioneering figureheads their legendary status. Archimedes died in 212BC, a full 2090 years before Babbage, so we may have some years to go. It could also be that the speed of advancement of the computer industry, and the inherent obsolescence of many of the transient articles of computing over the years robs the incumbent professionals of their immortality.

So what of today’s names be memorable to the masses in 100, or even 2000 years time? Tim Berners-Lee, founder of the world wide web will surely get a mention, as may Steve Jobs, co-founder of Apple.  And regardless of any sentiments you may hold of him, I also expect history will be kind to Bill Gates.

Again, I’m plucking random names off the top of my head, but would love to hear your opinions on others.

So, who exactly will be our modern-day heroes of computing…tomorrow?

, , ,

In languages where compilation of code is required up-front before it can be executed, the developer often has the luxury of being warned about unused or unreachable code by the compiler.

For JavaScript, we have no such luxury, however, JSLint is there to emulate some of the features that a compiler would provide.

So, when we write code that contains unused variables, JSLint will helpfully warn about us about it. The following code sample will yeild this error:

function MyFunc(){
    var x = 0;
    for (x=0; x<0; x++){
        //do something
        var y = 0;
    }
}

At best this is redundant code that was never cleared up and, at worst, this is some sort of bug that is yet to be identified.

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, , ,

This message is documented quite concisely on the JSLint instructions page:

JSLintexpects that a returnbreakcontinue, or throw statement will be followed by a } or case or default

At best, the presence unreachable code is indicative of general laziness on behalf of the developer, and, at worst, it may highlight a potential bug. Either way, JSLint is fully justified in raising the error.

The following code shows a scenario where this might arise:

function MyFunc(){
   var x = 0;
   return x;
   x++;
}

JSLint is also savvy enough to look within conditional statements…

function MyFunc(){
    var b = false;
    if (b){
        return 1;
    }
    else{
        return 2;
    }
    return 3;
}

…loops…

function MyFunc(){
    var x = 0;
    var y = 0;
    for (x=0; x<10; x++){
        if (x<5){
            break;
            y++;
        }
    }
}

…and the not often seen “throw” statement.

function MyFunc(){
    var x = 0;
    throw "MyError";
    x++;
}

This is just another way that JSLint can help you identify potential issues earlier in the development process.

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, ,