🟨 JavaScript tutorial for beginners · Class 8 · Lesson 3 of 18 · Free
Functions – Write Reusable Code in JavaScript
⏱ About 30 minutes · ▶ run real JavaScript here — nothing to install · no sign-in
In this lesson you will
- Create a function and call it with different arguments
- Return a value from a function and use it in more calculations
- Write short arrow functions and know where a variable can be used
Your class teacher writes the same report-card sentence 40 times: "Name scored X out of 100." What if she could write it once and just change the name and marks? That is exactly what a function does — write the steps once, use them again and again.
What is a function in JavaScript?
A function is a named set of steps. You write it once with the word function. Then you run it any time by writing its name and ( ). Running it is called calling the function.
Making the function does not run it. Nothing happens until you call it. Watch the animation: JavaScript jumps into the function, runs it, then comes back.
You already used built-in functions: console.log() and Number() from Lesson 2. Now you make your own.
1function sayGoodMorning() {2 console.log("Good morning, class!");3 console.log("Please open your books.");4}5▶console.log("Bell rings...");7sayGoodMorning();8sayGoodMorning();
No variables yet.
▌✏️ Change this code and run it yourself
Bell rings...Good morning, class!Please open your books.Good morning, class!Please open your books.
💡 Try it: add a third sayGoodMorning(); line and run again.
What are parameters and arguments in JavaScript functions?
A function becomes useful when it can work with different values. A parameter is a variable in the brackets of the function, like name here. It is a placeholder.
An argument is the real value you pass when you call it, like "Asha". Each call fills the parameter with a new value.
A function can have many parameters, separated by commas. Pass the arguments in the same order.
1function reportLine(name, marks) {2 console.log(`${name} scored ${marks} out of 100.`);3}4▶reportLine("Asha", 92);6reportLine("Rahul", 78);7reportLine("Fatima", 85);
No variables yet.
▌✏️ Change this code and run it yourself
Asha scored 92 out of 100.Rahul scored 78 out of 100.Fatima scored 85 out of 100.
What does return do in a JavaScript function?
console.log only shows a value on the screen. return hands the value back to the code that called the function. You can then store it, print it or use it in more maths.
return also ends the function at once. Any line after it does not run.
A function with no return gives back undefined. That is why a forgotten return is a common bug.
1function addGST(price) {2 return price + price * 18 / 100;3}4▶const bat = addGST(1000);6const ball = addGST(200);7console.log("Bat:", bat);8console.log("Ball:", ball);9console.log("Total:", bat + ball);
No variables yet.
▌✏️ Change this code and run it yourself
Bat: 1180Ball: 236Total: 1416
💡 Try it: change 18 to 12 for a lower tax rate.
What is an arrow function in JavaScript?
An arrow function is a shorter way to write a function. You store it in a const. The arrow => separates the parameters from the body.
If the body is one expression, you can leave out { } and return. The value is returned automatically.
Both styles do the same job. You will see arrow functions everywhere, especially with events in Lesson 5.
494925.5
Where can I use a variable that is made inside a function?
A variable made inside a function lives only inside it. This is called scope. Outside the function, that name does not exist.
But a function can read variables made outside it, at the top of the program.
Scope is good. Two functions can both use a name like total without getting mixed up.
Dev | Green Valley Schoolundefined
💡 typeof card is "undefined" because card only exists inside idCard.
How do I use a JavaScript function on a web page?
Functions are perfect for pages. Here, tiffinBill() does the maths. The button only reads the input, calls the function and shows the answer.
Keeping the maths in its own function means you can test it in the console too. Lesson 4 explains the page parts in detail.
📄 HTML of the page (tap to see / edit)
Test: 3 plates cost ₹120
🤔 Predict the output
Think like JavaScript: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
function double(x) {
return x * 2;
}
console.log(double(3) + 1);Question 2. What does this print?
function hello() {
console.log("Hi");
}
console.log(hello());Question 3. What does this print?
const add = (a, b) => a + b;
console.log(add("2", 3));🧩 Your challenge
Write a function percentage(marks, total) that returns the percentage. Then write grade(percent) that returns "A" if percent is 80 or more, otherwise "B". Use them for 45 out of 50. Expected output: 90 Grade: A
90 Grade: A
⚠️ Common mistakes (and how to fix them)
❌ Wrong
function area(length, width) {
length * width;
}
console.log(area(5, 4));No error, but it prints undefined instead of 20. The function works out the answer and then throws it away.
✅ Right
function area(length, width) {
return length * width;
}
console.log(area(5, 4));Use return to send the result back to the caller.
❌ Wrong
console.log(cube(3)); const cube = (n) => n * n * n;
ReferenceError: Cannot access 'cube' before initialization
✅ Right
const cube = (n) => n * n * n; console.log(cube(3));
An arrow function stored in a const does not exist until that line runs. Define it first, then call it.
❌ Wrong
function makeTotal() {
const total = 50 + 30;
}
makeTotal();
console.log(total);ReferenceError: total is not defined
✅ Right
function makeTotal() {
const total = 50 + 30;
return total;
}
console.log(makeTotal());total lives only inside makeTotal (scope). Return the value and use the function's result outside.
📌 Remember
- A function is a named set of steps; it runs only when you call it with ( ).
- Parameters are placeholders; arguments are the real values you pass in.
- return sends a value back and ends the function; no return means undefined.
- Arrow functions are a short form: const square = (n) => n * n;
- Variables made inside a function exist only inside it (scope).
- Keep the maths in a function and let the page code just call it.
Finished the quiz and the challenge?
Questions students ask
What is the difference between a parameter and an argument?
A parameter is the name in the function's brackets, like marks in function grade(marks). An argument is the actual value you pass when calling it, like 85 in grade(85).
Should I use console.log or return in a function?
Use return when other code needs the answer, for example to add it or show it on a page. Use console.log to look at values while testing. Most useful functions return something.
When should I use an arrow function in JavaScript?
Arrow functions are great for short, one-line jobs and for event handlers. Normal function declarations are clear for bigger, named tasks. Both are correct; pick the one that reads best.
Can I call a JavaScript function before I write it?
A normal function declaration (function name() {}) can be called earlier in the file, because JavaScript sets it up first. An arrow function in a const cannot — you get a ReferenceError.