JavaScript Functions

Reusable Code Blocks

Functions are reusable blocks of code that perform a specific task.

Functions can take inputs (parameters) and return outputs (return values).

// Function Declaration
function greet(name) {
  return 'Hello, ' + name + '!';
}

// Function Expression
const sayHello = function(name) {
  return `Hello, ${name}!`;
};

// Arrow Function
const greetUser = (name) => {
  return `Hello, ${name}!`;
};

// Short Arrow Function
const add = (a, b) => a + b;

// Function with Multiple Parameters
function calculateArea(width, height) {
  return width * height;
}

// Function with Default Parameters
function greetUser(name = 'Guest') {
  return `Welcome, ${name}!`;
}

// Calling Functions
let message = greet('John');
console.log(message);  // Hello, John!

let sum = add(5, 3);
console.log(sum);  // 8
  • function keyword - Declares a function
  • Parameters - Input values in parentheses
  • return - Sends value back to caller
  • Arrow functions => - Modern syntax
  • Default parameters - Fallback values
  • Function expression - Function as value
  • Functions are first-class objects

Try Functions

<div class="function-demo">
  <input type="text" id="userName" placeholder="Enter your name">
  <button onclick="greetUser()">Greet</button>
  <div id="greeting"></div>
  
  <hr style="margin: 20px 0;">
  
  <input type="number" id="num1" value="5" style="width: 80px;">
  <input type="number" id="num2" value="3" style="width: 80px;">
  <button onclick="calculateSum()">Add Numbers</button>
  <div id="sum"></div>
</div>

Note: Functions make your code DRY (Don't Repeat Yourself). Use them for any code you'll use more than once!