JavaScript Foundations·Language basics

Functions and scope

Package logic into reusable functions and understand where variables live.

Beginner 12 min read Lesson 2 of 480 Challenge included
What you will be able to do
  • Declare functions and arrow functions
  • Return values
  • Understand block scope

Functions turn repeated logic into a named unit. Parameters are inputs, return is the output. A function without a return gives undefined.

functions.jsJavaScript
function progressPercent(done, total) {
  if (total === 0) return 0;
  return Math.round((done / total) * 100);
}

const label = (percent) => `${percent}% complete`;

console.log(label(progressPercent(7, 10))); // "70% complete"
Parameter
A named input in the function definition.
Argument
The actual value passed when calling the function.
Scope
The region where a variable can be accessed.
Closure
A function remembering variables from where it was created.
Your turn

Write a formatter

Medium

Write a function formatPrice(amount) that returns a string like "$12.50".

JAVASCRIPT · starter
function formatPrice(amount) {
  // your code here
}
Check your understanding before moving on.
Knowledge checkQuestion 1

What does a function return if it has no return statement?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Arrays and objects
Lesson 2 of 480 · 0% of course