DevNotes
@devnotes ·
JavaScript Part 5: Functions
A function is a named piece of code you can run whenever you need it. You write it once, and when it needs fixing, you fix it in one place.
Writing one and calling it
nameis a parameter: a placeholder for the value you'll pass in."Asha"is the argument: the actual value for this call.returnsends a value back to wherever the function was called.
Writing a function doesn't run it. The code inside only runs when you call the function, with brackets: greet("Asha").
return ends the function
The moment a return runs, the function stops. A function with no return gives back undefined. It's an easy bug to write: you work out the answer, forget to return it, and get undefined.
Default values
Arrow functions
A shorter way to write a function, and the style you'll see most in modern code and in React:
When a single expression follows the arrow, its value is returned automatically, without return or braces. With braces, you write the return yourself, as usual.
Scope: what a function can see
A variable made inside a function exists only inside that function. The function can see variables outside it, like shop, but the outside can't see in. That's a good thing: each function's variables stay out of every other function's way.
Functions as values
In JavaScript, a function is a value like any other. You can store it in a variable, or pass it into another function:
Passing functions around is everywhere in JavaScript: click handlers, array methods, timers. You'll see it in every part from here on.
Keep them small
A good function does one job, and its name says which: calculateTotal, isValidEmail, formatDate. If you can't think of a name, it's probably doing two jobs. Split it.
Try it
Write isEven(n), which returns true or false, and celsiusToFahrenheit(c), which multiplies by 9, divides by 5 and adds 32. Test both in the console with a few values, including 0 and a negative number.
Next: JavaScript Part 6: Arrays
Join WIK to like and reply to DevNotes and see more like this.