Course Content
Data types and Values
0/1
Object-oriented programming in JavaScript
0/1
Error handling and debugging in JavaScript
0/1
JavaScript functions for string and array manipulation
0/1
JavaScript Libraries and Frameworks
0/1
JavaScript
About Lesson

JavaScript Functions

In JavaScript, a function is a reusable block of code that can be defined once and executed (or called) multiple times throughout your code. Functions are a fundamental building block of programming and play a crucial role in organizing and modularizing your code.

Function Declaration

You can declare a function using the function keyword, followed by the function name, a pair of parentheses (), and curly braces {} that enclose the function’s code block. Here’s the basic syntax:


function functionName(parameters) {
    // Function code block
  }

function sayWelcome() {
  console.log('Hello, welcome to our website!');
}

Function Parameters

Parameters are placeholders for values that you can pass to the function when calling it. These values are used within the function’s code block. You list the parameters inside the parentheses when declaring the function. For example:


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

Function Calling

To use a function, you “call” it by using its name followed by parentheses. If the function has parameters, you provide the values (arguments) for those parameters within the parentheses. For example:


greet('Alice'); // Outputs: Hello, Alice!
sayWelcome(); // Calling the function

Return Statement

Functions can return a value using the return statement. The returned value can be used in further computations or assigned to variables. If a function doesn’t explicitly return a value, it returns undefined. For example:

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

  const sum = add(5, 3); // sum is now 8

Function Expressions

In addition to function declarations, you can also create functions using function expressions. A function expression assigns an anonymous (unnamed) function to a variable. For example:

The motivation here is that, The variable “add” is like a reference to the defined function in the outer scope. Functions act as values, just as numbers or arrays do. It might sound odd, but you can pass a function itself as a value. It can be stored in variables, passed around, or returned from other functions. So, think of a function value as an expression, much like any other value.

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

  const result = multiply(4, 6); // result is now 24


Also, consider
var anony = function() {
      // ..
};
var x = function bar(){
      // ..
};

The initial function assigned to “anony” is anonymous, lacking a name. The second function expression, named “bar,” is assigned to the variable “x.” Named function expressions are usually favored, while anonymous ones are still widely used. Also the function assigned to multiply is also anonymous and has no name.

Arrow Functions

Arrow functions provide a more concise syntax for creating functions, especially when the function’s body is a single expression. They are often used for short, inline functions. For example:

const square = x => x * x;

  const squaredValue = square(7); // squaredValue is now 49

Functions are essential for code organization, reusability, and maintaining a clean codebase. They allow you to break down complex tasks into smaller, manageable pieces and encapsulate logic into separate units, enhancing the readability and maintainability of your code. Also even if the function is called only once, organizing code into a function makes the code cleaner. If the function has more statements in it, the beneficial it becomes.

Immediately Invoked Function Expressions (IIFEs)

An Immediately Invoked Function Expression (IIFE) is a JavaScript design pattern that involves defining and executing a function immediately after its creation. It’s often used to create a private scope for variables, prevent polluting the global scope, and execute code right away. We achieve this by doing something like: foo() or x(),

Syntax:

(function() {
  // Code to execute immediately
})();

Usage:

IIFEs are typically used when you want to encapsulate a piece of code to avoid variable name clashes and to keep your codebase organized. They are especially useful in scenarios like setting up initialization code or managing modular code.

Example:

(function() {
  let secretValue = "I am hidden";
  console.log(secretValue);
})();

// This will throw an error because secretValue is not in scope
console.log(secretValue);

nspb;nspb;nspb;nspb;nspb;nspb;
//Example 2:
var myVariable = 250;

(function IIFE(){
var myVariable = 100;
console.log( 100 ); // 100
})();
console.log( myVariable ); // 250

nspb;nspb;nspb;nspb;nspb;nspb;
//Example 3
var myNumber = (function IIFE(){
return 754;
})();
x; // 754

The outer `( .. )` around the `function IIFE(){ .. }` function expression is a quirk of JavaScript’s grammar that prevents it from being treated as a regular function declaration.

The trailing `()` at the end—`})();`—is what runs the function expression just before it.

While this might seem strange at first, it’s not as unfamiliar as it looks. Think about the parallels between `foo` and `IIFE` in this context.

By wrapping the code in an IIFE, you create a private scope where secretValue is accessible, but it doesn’t pollute the global scope.