Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.
  • Is Javascript a functional language? I know it has objects & you can do OOP with it also, but is it also a functional language, can it be used in that way?
  • You know how OOP became/seems like the next evolution in programming, does that mean that 'Functional Programming' is the next evolution(Note: this is NOT a prompt for opinion BUT a prompt for a factual evidence based answer, & this note is more for the moderators than the contributors ;) ).
  • I learn best through examples, maybe someone could show performing the same task in a OOP way & then in a Functional Programming way for myself to understand & compare what functional programming does/is.

I don't really completely understand 'Functional Programming' to be honest :P So comparing Javascript to functional programming may be totally incorrect.

To put Functional programming in laymans terms: is it simply the benefit of abstration THROUGH using anonymous functions?

Or is that way too simple? In a simple way, OOP is the benefit of abstraction through objects, but I believe thats being a little too simplistic to describe OOP.

Is this a good example of functional programming?...

Javascript OOP Example:

// sum some numbers
function Number( v )
{ 
  this.val = v;
}

Number.prototype.add( /*Number*/ n2 )
{
    this.val += n2.val;
}

Functional programming example:

function forEach(array, action) 
{
   for (var i = 0; i < array.length; i++)
       action(array[i]);
}  

function add(array)
{
    var i=0;
    forEach(array, function(n)
    {
        i += n;
    });
    return i;
}

var res = add([1,9]);
share|improve this question
    
It depends on the definition of "functional programming language". In a broad sense, it can be understood as the ability to build functional values with closed values, ie as having a "lambda" construct (in the sense of the lambda-calculus), and then Javascript fits the bill. –  Basile Starynkevitch Dec 30 '11 at 8:05
2  
Or is that way too simple? Yeap, it is. Anonymous functions are sometimes associated with functional languages and multi paradigm languages that favour functional programming, but they are not a unique characteristic of functional languages. But if you see them as an implementation of λ-calculus, well they are a core part of functional programming, the main point being that it's not so simple :) –  Yannis Rizos Dec 30 '11 at 8:31
    
Javascript's design prevents implementations being able to do tail-call optimization. In my books that alone prevents it from being labelled as functional. –  dan_waterworth Jan 13 '12 at 14:27
    
I know it has objects & you can do OOP with it also No, you can't. It's prototype based programming which eliminates distinction between class and object. Personally I consider prototype based programming to be flawed on this basic level. –  U Mad Jan 13 '12 at 15:33

5 Answers 5

Is Javascript a functional language? I know it has objects & you can do OOP with it also, but is it also a functional language, can it be used in that way?

Sometimes, people will say functional programming, when what they mean is imperative programming or procedural programming. Strictly speaking, functional programming is:

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. Functional programming has its roots in lambda calculus, a formal system developed in the 1930s to investigate function definition, function application, and recursion. Many functional programming languages can be viewed as elaborations on the lambda calculus.

Although Javascript is not widely known or used as a functional language, it does have some functional elements:

JavaScript has much in common with Scheme. It is a dynamic language. It has a flexible datatype (arrays) that can easily simulate s-expressions. And most importantly, functions are lambdas.

Scheme is a dialect of Lisp, and probably one of the languages most programmers think of when they discuss functional programming. When it comes to object orientation, Javascript is an object oriented language. But its object orientation is prototype based:

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming.

So although Javascript is object oriented, it doesn't follow the more common class based model, as do languages as C++, C#, Java and PHP (and quite a few others). And of course it's also an imperative language, which leads to the confusion with functional programming I described above.

You know how OOP became/seems like the next evolution in programming, does that mean that 'Functional Programming' is the next evolution

Object orientation and functional programming are just two of the many different programming paradigms, they are different styles of programming with different concepts and abstractions. The key word is "different". There isn't a single paradigm that's better than others or more evolved than others, each and every one fits some scenarios better than the others. Some may be quite older in origin than others, but in evolutionary terms that makes them better, as they have survided longer. But that's not a very smart way of looking at it.

