Functions
A function is a reusable block of code with a name. You write it once and call it as many times as you like. Functions are the main way programmers organise code into small, understandable pieces.
Declaring and calling
nameis a parameter: a placeholder for the input.'Asha'is an argument: the actual value you pass in.returnsends a value back to whoever called the function. It also ends the function immediately.
A function without return gives back undefined.
Multiple parameters and defaults
Arrow functions
Modern JavaScript has a shorter syntax called arrow functions. You'll see them everywhere.
Functions are values
In JavaScript, you can store functions in variables, pass them to other functions, and return them. A function passed to another function is called a callback.
This idea, higher-order functions, powers map, filter and much more in the next lesson.
Rest parameters
Writing good functions
- One job per function. If you need "and" to describe it, split it up.
- Name it with a verb:
calculateTotal,isValidEmail,fetchUser. - Prefer returning values over printing inside the function, so the result can be reused.
Practice
Write isPalindrome(word) that returns true if a word reads the same backwards, ignoring case. Hint: word.split('').reverse().join('') reverses a string.
1.What does a function return if it has no return statement?
2.Which is a valid arrow function that doubles a number?