Skip to main content

JavaScript Functions

By SamK
0
0 recommends
Category(s)
Topic(s)

A function in JavaScript is a set of statements created to carry out a specific operation.

Syntax

In JavaScript, functions are created using the function keyword, followed by a unique name and a pair of parentheses ().

Function names can include letters, numbers, underscores, and dollar signs.

Parameters, if any, are listed within the parentheses and separated by commas.

The logic or statements to be executed by the function are enclosed within curly braces {}.

Functions typically produce a result, known as the return value, which is sent back to the caller.

// Defining function calculateProduct
function calculateProduct(num1, num2) { // num1 & num2 are input parameters
  let num = num1 * num2; // Processing logic
  return num; // Return value
}

Function Invocation

Functions are executed when they are called or invoked by another part of the code. For example:

  • When a specific event happens (like a user clicking a button)
  • When it's explicitly called from another part of the JavaScript code
  • Automatically, as in self-invoking functions

The () operator is used to call or invoke a function.

// Defining function calculateProduct
function calculateProduct(num1, num2) { 
  let num = num1 * num2; 
  return num; 
}

let output = calculateProduct(5, 6); // Function invocation with parameters
console.log(output); // Result: 30

Providing incorrect parameters when calling a function can lead to inaccurate results.

 // Defining function calculateProduct
function calculateProduct(num1, num2) { 
  let num = num1 * num2; 
  return num; 
}

let output = calculateProduct("apple", 6); // Function invocation with parameters
console.log(output); // Result: NaN (invalid or undefined numerical result)

Local Variables

Variables that are declared inside a JavaScript function are considered local to that function.

These variables can only be accessed and used within the scope of the function where they are defined.

function calculateProduct(num1, num2) { 
  let num = num1 * num2; // Declaring a local variable num
  return num; 
}
console.log(num); // Output: num is not defined

Local variables are scoped to their functions, meaning you can use the same variable name in different functions without conflict.

These variables are initialized when the function is invoked and are removed once the function finishes executing.

Questions & Answers