DEV Community

Cover image for Day 5: Understanding Functions in JavaScript
Dipak Ahirav
Dipak Ahirav

Posted on

Day 5: Understanding Functions in JavaScript

Introduction

Welcome to Day 5 of your JavaScript journey! Yesterday, we explored control structures, learning how to make decisions and repeat actions in our code. Today, we'll dive into functions, which are essential for organizing and reusing code in JavaScript.

please subscribe to my YouTube channel to support my channel and get more web development tutorials.

Functions

Functions are blocks of code designed to perform a particular task. They help to make your code more modular, reusable, and easier to read.

1. Function Declaration

A function declaration defines a function with the specified parameters.

Syntax:

function functionName(parameters) {
  // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

Example:

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

greet("Alice"); // Output: Hello, Alice!
greet("Bob");   // Output: Hello, Bob!
Enter fullscreen mode Exit fullscreen mode

2. Function Expression

A function expression defines a function as part of an expression. It can be anonymous or named.

Syntax:

const functionName = function(parameters) {
  // code to be executed
};
Enter fullscreen mode Exit fullscreen mode

Example:

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

greet("Charlie"); // Output: Hello, Charlie!
Enter fullscreen mode Exit fullscreen mode

3. Arrow Functions

Arrow functions provide a shorter syntax for writing functions. They are anonymous and cannot be used as constructors.

Syntax:

const functionName = (parameters) => {
  // code to be executed
};
Enter fullscreen mode Exit fullscreen mode

Example:

const greet = (name) => {
  console.log("Hello, " + name + "!");
};

greet("Dave"); // Output: Hello, Dave!
Enter fullscreen mode Exit fullscreen mode

Parameters and Arguments

Functions can accept parameters, which are placeholders for the values you pass to the function (arguments).

Example:

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

let sum = add(5, 3);
console.log(sum); // Output: 8
Enter fullscreen mode Exit fullscreen mode

Return Statement

The return statement specifies the value to be returned by the function.

Example:

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

let product = multiply(4, 7);
console.log(product); // Output: 28
Enter fullscreen mode Exit fullscreen mode

Function Scope

Variables declared inside a function are local to that function and cannot be accessed outside it.

Example:

function scopeTest() {
  let localVar = "I am local";
  console.log(localVar); // Output: I am local
}

scopeTest();
// console.log(localVar); // Error: localVar is not defined
Enter fullscreen mode Exit fullscreen mode

Practical Examples

Example 1: Function to calculate the area of a rectangle

function calculateArea(width, height) {
  return width * height;
}

let area = calculateArea(5, 10);
console.log("Area:", area); // Output: Area: 50
Enter fullscreen mode Exit fullscreen mode

Example 2: Function to find the maximum of two numbers

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

let max = findMax(8, 12);
console.log("Max:", max); // Output: Max: 12
Enter fullscreen mode Exit fullscreen mode

Example 3: Arrow function to check if a number is even

const isEven = (number) => {
  return number % 2 === 0;
};

console.log(isEven(4)); // Output: true
console.log(isEven(7)); // Output: false
Enter fullscreen mode Exit fullscreen mode

Practice Activities

1. Practice Code:

  • Write functions using function declarations, function expressions, and arrow functions.
  • Create functions with parameters and return values.

2. Mini Project:

  • Create a simple script that takes a number from the user and uses a function to determine if the number is prime.

Example:

function isPrime(number) {
  if (number <= 1) {
    return false;
  }
  for (let i = 2; i < number; i++) {
    if (number % i === 0) {
      return false;
    }
  }
  return true;
}

let num = parseInt(prompt("Enter a number:"));
if (isPrime(num)) {
  console.log(num + " is a prime number.");
} else {
  console.log(num + " is not a prime number.");
}
// If the user enters 5, the output will be:
// 5 is a prime number.
Enter fullscreen mode Exit fullscreen mode

Summary

Today, we explored functions in JavaScript. We learned about function declarations, function expressions, and arrow functions. We also covered parameters, arguments, return statements, and function scope. Understanding functions is crucial for creating modular and reusable code.

Stay tuned for Day 6, where we'll dive into arrays and their methods in JavaScript!

Feel free to leave your comments or questions below. If you found this guide helpful, please share it with your peers and follow me for more web development tutorials. Happy coding!

Follow and Subscribe:

Top comments (1)

Collapse
 
pengeszikra profile image
Peter Vivo

Missing the posibilites of use standard function as instance:

let seller = new (function Store ( state ) {
    this.state = [state];
    this.add = function (item) { this.state.push(item) }
    this.store = function (){ return this.state.join(' - ') }
})('initial item')

seller.add('something else')
seller.store() // ->  initial item - something else'
Enter fullscreen mode Exit fullscreen mode

This way function are backbone of OOP programming in JS - I am FP fun, so my advice use arrow function which are cannot make instance with a new