Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In Python there is a function called map that allows you to go: map(someFunction, [x,y,z]) and go on down that list applying the function. Is there a javascript equivalent to this function?

I am just learning Python now, and although I have been told javascript is functional language, I can see that I have been programming in a non-functional javascript style. As a general rule, can javascript be utilized as a functional language as effectively as Python can? Does it have similar tricks like the map function above?

I've also just begun an SML course and am wondering how much of what I learn will be applicable to javascript as well.

share|improve this question
1  
It's called .map() and it's a method on the Array prototype. –  Pointy Nov 8 at 3:19
 
Js is object-oriented functional. Instead of map(f,[]) you do [].map(f). But js is also functional in the sense that just like Python you can implement the function map(f,[]) in javascript. Map is not what makes Python functional. It's the ability to write the map function that makes it functional - it just so happens that the standard library has one provided. –  slebetman Nov 8 at 3:48
 
As a note, python doesn't make a really great functional programming language (for that, look at lisp, scheme, haskel). It has some capabilities, but -- it's not really optimized for that... –  mgilson Nov 8 at 3:49

2 Answers

up vote 3 down vote accepted

Sure! JavaScript doesn't have a lot of higher-order functions built-in, but map is one of the few that is built-in:

var numbers = [1, 2, 3];
var incrementedNumbers = numbers.map(function(n) { return n + 1 });
console.log(incrementedNumbers);  // => [2, 3, 4]

It might be worthwhile to note that map hasn't been around forever, so some rather old browsers might not have it, but it's easy enough to implement a shim yourself.

share|improve this answer

You can also use underscore.js which adds tons of nice functionalists with only 4k size.

_.map([1, 2, 3], function(num){ return num * 3; });
//=> [3, 6, 9]
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.