Almost! Both take a string as input and return a number. But one
returns an integer and the other a
float. So parseInt("3.14")
returns 3
and parseFloat("3.14")
returns 3.14
Functions are very cool. We're all used to variables that contain unknown values:
(I made a mistake above; what is it?)
In the above code, we know what all the functions are. But that might not be the case in another situation, where the variable holds a function.
For fun, here's the same idea in Python:
When we are going to pass a function to someone else to run, often we don't need a name for it. So, we just give the code: an anonymous function.
After all, the only reason to have a name is to refer to something later.
Yeah, they are, aren't they? Very concise in some cases (see above). There are some subtle differences, which we'll talk about later. But essentially:
Is the same as
You omit the name, if any, the return
keyword and the braces.
But you can add the braces and return
back if you need them.
forEach
is a method on arrays that takes a function
and invokes it for each element of the array. It
returns no value. We can use it instead of a loop. (Loops also return
no value.)
It's not necessarily preferred in industry, but for this class, I do. Because:
I'm not sure what you mean by "looping through functions". Do you
mean the forEach
method? We will do some practicing with
that.
Sorting is similar to Python, but a little different. In Python:
In JavaScript, we provide a comparison function between any two elements:
The comparison function must return *negative* if a should precede b, otherwise *positive*, and *zero* for ties.
Glad to hear it!