Onjsdev

Share


JavaScript Functions


By onjsdev

Jan 25th, 2024

What are JavaScript Functions?

  • Reusable blocks of code that perform specific tasks.
  • Encapsulate logic, making code modular and organized.
  • Can accept input (parameters) and produce output (return values).
  • Essential for building interactive and dynamic web applications.

A Basic Javascript Function Syntax

function functionName(parameters) {
  // Statements to be executed
  return value; // Optional
}
  • function: Keyword indicating function definition.

  • functionName: Name you assign to the function (alphanumeric, underscores, $).

  • parameters: Comma-separated list of values the function expects (optional).

  • {}: Curly braces enclosing the function's body.

  • return value: Value the function returns when executed (optional).

Function Call

Once a function is defined, you can call it by using its name followed by parentheses, optionally passing arguments if the function has parameters.

// Function declaration
function addNumbers(a, b) {
  var sum = a + b;
  return sum;
}

// Function call
var result = addNumbers(5, 10);
console.log(result); // Output: 15

Anonymous Functions (Function Expressions):

You can also create functions without naming them, known as anonymous functions or function expressions.

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

var product = multiply(3, 4);
console.log(product); // Output: 12

Arrow Functions (ES6+):

Arrow functions provide a concise syntax for writing functions, especially useful for short and simple functions.

const square = (num) => num * num;
console.log(square(5)); // Output: 25

Callback Functions:

Functions can be passed as arguments to other functions, which is useful for implementing callback functionality.

function doSomething(callback) {
  console.log("Doing something...");
  callback();
}

function onComplete() {
  console.log("Operation complete!");
}

doSomething(onComplete);

Conclusion

These are the fundamental concepts of JavaScript functions. As you get more comfortable with these basics, you can explore more advanced topics like closures, recursion, and higher-order functions