Javascript, as I described above and as quite a few other languages, is multi-paradigm. It allows you to write code in imperative, prototype based object oriented and functional style. It's up to you to choose which one best fits whatever you are building. There are also several single paradigm languages, the canonical example being Java, which only allows for class based object oriented programming1.

You should really resist any urge to treat languages & paradigms as fashion statements. There's an abudance of crap out there, mostly written by fanboys / fangirls or marketing people, with little (if any) knowledge and understanding of programming. Terms like "better", "more evolved" etc, simply don't apply.

I learn best through examples, maybe someone could show performing the same task in a OOP way & then in a Functional Programming way for myself to understand & compare what functional programming does/is.

That would be a terrible way to learn. Functional and object orientation are quite different styles, and any example other than terribly simple ones would not fit one or the other style.

1 But lately tries to expand its scope to generic programming, let's see how that goes.


In conclusion:

  • Concentrate on learning Javascript, it's a beautiful and extremly useful language. Learn the language, not the hype.
  • Quite a few different paradigms, all equally useful. Up to you to choose which one you prefer and which one fits best whatever you're building.
  • If you want to learn functional programming, choose a more suited language, like Scheme or Clojure. But you'll first need to understand the mathematical concepts involved.
  • Do some research before you ask. Most of your questions are answered by the relevant Wikipedia articles. Knowing how to research and how to ask is an extremely important skill for any programmer.
share|improve this answer
3  
+1 Great response. Because of the way programming education is structured, new coders seem to think the paradigms are exclusive and discrete, but they're not. Try to write OOP code that takes advantage of functional concepts when it makes sense to do so. Event-driven programming is a paradigm, but aspects of EDP influence certainly every gui and web program. Polymorphism, a core feature of OOP, is really generic programming. Naming these ideas helps us conceptualize good programming, but you shouldn't use one to the exclusion of others. –  kojiro Dec 30 '11 at 18:51

Evolution normally means an incremental change. OOP is not an incremental addition to the procedural programming - in fact, it is entirely orthogonal to an underlying programming model and can be combined with any of them. Functional programming is not an incremental addition to procedural, OOP or whatever - it is an alternative basis for expressing fundamental computing principles, and it is actually the first such basis ever formulated, long before the first computers appeared. It is important to understand that all such fundamental systems are equivalent (i.e., one can be expressed in terms of another).

In order to understand the functional approach, you'll need to get the basic math first. If you want to get a feeling of what does it mean to code in a functional style in Javascript, start using jQuery.

share|improve this answer

Javascript can be used as a functional language, in fact it does it quite well. It is possible to implement monads has support for a lambda construct etc. It is not exclusively a functional language in that it also has a lot of object oriented features but it can be used that way. Actually I find that using Javascript as a functional language is a great way to use it. (Example jQuery and underscore.js)

share|improve this answer
    
good & concise! Agreed that functional programming is often the easiest way to get something done in js. –  bunglestink Dec 30 '11 at 12:27
    
Even more interesting than monads, you can implement arrows is JS (cs.umd.edu/projects/PL/arrowlets). Now, as to why anyone would want arrows in JavaScript, that's an open question. But it can be done. –  rtperson Jan 13 '12 at 14:16
    
I will admit that I don't understand enough about arrows to know if they will be useful. But I am working on a Book on Monads in Javascript and may add a chapter on Arrows (shop.oreilly.com/product/0636920023890.do) –  Zachary K Jan 14 '12 at 16:02

No.

JavaScript is an object-oriented language first and foremost.

That is not to say that you can't write JavaScript programs in a functional style, since you can adopt a functional style in any Turing complete language if you try hard enough. You can do functional programming in assembler if you like. But this does not make every language functional. You might equally as well call Haskell imperative, or Java a logic programming language - if you took this approach, the terms would soon become meaningless.

IMO the way to classify a language into the appropriate paradigm is to consider:

  • What is the dominant style enabled by the language constructs (clearly OOP for JavaScript, functional languages instead emphasise functions and immutable data values)
  • What paradigm is supported in the language's core libraries (again clearly OOP for JavaScript)
  • What features are disabled or discouraged in the language (functional languages discourage or forbid mutable variables, which is not the case for JavaScript)
  • What development style is prevalent in the community of developers using the language (again, OOP is clearly prevalent in the JavaScript world)

