Defining and Calling
Functions in JavaScript



What is a Function?

A function in JavaScript is a block of reusable code that performs a specific task. Functions help in organizing code, avoiding repetition, and making programs easier to understand and maintain.

How to Define a Function

There are multiple ways to define a function in JavaScript. The most basic one is using the function keyword.

Example 1: Basic Function Definition and Call


function greet() {
  console.log("Hello, welcome to JavaScript!");
}

greet();
    

Output:

Hello, welcome to JavaScript!
    

This is a simple function named greet that prints a message. We call it using greet().

Example 2: Function with Parameters


function greetUser(name) {
  console.log("Hello, " + name + "!");
}

greetUser("Alice");
greetUser("Bob");
    

Output:

Hello, Alice!
Hello, Bob!
    

Here, name is a parameter. When calling the function, you pass an argument like "Alice". The function uses it to personalize the output.

Question:

Can a function have more than one parameter?

Answer: Yes! You can pass multiple parameters separated by commas.

Example 3: Multiple Parameters


function add(a, b) {
  console.log("Sum is:", a + b);
}

add(5, 7);
add(10, 15);
    

Output:

Sum is: 12
Sum is: 25
    

Returning a Value from a Function

Functions can also return a value using the return keyword.

Example 4: Function with Return


function square(num) {
  return num * num;
}

let result = square(6);
console.log("Square is:", result);
    

Output:

Square is: 36
    

This function computes the square of a number and returns the result. We can store the return value in a variable.

Function Syntax Recap


function functionName(parameters) {
  // code to execute
  return value; // optional
}
    

Best Practices

Question:

What happens if you define a function but never call it?

Answer: The function code won't run. Functions only execute when they are called.

Try it Yourself

Define a function that takes your name and age, and logs a greeting like: "Hi, I'm Alex and I'm 25 years old."


// Your turn to practice
function introduce(name, age) {
  console.log("Hi, I'm " + name + " and I'm " + age + " years old.");
}

introduce("Alex", 25);
    

Output:

Hi, I'm Alex and I'm 25 years old.
    

Summary



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M