Lesson 8 - Function

Functions in JavaScript

A function is a reusable block of code that performs a specific task. Instead of writing the same code again and again, you can put it inside a function and call it whenever needed.

function sayHello() {
  console.log("Hello!");
}

// Call (use) the function
sayHello();
❓Why use functions?
  • They make code organized and readable.
  • You can reuse the same code multiple times.
  • They allow you to break problems into smaller parts.
Functions with parameters
function greet(name) {
  console.log("Hello,", name, "!");
}

greet("Alice");
greet("Bob");

You can give a function inputs (called parameters) to make it more flexible

Functions that return values
function add(a, b) {
  return a + b;
}

let result = add(5, 3);
console.log("Result:", result);

Functions can also return results using the return keyword

Arrow functions (a shorter way)
const add = (a, b) => {
  return a + b;
};

console.log(add(5, 3));

It works the same way as function, just written with an arrow =>.

📋 Key Points
  • Use function to define a function.
  • Use parentheses () to call a function.
  • Use curly braces { } to wrap the code inside the function.
  • Functions can take parameters (inputs).
  • Functions can return a value.

Say Hello

function sayHello() {
  console.log("Hello, everyone!");
}

sayHello();

💡 Try changing the message inside console.log().


Say Your Name

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

greet("Anna");

💡 Try greeting yourself by changing the name.


Add Two Numbers

function addNumbers(a, b) {
  return a + b;
}

console.log(addNumbers(2, 3));

💡 Try adding bigger numbers.


Double a Number

function double(x) {
  return x * 2;
}

console.log(double(6));

💡 Try doubling your age!


Make a Sentence

function makeSentence(name, food) {
  return name + " likes " + food;
}

console.log(makeSentence("Sam", "pizza"));

💡 Try your own name and favorite food.


Find the Bigger Number

function bigger(a, b) {
  if (a > b) {
    return a;
  } else {
    return b;
  }
}

console.log(bigger(8, 3));

💡 Try two different numbers.


Repeat a Word

function repeatWord(word, times) {
  return word.repeat(times);
}

console.log(repeatWord("Hi ", 3));

💡 Try repeating your name 5 times.


Multiply Three Numbers

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

console.log(multiply(2, 3, 4));

💡 Try three different numbers.


Check Even or Odd

function checkNumber(n) {
  if (n % 2 === 0) {
    console.log("Even");
  } else {
    console.log("Odd");
  }
}

checkNumber(7);

💡 Try with your favorite number.


Make a Birthday Song

function birthdaySong(name) {
  console.log("Happy Birthday to you!");
  console.log("Happy Birthday dear " + name);
}

birthdaySong("Liam");

💡 Try singing the song for your friend!

Back Next Lesson