JavaScript function

Introduction: What is a Javascript Function?

A Javascript Function is a piece of code that performs a specific task when it is called. It takes one or more inputs and returns an output. Functions are useful for code reuse and organization. They can be used to break down a complex problem into smaller, manageable pieces. Functions also allow developers to create code that can be used again and again with different inputs.

What are the Advantages of Using a JavaScript Function?

Functions in JavaScript can be used to group together the related pieces of code into one place, which makes the code easier to read and understand. This is important because when you’re working on large projects, you want to avoid having sections of your project that become difficult or impossible to work on due to how complex they are or how much they overlap with other sections of the project. Functions can also be useful for making sure that you’re not duplicating any lines of code that have been used elsewhere in the project, which is something that should always be avoided when possible (unless there’s some good reason for doing so).

Function syntax in JavaScript

The syntax for a function in JavaScript is as follows:

function name(parameters) { // code to be executed }

function take input as argument and return result as retrun value

Functions Examples

function add(a, b) {
    return a + b;

function subtract(a, b) {
    return a - b;

function multiply(a, b) {
    return a * b;

function divide(a, b) {
    return a / b;

console.log(add(3, 4)); // 7
console.log(subtract(10, 5)); // 5
console.log(multiply(3, 4); // 12
console.log(divide(10, 5)); // 2

Here’s an example of how the code would look:

function triangleArea(base, height) {
   return (base * height)/2;

Once the function is defined, we can call it as many times as we want, passing in different values for the base and height.

let area = triangleArea(5, 10);
console.log(area); // Outputs 25

In this example, we passed in 5 for the base and 10 for the height. The function then returned 25, which is the area of the triangle.

By using functions, we can easily create a reusable block of code that can be used to calculate the area of any triangle.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at

%d bloggers like this: