JavaScript Tutorial menu

JavaScript Functions

A function is a block of code with a name. You write it once and run it whenever you need it.

Writing a Function

Use the function keyword, a name, brackets () and a code block { }:

Example

javascript
function sayHello() {
  console.log("Hello from Workownix!");
}

sayHello();   // calling (running) the function
sayHello();
Output
Hello from Workownix!
Hello from Workownix!

The code inside the function runs only when the function is called with its name and brackets.

Parameters and Arguments

Parameters are names listed inside the brackets. They receive values, called arguments, when the function is called.

Example

javascript
function greet(name, city) {
  console.log("Welcome " + name + " from " + city);
}

greet("Ali", "Karachi");
greet("Sana", "Hyderabad");
Output
Welcome Ali from Karachi
Welcome Sana from Hyderabad

Returning a Value

return sends a result back to the place where the function was called. The function stops at return.

Example

html
<!DOCTYPE html>
<html>
<body>

<h2>Fee Calculator</h2>
<p id="demo"></p>

<script>
function totalFee(monthly, months) {
  return monthly * months;
}

let fee = totalFee(3500, 4);
document.getElementById("demo").innerHTML = "Total fee: Rs " + fee;
</script>

</body>
</html>
Try it Yourself »
Output
Total fee: Rs 14000

Why Use Functions?

  • Reuse: write the code once, use it many times
  • Readability: a name like calculateDiscount() explains what the code does
  • Easy changes: fix a bug in one place, and it is fixed everywhere

Default Parameters

If an argument is missing, its parameter is undefined. You can give a default value instead:

Example

javascript
function deliveryCharge(city = "Karachi") {
  return city === "Karachi" ? 150 : 300;
}

console.log(deliveryCharge());          // 150
console.log(deliveryCharge("Quetta"));  // 300

Functions Used With Events

Functions are often run when the user does something, like clicking a button.

Example

html
<!DOCTYPE html>
<html>
<body>

<input id="celsius" type="number" value="35"> &deg;C
<button onclick="convert()">Convert</button>
<p id="result"></p>

<script>
function convert() {
  let c = Number(document.getElementById("celsius").value);
  let f = c * 9 / 5 + 32;
  document.getElementById("result").innerHTML = c + " &deg;C is " + f + " &deg;F";
}
</script>

</body>
</html>
Try it Yourself »

Function Expressions

A function can also be stored in a variable:

Example

javascript
const square = function (n) {
  return n * n;
};
console.log(square(6));   // 36

Arrow Functions

Arrow functions are a shorter way to write a function expression:

Example

javascript
const square = (n) => n * n;
const add = (a, b) => a + b;
const hello = () => "Hello!";

console.log(square(5), add(2, 3), hello());
Output
25 5 Hello!

If the body is a single expression, its value is returned automatically. With curly brackets, you need return.

Variables created inside a function are local: they exist only inside that function. Code outside cannot see them.

Exercise

Exercise

What will this code show? function double(n) { return n * 2; } console.log(double(7));

Learn JavaScript with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp