JavaScript Functions: Declarations, Parameters and Return
Learn how to write reusable JavaScript functions: declarations, expressions, parameters, return values and default parameters, with practical examples.
What you will learn
So far, every line of code you wrote ran once, in order. But what if you need the same steps in ten different places, like calculating a discount, or greeting a user? Copying and pasting is slow and risky. A function lets you write the steps once, give them a name, and use them whenever you like. In this lesson you will learn how to create functions, give them inputs (parameters), get an answer back (return), and set default values.
What is a function?
A function is a reusable block of code that does one job.
Think of a juice machine:
- You put in fruit (the input).
- The machine does its work (the code inside).
- You get juice (the output).
You do not rebuild the machine each time. You just use it. Functions work the same way, and they follow a rule programmers love: DRY (Don’t Repeat Yourself).
Functions give you:
- Reuse: write once, use many times.
- Organisation: break a big problem into small named pieces.
- Easy fixes: change the code in one place, and every use is updated.
Your first function
function greet() {
console.log("Hello, welcome to MyCodeNest!");
}
greet();
greet();
Output:
Hello, welcome to MyCodeNest!
Hello, welcome to MyCodeNest!
There are two steps here:
- Declare (define) the function with the
functionkeyword, a name, brackets()and a body in{ }. - Call (invoke) it by writing its name followed by
().
function name ( parameters ) {
// body: the code to run
}
Important: declaring a function does not run it. The code inside runs only when you call it.
Calling needs the brackets
function greet() {
console.log("Hello!");
}
greet(); // runs the function
greet; // does nothing! This is just the function itself, not a call
Parameters and arguments
A function becomes powerful when it can work with different inputs. Inputs are called parameters.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Riya");
greet("Karan");
Output:
Hello, Riya!
Hello, Karan!
Two words that are easy to mix up:
- A parameter is the variable name in the function definition:
name. - An argument is the real value you pass when you call it:
"Riya".
Think of a parameter as an empty slot and an argument as what you put in it.
Multiple parameters
Separate them with commas. The arguments are matched by position, from left to right.
function introduce(name, age) {
console.log(`${name} is ${age} years old.`);
}
introduce("Riya", 20); // "Riya is 20 years old."
introduce(20, "Riya"); // "20 is Riya years old." (wrong order!)
Too few or too many arguments
JavaScript does not complain about the number of arguments:
function introduce(name, age) {
console.log(name, age);
}
introduce("Riya"); // "Riya" undefined (missing = undefined)
introduce("Riya", 20, "Delhi"); // "Riya" 20 (extra is ignored)
A missing argument becomes undefined. You will see how to handle that with default values shortly.
The return statement
So far our functions only printed something. Often you want the function to give back a result that you can store and use. That is what return does.
function add(a, b) {
return a + b;
}
const result = add(5, 3);
console.log(result); // 8
console.log(add(10, 20) * 2); // 60
The function call add(5, 3) is replaced by the returned value, so add(5, 3) is the same as 8 in your code.
return ends the function
Nothing after return runs:
function check(age) {
if (age >= 18) {
return "Adult";
}
return "Minor";
console.log("This line never runs");
}
console.log(check(20)); // "Adult"
console.log(check(10)); // "Minor"
If age is 18 or more, the function returns "Adult" and stops immediately. This style is very common, and it keeps code flat and easy to read.
No return means undefined
function sayHi() {
console.log("Hi!");
}
const value = sayHi(); // prints "Hi!"
console.log(value); // undefined
console.log vs return
This is the most common confusion for beginners:
console.log() |
return |
|
|---|---|---|
| What it does | Shows a value in the console | Gives a value back to the code that called the function |
| Can you use the result later? | No | Yes |
| Typical use | Testing and debugging | Real work |
function addAndPrint(a, b) {
console.log(a + b); // you can see it, but cannot use it
}
function addAndReturn(a, b) {
return a + b; // you can use it anywhere
}
const x = addAndPrint(2, 3); // prints 5, x is undefined
const y = addAndReturn(2, 3); // prints nothing, y is 5
console.log(x, y); // undefined 5
Tip: write functions that return a result, and decide outside the function what to do with it (print it, show it on the page, store it).
Function expressions
There is a second way to create a function: put it inside a variable.
const multiply = function (a, b) {
return a * b;
};
console.log(multiply(4, 5)); // 20
This is called a function expression. The function has no name of its own, and the variable multiply holds it. Notice the ; at the end, because it is a normal const statement.
Declaration vs expression
// Function declaration
function add(a, b) {
return a + b;
}
// Function expression
const subtract = function (a, b) {
return a - b;
};
They work almost the same, but there is one important difference: declarations can be called before they appear in the code, and expressions cannot.
console.log(square(4)); // 16 (works!)
function square(n) {
return n * n;
}
console.log(cube(2)); // ReferenceError: Cannot access 'cube' before initialization
const cube = function (n) {
return n * n * n;
};
This behaviour is called hoisting, and a later lesson explains it fully. For now: define your functions before you use them, and everything is safe.
Default parameters
What if an argument is missing? You can give a parameter a default value, which is used when no argument is given.
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
console.log(greet("Riya")); // "Hello, Riya!"
console.log(greet()); // "Hello, Guest!"
More examples:
function calculatePrice(price, quantity = 1, taxRate = 0.18) {
return price * quantity * (1 + taxRate);
}
console.log(calculatePrice(100)); // 118
console.log(calculatePrice(100, 3)); // 354
console.log(calculatePrice(100, 3, 0.05)); // 315
When is the default used?
The default is used only when the argument is undefined (missing). Other “empty-looking” values are kept:
function show(value = "default") {
console.log(value);
}
show(); // "default"
show(undefined); // "default"
show(null); // null (null is a real value)
show(""); // "" (empty text is a real value)
show(0); // 0
Defaults can use earlier parameters
function createUser(name, username = name.toLowerCase()) {
return `${name} (@${username})`;
}
console.log(createUser("Riya")); // "Riya (@riya)"
console.log(createUser("Riya", "riya_99")); // "Riya (@riya_99)"
Put parameters that have defaults at the end, so callers can leave them out.
Returning more than one value
A function can return only one thing, but that one thing can be an array or an object holding several values. (You will study both soon.)
function getMinMax(a, b) {
return {
min: Math.min(a, b),
max: Math.max(a, b)
};
}
const result = getMinMax(8, 3);
console.log(result.min, result.max); // 3 8
Functions calling other functions
Real programs are built from small functions that use each other:
function calculateTax(amount) {
return amount * 0.18;
}
function calculateTotal(amount) {
return amount + calculateTax(amount);
}
function formatPrice(amount) {
return "₹" + amount.toFixed(2);
}
console.log(formatPrice(calculateTotal(1000))); // "₹1180.00"
Each function does one small job and has a clear name. That makes the code easy to read, test and fix.
Local variables
Variables created inside a function exist only inside it. They are called local variables. Each call gets its own fresh set.
function makeMessage() {
const message = "I live inside the function";
return message;
}
console.log(makeMessage()); // works
console.log(message); // ReferenceError: message is not defined
A function can read variables from outside it, but the outside cannot read the inside. The arrow functions and scope lessons look at this in more detail.
Naming functions
- Use camelCase, like variables:
calculateTotal, notcalculate_totalorCalculateTotal. - Start with a verb, because a function does something:
getUser,calculateTax,showMessage,sendEmail. - Functions that answer a yes/no question usually start with
is,hasorcan:isAdult,hasDiscount,canVote. - Give each function one clear job. If you struggle to name it, it probably does too much.
Real-life use cases
1. Area of shapes
function circleArea(radius) {
return Math.PI * radius ** 2;
}
function rectangleArea(width, height) {
return width * height;
}
console.log(circleArea(5).toFixed(2)); // "78.54"
console.log(rectangleArea(4, 6)); // 24
2. A yes/no check
function isEven(number) {
return number % 2 === 0;
}
function isAdult(age) {
return age >= 18;
}
console.log(isEven(10)); // true
console.log(isAdult(15)); // false
Because these return true or false, they fit perfectly into if statements:
function isAdult(age) {
return age >= 18;
}
if (isAdult(20)) {
console.log("Entry allowed");
}
3. Temperature converter
function celsiusToFahrenheit(celsius) {
return (celsius * 9) / 5 + 32;
}
console.log(celsiusToFahrenheit(37)); // 98.6
console.log(celsiusToFahrenheit(0)); // 32
4. Discount calculator with a default
function applyDiscount(price, discountPercent = 10) {
const discount = (price * discountPercent) / 100;
return price - discount;
}
console.log(applyDiscount(500)); // 450 (default 10%)
console.log(applyDiscount(500, 25)); // 375
5. Grade finder
function getGrade(marks) {
if (marks >= 90) return "A+";
if (marks >= 75) return "A";
if (marks >= 60) return "B";
if (marks >= 40) return "C";
return "Fail";
}
console.log(getGrade(82)); // "A"
console.log(getGrade(35)); // "Fail"
No else is needed, because each return ends the function right away.
6. Capitalise a name
function capitalize(text) {
return text[0].toUpperCase() + text.slice(1).toLowerCase();
}
console.log(capitalize("rIYA")); // "Riya"
7. Count vowels (reusing a function)
function countVowels(text) {
let count = 0;
for (const letter of text.toLowerCase()) {
if ("aeiou".includes(letter)) {
count++;
}
}
return count;
}
console.log(countVowels("Hello World")); // 3
console.log(countVowels("JavaScript")); // 3
Write the logic once, and use it for any text.
8. Random number between two values
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 6)); // a dice roll
console.log(randomInt(100, 999)); // a 3-digit number
Common mistakes
-
Forgetting the brackets when calling.
greetdoes nothing. Writegreet(). -
Forgetting
return. The function gives backundefined, and your variable ends up empty. -
Using
console.loginstead ofreturn. You can see the value, but you cannot use it later. -
Putting a line break after
return. JavaScript adds a semicolon for you, and the function returnsundefined:function getNumber() { return 42; } console.log(getNumber()); // undefinedAlways start the returned value on the same line as
return. -
Passing arguments in the wrong order.
introduce(20, "Riya")mixes up the values. -
Calling a function expression before it is defined. It gives a
ReferenceError. -
Using a local variable outside the function. It does not exist there.
-
Writing code after
return. It never runs. -
Making one giant function. Split big jobs into small named functions.
-
Expecting a default value for
nullor"". Defaults apply only toundefined.
Practice
-
Write a function
sayHello(name)that returns"Hello, <name>!". Call it with your name and print the result. -
Write
square(n)that returnsn * n, andcube(n)that returnsn * n * n. -
Write
isPositive(number)that returnstruewhen the number is greater than 0. -
Write
calculateBill(price, quantity, taxRate = 0.05)and test it with and without the third argument. -
Write
max(a, b)that returns the larger of two numbers, without usingMath.max. -
Write
fullName(first, last)that returns the name in the format"LAST, First", for example"SHARMA, Riya". -
Write
getDayType(day)that returns"Weekend"for"Saturday"and"Sunday", and"Weekday"otherwise. -
Write a function
reverseText(text)that returns the text reversed (use the loop from the loops lesson). -
Predict the output, then run it:
function mystery(a, b = a * 2) { return a + b; } console.log(mystery(3), mystery(3, 1)); -
Challenge: write
isPrime(n)that returnstrueorfalse, then use it in a loop to print all primes up to 50.
Recap
- A function is a named, reusable block of code. It follows the DRY idea: write once, use many times.
- Declare with
function name(parameters) { ... }, and call withname(arguments). Brackets are needed to call. - Parameters are the placeholders. Arguments are the real values. They match by position.
returnsends a value back and ends the function. Noreturnmeansundefined.- Use
returnfor results andconsole.logonly for checking. - Function expressions store a function in a variable. Declarations can be called before they are defined, expressions cannot.
- Default parameters (
name = "Guest") apply only when the argument isundefined. - Variables created inside a function are local.
- Name functions with a verb in camelCase, and give each one a single job.
- Next you will learn arrow functions, a shorter way to write functions, and a first look at scope.