Functions can accept inputs called parameters that allow them to work with different data each time they're called.
The basic structure of a function in JavaScript:
To invoke (call) this function, you simply write:
Function execution flow:
Remember: Unless you invoke a function, it will not run. This is good news because it means you can define multiple functions upfront and only call them when needed.
Functions can send data back to where they were called using the return statement.
The return statement allows a function to output a value that can be used elsewhere in your code:
Tip: A function stops executing as soon as it encounters a return statement. This means any code after the return statement will not be executed.
If a function doesn't have a return statement, it automatically returns undefined
:
Scope determines where variables are accessible in your code. Function scope limits variables to the function where they're defined.
Variables defined inside a function are only accessible within that function:
Local variables are declared inside a function and can only be used within that function:
Global variables are declared outside of any function and can be accessed anywhere in your code:
When local and global variables have the same name, the local variable takes precedence inside the function:
Arrow functions provide a concise syntax for writing function expressions in JavaScript.
Let's compare traditional and arrow function syntax:
Note: Arrow functions have some differences in how they handle this
keyword compared to regular functions. For beginners, focus on the syntax benefits, and you'll learn more about the behavior differences later.
Practice creating and using functions by completing these exercises:
Remember to test your functions by calling them with different arguments!