DEV Community

Tony Chase
Tony Chase

Posted on

Learning JS in 30 Days - Day 6

The first five days have covered JavaScript basic syntax, variables and data types, operators and expressions, conditional statements, and loops. Today focuses on function basics, one of the most important concepts in JavaScript. Functions are the foundation of code reuse and the core building blocks for complex programs.

๐Ÿ“š Today's Learning Objectives

  • Master function definitions and calls
  • Understand parameters and return values
  • Learn function expressions and arrow functions
  • Understand function scope and the basics of closures

๐Ÿ”ง Function Basics

Functions in JavaScript are first-class citizens and are reusable blocks of code.

Why Use Functions?

// Without functions - repeated code
let num1 = 5;
let num2 = 3;
let sum1 = num1 + num2;
console.log(`5 + 3 = ${sum1}`);

let num3 = 10;
let num4 = 7;
let sum2 = num3 + num4;
console.log(`10 + 7 = ${sum2}`);

// With functions - code reuse
function add(a, b) {
  return a + b;
}

console.log(`5 + 3 = ${add(5, 3)}`);
console.log(`10 + 7 = ${add(10, 7)}`);
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ Ways to Define Functions

1. Function Declaration

// Basic syntax
function functionName(parameters) {
  // function body
  return value;
}

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

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

// Calls
console.log(greet("Alice")); // "Hello, Alice!"
console.log(calculateArea(5, 3)); // 15
Enter fullscreen mode Exit fullscreen mode

2. Function Expression

// Basic syntax
const functionName = function (parameters) {
  // function body
  return value;
};

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

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

// Calls
console.log(greet("Bob")); // "Hello, Bob!"
console.log(calculateArea(4, 6)); // 24
Enter fullscreen mode Exit fullscreen mode

3. Arrow Function (ES6)

// Basic syntax
const functionName = (parameters) => {
  // function body
  return value;
};

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

const calculateArea = (width, height) => {
  return width * height;
};

// Shorthand (single expression return)
const add = (a, b) => a + b;
const square = (x) => x * x;

// Calls
console.log(greet("Carol")); // "Hello, Carol!"
console.log(calculateArea(3, 7)); // 21
console.log(add(2, 3)); // 5
console.log(square(4)); // 16
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Š Parameters and Return Values

Using Parameters

// No-parameter function
function sayHello() {
  console.log("Hello World!");
}

// Single-parameter function
function greet(name) {
  console.log(`Hello, ${name}!`);
}

// Multiple-parameter function
function introduce(name, age, city) {
  console.log(`Name: ${name}, Age: ${age}, City: ${city}`);
}

// Default parameters (ES6)
function greetWithDefault(name = "friend") {
  console.log(`Hello, ${name}!`);
}

// Calls
sayHello();
greet("Alice");
introduce("Bob", 25, "Beijing");
greetWithDefault(); // "Hello, friend!"
greetWithDefault("David"); // "Hello, David!"
Enter fullscreen mode Exit fullscreen mode

Using Return Values

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

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

function isEven(num) {
  return num % 2 === 0;
}

// Using return values
let sum = add(5, 3);
let product = multiply(4, 6);
let evenCheck = isEven(8);

console.log(`Sum: ${sum}`); // "Sum: 8"
console.log(`Product: ${product}`); // "Product: 24"
console.log(`Is 8 even: ${evenCheck}`); // "Is 8 even: true"

// Chained calls
let result = multiply(add(2, 3), 4); // (2+3) * 4 = 20
console.log(result); // 20
Enter fullscreen mode Exit fullscreen mode

Functions Without Return Values

// Function without return (returns undefined)
function printInfo(name, age) {
  console.log(`Name: ${name}`);
  console.log(`Age: ${age}`);
}

let result = printInfo("Alice", 25);
console.log(result); // undefined
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ Advanced Function Features

Rest Parameters

function sum(...numbers) {
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  return total;
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
console.log(sum()); // 0
Enter fullscreen mode Exit fullscreen mode

Destructured Parameters

function displayUser({ name, age, city }) {
  console.log(`Name: ${name}, Age: ${age}, City: ${city}`);
}

let user = {
  name: "Alice",
  age: 25,
  city: "Beijing",
};

displayUser(user); // "Name: Alice, Age: 25, City: Beijing"
Enter fullscreen mode Exit fullscreen mode

Functions as Parameters

function calculate(a, b, operation) {
  return operation(a, b);
}

function add(x, y) {
  return x + y;
}

function multiply(x, y) {
  return x * y;
}

console.log(calculate(5, 3, add)); // 8
console.log(calculate(5, 3, multiply)); // 15

// Using arrow functions
console.log(calculate(5, 3, (x, y) => x - y)); // 2
console.log(calculate(5, 3, (x, y) => x / y)); // 1.6666666666666667
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”„ Function Expression vs Function Declaration

Differences in Hoisting

// Function declarations are hoisted
console.log(hoistedFunction()); // "I was hoisted!"

function hoistedFunction() {
  return "I was hoisted!";
}

// Function expressions are not hoisted
try {
  console.log(notHoistedFunction());
} catch (e) {
  console.log("ReferenceError");
}

const notHoistedFunction = function () {
  return "I was not hoisted";
};
Enter fullscreen mode Exit fullscreen mode

Usage Scenarios

// Function declaration - suitable for main features
function mainFunction() {
  console.log("This is a main feature");
}

// Function expression - suitable for callbacks
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function (num) {
  return num * 2;
});