Personally I find it rather amusing that lots of people like to claim a language is "functional" just because it is a trendy term at the moment :-)

If you want a slightly long but entertaining perspective on programming paradigms through the years, it's worth watching Uncle Bob Martin's video "The Last Programming Language". For me the great insight from this talk was that programming paradigms are defined by what features they take away, not what features they put in......

share|improve this answer
    
What is the dominant style enabled by the language constructs I dare you to try and apply that to Perl... Or any other of your points, really :) –  Yannis Rizos Jan 13 '12 at 10:13
2  
Perl? Good challenge! It's a somewhat like assembly language in the sense that you can hack pretty much any paradigm you want together, but in the common usage that I have seen (scripting) it's used mostly as an imperative / procedural language. –  mikera Jan 13 '12 at 10:37
    
Well, oop is also pretty common. In a perly way of course. And, functional too, although uncommon. perl is just perl, no sense in trying to make sense out of it :) –  Yannis Rizos Jan 13 '12 at 10:50
    
JavaScript is slightly more functional then Java because it at least has closures and first class functions. But your right, JavaScript is just as functional as C# is. –  Raynos Jan 13 '12 at 12:28

Javascript is prototypal first, with functional capabilities - granted by it's use of functions as first class objects.

This means that you can use functions as data, which has the curious effect of reducing the need for variables that maintain state. If you find that yourself reaching for the var statement, or are using one or more "if" statements, then you're straying from a functional style.

Another notable idiosyncrasy of functional style is that functions should ONLY return the result of their evaluation and have no side effects on the state outside of their scope:

// oops, this is producing a side effect
function sideEffecter(){//theres no input...        
    window.thingy = 'foo';
    // hey, this isn't returning anything!!!
} 

Functional languages are non-destructive - meaning that they do not mutate the input, but rather return entirely new data based on the input. See this thread: http://stackoverflow.com/questions/749084/jquery-map-vs-each

Functional languages also feature a lot of methods in common - with names like "map", "fold", "reduce" that process lists/collections. In JS, unlike other languages, we have to handcrank these into existence - see libraries like underscore.js for some examples, although the latest implementation of JS has some of these straight out the box.

The important thing to bear in mind (IMO) is that while JS can utilise some functional patterns, it is not always well equipped to execute then.

Take iterating over an array, for example. You can do this using a functional style or the native loop constructs - and generally speaking the loop is more performant. Take this example - hit it with loops of increasing size and record the execution times in different browsers (i've done this already, but I've lost the benchmarks - sorry!):

var test = ['foo', 'bar', 'baz'], removeFunc, removeLoop;

//(semi)functional style...
// to be really functional each condition in the ternary would be another function
removeFunc = function(src, trg) {
    return src.length === 0 ? 
        src : 
            src[0] === trg ? 
                src.slice(1) : 
                    [src[0]].concat(removeFunc(src.slice(1), trg));
};

//but this is faster
removeLoop = function(src, trg){
    var len = src.length, // using variables to represent state...
        i=0, 
        result = [];        
    while(i < n){
       if(src[i] !== trg){
          result.push(src[i]);
       }
       i = i+1;
    }
}

In addition, if you use a functional construct to hit loops of considerable size and don't utilise some form of ad-hoc stack management you could flood the stack (although, to be fair, you need a BIG list for this to occur...). You've also got to factor in to the mix the variant optimisations in each browser - although if you're working in a Node.js environment this is obviously more of a fixed target.

That's not to say you shouldn't use functional constructs in Javascript - just be aware of the limitations in it's implementation relative to it's environment.

Here are some links that might be of interest to you:

A good chapter on Functional Programming in Javascript from the excellent "Eloquent Javascript"

The Little Schemer

a friend of mine wrote a JS library based on the Little Schemer

A good tutorial on Scheme that might help you better comprehend FP

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.