HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

JavaScript Functions

In JavaScript, functions are a fundamental part of the language and can be thought of as reusable blocks of code that perform a specific task.

Functions can take inputs (parameters), perform actions, and return outputs.

Example

// Defining a function named "greet"
function greet(name) {
  return "Hello, " + name + "!";
}

// Calling the function
const message = greet("John");
console.log(message); // Output: Hello, John!

 

JavaScript Function Syntax

In JavaScript, functions can be defined using two main syntaxes: function declarations and function expressions.

Example

    function functionName(parameters) {
  // Function body
  // Code to be executed
  return value; // Optional
}
 

Function Invocation

Function invocation in JavaScript refers to the process of executing or calling a function to perform its defined task. When a function is invoked, the JavaScript runtime starts executing the code inside the function body.

There are several ways to invoke a function in JavaScript:

  • Using Parentheses: You can invoke a function by following its name with parentheses (). This is the most common way to invoke functions.
  • With Arguments: You can pass arguments to a function when invoking it.
  • Using Method Invocation: Functions can be invoked as methods of objects. When a function is called as a method of an object, this inside the function refers to the object on which the method was called.
  • Using the call() or apply() Methods: The call() and apply() methods are used to invoke a function with a specified this value and optional arguments provided as an array.
  • Using the new Operator (Constructor Invocation): Functions can be used as constructors to create new objects. When a function is invoked with the new operator, it creates a new instance of the function (known as an object constructor).