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
function sayHello() {
console.log("Hello from Workownix!");
}
sayHello(); // calling (running) the function
sayHello();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
function greet(name, city) {
console.log("Welcome " + name + " from " + city);
}
greet("Ali", "Karachi");
greet("Sana", "Hyderabad");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
<!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 »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
function deliveryCharge(city = "Karachi") {
return city === "Karachi" ? 150 : 300;
}
console.log(deliveryCharge()); // 150
console.log(deliveryCharge("Quetta")); // 300Functions Used With Events
Functions are often run when the user does something, like clicking a button.
Example
<!DOCTYPE html>
<html>
<body>
<input id="celsius" type="number" value="35"> °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 + " °C is " + f + " °F";
}
</script>
</body>
</html>Try it Yourself »Function Expressions
A function can also be stored in a variable:
Example
const square = function (n) {
return n * n;
};
console.log(square(6)); // 36Arrow Functions
Arrow functions are a shorter way to write a function expression:
Example
const square = (n) => n * n;
const add = (a, b) => a + b;
const hello = () => "Hello!";
console.log(square(5), add(2, 3), hello());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));
