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

Defining and invoking functions

In JavaScript, a function is a block of code that performs a specific task. Functions are defined using the function keyword, followed by a name for the function, and a set of parentheses that can contain zero or more parameters. The code to be executed is enclosed in curly braces { }, and can include any valid JavaScript code.

Here is an example of a simple function that takes two parameters and returns their sum:

function addNumbers(num1, num2) {

  let sum = num1 + num2;

  return sum;

}

In this example, addNumbers is the name of the function, and it takes two parameters (num1 and num2). The function calculates the sum of the two numbers and assigns it to the sum variable, and then returns the value of sum.

Once a function has been defined, it can be invoked (or called) by its name, followed by a set of parentheses that contain the arguments (values) to be passed to the function. Here is an example of how to call the addNumbers function:

let result = addNumbers(5, 10);

console.log(result); // Outputs 15

In this example, the addNumbers function is called with the arguments 5 and 10, which are passed to the num1 and num2 parameters, respectively. The function calculates the sum of the two numbers and returns the result, which is then assigned to the result variable. Finally, the value of result is output to the console using the console.log function.

Functions can also be defined using function expressions, which involve assigning a function to a variable.

Function expressions can also be used to define anonymous functions, which are functions that do not have a name.