// Arrow function - suitable for simple operations
const tripled = numbers.map((num) => num * 3);

console.log(doubled); // [2, 4, 6, 8, 10]
console.log(tripled); // [3, 6, 9, 12, 15]
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ Practice Exercises

Exercise 1: Calculator Function Set

// Basic calculation functions
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

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

function divide(a, b) {
  if (b === 0) {
    return "Error: Cannot divide by zero";
  }
  return a / b;
}

// Advanced calculation functions
function power(base, exponent) {
  return base ** exponent;
}

function factorial(n) {
  if (n < 0) return "Error: Negative numbers have no factorial";
  if (n === 0 || n === 1) return 1;

  let result = 1;
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
}

function fibonacci(n) {
  if (n <= 0) return "Error: Please enter a positive integer";
  if (n === 1) return 0;
  if (n === 2) return 1;

  let a = 0,
    b = 1;
  for (let i = 3; i <= n; i++) {
    let temp = a + b;
    a = b;
    b = temp;
  }
  return b;
}

// Test calculator functions
console.log("Add:", add(10, 5));
console.log("Subtract:", subtract(10, 5));
console.log("Multiply:", multiply(10, 5));
console.log("Divide:", divide(10, 5));
console.log("Power:", power(2, 3));
console.log("Factorial:", factorial(5));
console.log("Fibonacci(10):", fibonacci(10));
Enter fullscreen mode Exit fullscreen mode

Exercise 2: String Utilities

// String utility functions
function reverseString(str) {
  return str.split("").reverse().join("");
}

function isPalindrome(str) {
  const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, "");
  return cleaned === reverseString(cleaned);
}

function countWords(str) {
  return str.trim().split(/\s+/).length;
}

function capitalizeWords(str) {
  return str
    .split(" ")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join(" ");
}

function removeDuplicates(str) {
  return [...new Set(str.split(""))].join("");
}

// Tests
let testString = "Hello World Hello";
console.log("Original:", testString);
console.log("Reversed:", reverseString(testString));
console.log("Is palindrome:", isPalindrome("racecar"));
console.log("Word count:", countWords(testString));
console.log("Capitalized:", capitalizeWords("hello world"));
console.log("Deduped:", removeDuplicates(testString));
Enter fullscreen mode Exit fullscreen mode

Exercise 3: Array Utilities

// Array utility functions
function findMax(arr) {
  if (arr.length === 0) return "Array is empty";
  return Math.max(...arr);
}

function findMin(arr) {
  if (arr.length === 0) return "Array is empty";
  return Math.min(...arr);
}

function calculateAverage(arr) {
  if (arr.length === 0) return "Array is empty";
  const sum = arr.reduce((acc, num) => acc + num, 0);
  return sum / arr.length;
}

function filterEvenNumbers(arr) {
  return arr.filter((num) => num % 2 === 0);
}

function sortNumbers(arr, ascending = true) {
  return [...arr].sort((a, b) => (ascending ? a - b : b - a));
}

function removeDuplicates(arr) {
  return [...new Set(arr)];
}

// Tests
let numbers = [3, 7, 2, 9, 1, 5, 8, 4, 6];
console.log("Original:", numbers);
console.log("Max:", findMax(numbers));
console.log("Min:", findMin(numbers));
console.log("Average:", calculateAverage(numbers));
console.log("Evens:", filterEvenNumbers(numbers));
console.log("Asc:", sortNumbers(numbers));
console.log("Desc:", sortNumbers(numbers, false));
console.log("Deduped:", removeDuplicates([1, 2, 2, 3, 3, 3, 4]));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Today's Key Points Summary

  1. Function definitions: Declarations, expressions, arrow functions
  2. Parameter handling: Default, rest, destructured parameters
  3. Return values: With vs without return values
  4. Function features: Hoisting, scope, functions as parameters
  5. Usage scenarios: Choose appropriate definition style based on needs

๐Ÿ“š Tomorrow's Preview

Tomorrow will learn about scope and hoisting, including:

  • Global scope and local scope
  • Variable hoisting mechanism
  • Differences between let, const, var
  • Basics of closures

๐Ÿ’ก Learning Tips

  1. Practice more: Solidify function usage through hands-on coding
  2. Understand concepts: Focus on functions as first-class citizens
  3. Choose the right style: Select appropriate function definition style per scenario
  4. Parameter design: Design reasonable parameters and return values

This concludes the introduction to day six's learning content. Tomorrow will continue learning about scope and hoisting.

Top comments (0)