JavaScript Course

Functions Declaration and Invocation

How to declare a function (using the keyword "function" and specifying the function name and parameters)

Functions are the building blocks of any programming language. They allow us to break down our code into smaller, reusable pieces, making it easier to manage and maintain. In JavaScript, functions are declared using the keyword "function", followed by the function name and the parameters it takes.

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

The above function takes a single parameter, name, which is the name of the person we want to greet. The function then logs a message to the console, saying "Hello, [name]!".

Function parameters

Parameters are the values that we pass into a function when we call it. They can be of any type, including strings, numbers, booleans, and even objects and arrays.

function sum(num1, num2) {
  return num1 + num2;
}

The above function takes two parameters, num1 and num2, which are the numbers we want to add together. The function then returns the sum of the two numbers.

Function bodies

The body of a function is the code that is executed when the function is called. The body can contain any valid JavaScript code, including other function calls, conditional statements, and loops.

function greet(name) {
  if (name === "Alice") {
    console.log("Hello, Alice!");
  } else if (name === "Bob") {
    console.log("Hello, Bob!");
  } else {
    console.log("Hello, " + name + "!");
  }
}

The above function takes a single parameter, name, and greets the person by name. If the name is "Alice" or "Bob", the function uses a special greeting. Otherwise, it uses a more generic greeting.

Returning values from functions

Functions can return values using the return keyword. The return keyword can be used to return any type of value, including strings, numbers, booleans, and even objects and arrays.

function sum(num1, num2) {
  return num1 + num2;
}

The above function returns the sum of the two numbers that are passed in as parameters.

Now that you know how to declare functions, you can start using them to make your JavaScript code more organized and reusable. In the next section, we'll learn how to invoke functions (by calling the function name with the appropriate arguments).

How to invoke a function (by calling the function name with the appropriate arguments)

To invoke a function, simply call the function name followed by the parentheses (). Inside the parentheses, you can pass any arguments that the function expects. For example, the following code invokes the greet function and passes in the argument "Alice":

greet("Alice");

This will log the following message to the console:

Hello, Alice!

Passing arguments to functions

When you pass arguments to a function, the arguments are assigned to the parameters of the function. For example, the following code defines a function that takes two parameters, num1 and num2:

function sum(num1, num2) {
  return num1 + num2;
}

When you invoke this function, you must pass in two arguments. The first argument will be assigned to the num1 parameter, and the second argument will be assigned to the num2 parameter. For example, the following code invokes the sum function and passes in the arguments 1 and 2:

sum(1, 2);

This will return the value 3.

Accessing arguments inside a function

Inside a function, you can access the arguments that were passed in using the arguments object. The arguments object is an array-like object that contains all of the arguments that were passed to the function. For example, the following code defines a function that prints all of the arguments that were passed in:

function printArgs() {
  for (const arg of arguments) {
    console.log(arg);
  }
}

When you invoke this function, you can pass in any number of arguments. The following code invokes the printArgs function and passes in the arguments 1, 2, and 3:

printArgs(1, 2, 3);

This will log the following output to the console:

1
2
3

Returning values from functions

Functions can return values using the return keyword. The value that is returned by a function can be any type of value, including strings, numbers, booleans, and even objects and arrays. For example, the following code defines a function that returns the sum of two numbers:

function sum(num1, num2) {
  return num1 + num2;
}

When you invoke this function, the value that is returned by the function can be assigned to a variable. For example, the following code invokes the sum function and assigns the returned value to the result variable:

const result = sum(1, 2);

The result variable will now contain the value 3.


Understanding the difference between function declaration and function expression

... (continued in the next section)

Understanding the difference between function declaration and function expression

Function declaration is a way of declaring functions using the function keyword, specifying the function name and parameters.

Function expression is a way of declaring functions that involves assigning a function to a variable.

Key differences

Feature Function declaration Function expression
Syntax function functionName(parameters) { ... } const variableName = function(parameters) { ... };
Hoisting Yes, functions are hoisted to the top of their scope No, functions are not hoisted
Scope Functions have their own scope Functions share the scope of the variable they are assigned to
Name Functions have a name Functions can be named or anonymous

Hoisting is a mechanism that moves function declarations to the top of their scope. This means that function declarations can be called before they are declared in the code.

Example

The following code shows an example of a function declaration:

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

The following code shows an example of a function expression:

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

Both of these functions will do the same thing, but the function declaration is hoisted to the top of the scope, while the function expression is not.

Which should you use?

In most cases, it is better to use function declarations because they are hoisted and have their own scope. However, there are some cases where it is better to use function expressions, such as when you need to create a function that is only used in a specific part of your code.

... (... continued in Using named function expressions (assigning a name to a function expression))

Using named function expressions (assigning a name to a function expression)

In JavaScript, we can assign a name to a function expression, creating a named function expression. This allows us to refer to the function by its name, even before it's declared.

