JavaScript Functions

Declarations, parameters, return and arrow functions.

✍️ 3 exercises + code challenge in this lesson

A function is a reusable block of code that runs when it is called.

  • Declare it: function name(param1, param2) { ... }
  • Call it: name(arg1, arg2)
  • return sends a value back and stops the function.
  • Parameters can have defaults: function greet(name = "Guest")

Arrow functions

A shorter syntax: const add = (a, b) => a + b;. With one expression, the result is returned automatically.

Key Takeaways: JavaScript Functions

Mastering JavaScript Functions helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Functions Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
function toCelsius(f) {
  return (5 / 9) * (f - 32);
}

function greet(name = "Guest") {
  return "Hello, " + name + "!";
}

const square = n => n * n;
const add = (a, b) => a + b;

log("77°F =", toCelsius(77).toFixed(1), "°C");
log(greet("Usman"));
log(greet());
log("square(9) =", square(9));
log("add(2, 3) =", add(2, 3));
</script>
Free sign-in required · Google login available

JavaScript Functions Practice Exercises

Check what you learned in “JavaScript Functions”.

/ 3 solved
Fill in the blank

Return the sum from the function.

function add(a, b) {
   a + b;
}
✓ Correct! Not quite. Try again.
Multiple choice

Which is a valid arrow function?

✓ Correct! Not quite. Try again.
Code challenge

Write a function double(n) that returns n * 2, then log double(21).

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services