DEV Community

Jennifer Tieu
Jennifer Tieu

Posted on • Edited on

Self-Taught Developer Journal, Day 30: TOP JavaScript Fundamentals Part 3 - Functions

Today I learned...

Function Declaration

A function declaration uses the function keyword and name of the function.

function calculateAge(birthYear) {
  return 2022 - birthYear;
}
Enter fullscreen mode Exit fullscreen mode

"Note: This form is always hoisted, so you can call function before function definition and it will work fine."

Anonymous Functions or Function Expression

A function without a name. Often used when a function expects to receive another function as a parameter. Anonymous expressions aren't hoisted.

function (birthYear) {
  return 2022 - birthYear;
}

const calculateAge = function (birthYear) {
  return 2022 - birthYear;
}
Enter fullscreen mode Exit fullscreen mode

Arrow Function

A shorter alternative form to Anonymous Functions.

// parameter and return statement
birthYear => 2022 - birthYear;

const calculateAge = birthYear => 2022 - birthYear;
const age = calculateAge(1997);

// with multiple parameters and return statement
const calculateAge = (birthYear, firstName) =>
{
   const age = 2022 - birthYear;
   return `${firstName} is ${age} years old`;
}

// no parameters
const hello = () => "Hello World";
Enter fullscreen mode Exit fullscreen mode
  • If the function only has one line in the curly brackets, you omit the curly brackets
  • If the only takes one parameter, you can also omit the brackets around the parameter
  • If the function needs a return value and only contains one line, you can omit the return statement

Knowledge Check

1. What are functions useful for?
Functions are used to repeatedly execute a block of code.
2. How do you invoke a function?
Using the name of the function followed by parenthesis (and parameters if needed).
3. What are anonymous functions?
They are functions that use the function keyword but have no name.
4. What is function scope?
A function scope is the contained block of code inside the function, but is inaccessible outside of it.
5. What are return values?
The values returned by the function.
6. What are arrow functions?
They are a shorter and alternative to anonymous functions.

Resources

The Odin Project Project
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions

Top comments (0)