JavaScript Lesson 7: Functions

⚡ JavaScript CourseLesson 7 of 20 · 35% complete

Functions are the building blocks of JavaScript. There are three ways to write them — and all are common in real code.

Function Declaration

function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet("Alice")); // Hello, Alice!

// Function declarations are "hoisted"
// You can call them before they are defined
sayHi(); // works!

function sayHi() {
  console.log("Hi!");
}

Function Expression

const greet = function(name) {
  return `Hello, ${name}!`;
};

// NOT hoisted — must define before calling
console.log(greet("Bob")); // Hello, Bob!

Arrow Function (Modern JS)

// Full arrow function
const greet = (name) => {
  return `Hello, ${name}!`;
};

// Short version — implicit return
const greet2 = (name) => `Hello, ${name}!`;

// Single param — no parentheses needed
const double = n => n * 2;

// No params
const sayHi = () => console.log("Hi!");

console.log(double(5));  // 10

Default Parameters

function greet(name = "stranger", greeting = "Hello") {
  return `${greeting}, ${name}!`;
}

console.log(greet());                // Hello, stranger!
console.log(greet("Alice"));         // Hello, Alice!
console.log(greet("Bob", "Hey"));    // Hey, Bob!

Rest Parameters and Arguments

function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}

console.log(sum(1, 2, 3));        // 6
console.log(sum(1, 2, 3, 4, 5));  // 15

🏋️ Practice Task

Create a temperature converter with 3 functions: celsiusToFahrenheit(c), fahrenheitToCelsius(f), kelvinToCelsius(k). Test each. Write them as arrow functions with implicit returns.

💡 Hint: Formulas: C to F = (c * 9/5) + 32. F to C = (f – 32) * 5/9. K to C = k – 273.15

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *