JavaScript Functions

What is a Function?

A function is a block of code designed to perform a particular task. Functions are executed when they are called (invoked). This allows you to reuse code, making your programs more modular and easier to maintain.

Defining a Function

To define a function in JavaScript, you use the function keyword followed by a name, parentheses () which may include parameters, and a block of code {}.

Tutorials dojo strip

Explanation of Code:

This example defines a function named greet that logs “Hello, World!” to the console when called.

JavaScript

Calling a Function

To execute the code inside a function, you need to call it by its name followed by parentheses ().

Explanation of Code:

This calls the greet function, which logs the message to the console.

JavaScript

Function Paramaters

Functions can accept parameters, which are values passed to the function when it is called. You can use these parameters within the function.

Explanation of Code:

The greet function now accepts a name parameter, which is used to customize the greeting message.

JavaScript

Function Return Values

Functions can return a value using the return statement. The returned value can be used in the code that called the function.

Explanation of Code:

The add function takes two parameters, a and b, and returns their sum. The result is stored in the sum variable and then logged to the console.

JavaScript

Anonymous Functions

Functions can also be defined without a name, known as anonymous functions. These are often used as arguments to other functions or assigned to variables.

Explanation of Code:

An anonymous function is assigned to the variable greet, and it works similarly to a named function.

JavaScript

Arrow Functions

Arrow functions provide a more concise syntax for writing functions. They are particularly useful for writing short, anonymous functions.

Explanation of Code:

The arrow function syntax => is used to define the function, making it more concise.

JavaScript

JavaScript Functions Example Code

Explanation of Code:

  • Named Function: Defines and calls a function named greet.
  • Anonymous Function: Defines an anonymous function and assigns it to the variable add.
  • Arrow Function: Defines a function using arrow function syntax and assigns it to the variable multiply.
HTML

JavaScript Labs

Tutorials dojo strip