Consider the following code:

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

greet("Alice"); // Output: Hello, Alice!

In this example, we declare a function expression and assign it to the variable greet. We can then call the greet function using its name, just like a regular function declaration.

Named function expressions can be useful in situations where we want to create a function that will only be used in a specific part of our code. For example, we could use a named function expression to create a helper function for a particular task.

Here's another example:

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

const area = calculateArea(5, 10); // Output: 50

In this example, we create a named function expression to calculate the area of a rectangle. We can then call the calculateArea function to calculate the area of a rectangle with a width of 5 and a height of 10, storing the result in the area variable.

Tips for using named function expressions:

  • Use named function expressions when you need to create a function that will only be used in a specific part of your code.
  • Avoid using named function expressions for global functions, as they can create naming conflicts.
  • Give your named function expressions descriptive names that clearly indicate their purpose.

... And here's a little suspenseful question to leave you with:

What if we didn't need to assign a name to a function expression?

In our next section, we'll explore anonymous function expressions, where we can declare functions without giving them a name... Stay tuned!

Using Anonymous Function Expressions

Understanding Anonymous Function Expressions

An anonymous function expression is a function declaration without a name assigned to it. This means that the function expression does not have its own identity and cannot be referenced by its name.

Instead, anonymous function expressions are typically assigned to variables or immediately invoked as part of another expression. This allows for greater flexibility and reusability of code.

Creating Anonymous Function Expressions

To create an anonymous function expression, simply use the following syntax:

const myFunction = function(parameters) {
  // Function body
};

For example:

const sum = function(num1, num2) {
  return num1 + num2;
};

In this example, we have created an anonymous function expression that takes two parameters, num1 and num2, and returns their sum.

Using Anonymous Function Expressions

Anonymous function expressions can be used in a variety of ways:

  • Assigning to Variables: Anonymous function expressions can be assigned to variables, allowing you to store functions for later use.
const greet = function(name) {
  console.log(`Hello, ${name}!`);
};

greet("Alice"); // Output: Hello, Alice!

  • Immediately Invoked Function Expressions (IIFEs): Anonymous function expressions can be immediately invoked by adding parentheses after the function declaration.
(function() {
  console.log("This is an immediately invoked function expression.");
})();

IIFEs are often used for encapsulation and data privacy in JavaScript.

  • Callbacks: Anonymous function expressions are commonly used as callbacks in asynchronous operations.
setTimeout(function() {
  console.log("This function will be called after 3 seconds.");
}, 3000);

Tips for Using Anonymous Function Expressions

  • Use anonymous function expressions when you need a function for a specific purpose that is not reusable elsewhere in your code.
  • Avoid creating unnecessarily complex anonymous function expressions.
  • Prefer named function expressions over anonymous function expressions when possible, as they provide better readability and debugging capabilities.

What's Next?

Now that you understand anonymous function expressions, you can explore more advanced concepts like passing arguments to functions and returning values from functions. Stay tuned for the next section!

Passing arguments to functions and accessing the arguments inside the function

Understanding how arguments work

When you call a function, you can pass it any number of arguments. These arguments are stored in an array-like object called the arguments object. You can access the arguments inside the function using the arguments object.

For example, the following function prints the arguments passed to it:

function printArgs() {
  for (const arg of arguments) {
    console.log(arg);
  }
}

When you invoke this function, you can pass in any number of arguments. The following code invokes the printArgs function and passes in the arguments 1, 2, and 3:

printArgs(1, 2, 3);

This will log the following output to the console:

1
2
3

Returning values from functions

Functions can return values using the return keyword. The value that is returned by a function can be any type of value, including strings, numbers, booleans, and even objects and arrays.

For example, the following function returns the sum of two numbers:

function sum(num1, num2) {
  return num1 + num2;
}

When you invoke this function, the value that is returned by the function can be assigned to a variable. For example, the following code invokes the sum function and assigns the returned value to the result variable:

const result = sum(1, 2);

The result variable will now contain the value 3.

Returning values from functions

Returning values from functions allows you to pass data back to the code that called the function. This is useful for performing calculations, getting user input, or retrieving data from a database.

To return a value from a function, use the return keyword followed by the value you want to return. For example:

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

const result = sum(1, 2); // result will be 3

Tips for returning values from functions:

  • Return early if possible. This makes your code more readable and easier to debug.
  • Use descriptive variable names for the values you return. This will help you and others understand what the function is returning.
  • Avoid returning null or undefined unless you have a good reason. These values can be difficult to work with and can lead to errors.

Example

The following function returns the area of a rectangle:

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

const area = calculateArea(5, 10); // area will be 50

Conclusion

Returning values from functions is an essential part of programming. By following these tips, you can write functions that are easy to read, debug, and reuse.

Share Button