Functions

Functions are fundamental building blocks in JavaScript. They allow you to encapsulate a block of code, give it a name, and reuse it throughout your program.

Defining and Calling Functions

JavaScript supports functions via the function keyword. A standard function declaration includes the name, parentheses for optional parameters, and curly braces containing the logic to execute.

// Function declaration
function getSum(a, b) {
  return a + b;
}

// Function call
const result = getSum(60, 9);

console.log(result);
// Output: 69

Practical Example

You will often need to manipulate strings, such as adding personalization by using a customer’s name within a template.

// A simple function to concatenate strings
function concatStrings(str1, str2) {
  return str1 + str2;
}

console.log(concatStrings("Lane,", " happy birthday!")); 
// Output: Lane, happy birthday!

console.log(concatStrings("Naomi,", " can you call me?")); 
// Output: Naomi, can you call me?