5

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.

3
  • 1
    It's called .map() and it's a method on the Array prototype. Commented Nov 8, 2013 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. Commented Nov 8, 2013 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... Commented Nov 8, 2013 at 3:49

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.