Lesson 4 of 30

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).

Example
// 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
HTML
<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>
CSS
.function-demo { padding: 20px; background: #f0f0f0; border-radius: 8px; }
input { padding: 10px; margin: 5px; border: 1px solid #ddd; border-radius: 4px; }
button { padding: 10px 20px; background: #d1039e; color: white; border: none; border-radius: 5px; cursor: pointer; margin: 5px; }
#greeting, #sum { margin-top: 15px; padding: 15px; background: white; border-radius: 5px; font-weight: bold; color: #d1039e; }
JavaScript
function greetUser() {
  const name = document.getElementById('userName').value || 'Guest';
  const message = `Hello, ${name}! Welcome to JavaScript Functions!`;
  document.getElementById('greeting').innerHTML = message;
}

function calculateSum() {
  const a = parseFloat(document.getElementById('num1').value);
  const b = parseFloat(document.getElementById('num2').value);
  const sum = a + b;
  document.getElementById('sum').innerHTML = `${a} + ${b} = ${sum}`;
}
Notes
  • Functions make your code DRY (Don't Repeat Yourself). Use them for any code you'll use more than once!