Functions bundle code into reusable chunks that can be utilized throughout an application.
- 1.This lengthy MDN article is a good place to start. Pay special attention to the sections on 'Function Scope'. Scope is a topic that commonly trips up both beginner and intermediate coders, so it pays to spend some time with it up front.
function favoriteAnimal(animal). The parameter,
animal, is found inside the parentheses. We could just as easily replace
blah. But in this case, naming the parameter
animalgives someone reading our code a bit of context so that they don't have to guess what
animalmay eventually contain. By putting
animalinside the parentheses of the
favoriteAnimalfunction. This means that
animalis just a placeholder for some future value. But what value are we sending? The last line,
favoriteAnimal('Goat'), is where we are calling our
favoriteAnimalfunction and passing the value
Goatinside that function. Here,
Goatis our argument. We are telling the
favoriteAnimalfunction, "Please send 'Goat' to the favoriteAnimal function and use 'Goat' wherever the 'animal' placeholder is." Because of the flexibility that using a parameter provides, we can declare any animal to be our favorite. Feel free to experiment with the code on your own and replace
Goatwith your favorite animal. Notice how we can change the argument to anything we like? Try changing
animalin the function declaration and in the function body, too. What happens when you do?
arrow function. Arrow functions are useful but not crucial, so don't worry about them too much just yet. We include them here because you are likely to encounter them as you move forward, and it's better that you have at least some idea of what you're looking at whenever they crop up.
- 6.Finally, read this article about call stacks and how
returnworks in the context of chained function calls. Don't worry if you don't fully understand this yet, but it's important to keep in mind where your
returned values are going. This doubles as a bit of early computer science as well.
For now, just write each function and test the output with
- 1.Write a function called
add7that takes one number and returns that number + 7.
- 2.Write a function called
multiplythat takes 2 numbers and returns their product.
- 3.Write a function called
capitalizethat takes a string and returns that string with only the first letter capitalized. Make sure that it can take strings that are lowercase, UPPERCASE or BoTh.
- 4.Write a function called
lastLetterthat takes a string and returns the very last letter of that string: