JavaScript Functions

by | Dec 25, 2020 | JavaScript

Home » Website Development » JavaScript » JavaScript Functions

JavaScript Functions

In JavaScript, you write all your logic within a function. A function is a block of code designed to perform a specific task. After performing its task, the function returns a result. To execute a function, we need to trigger it. In this section, we will learn how to write a function, how to trigger a function and how to get a result from that function.

JavaScript Function Syntax

A JavaScript function starts with a keyword function, it is followed by the function name and parentheses ( ). The code that needs to be executed is written within curly brackets { }.

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

This function has two parameters a and b, known as arguments of a function. The values of these parameters will be provided while calling this function. In return, this function will produce sum of these parameters.

Triggering a JavaScript Function

A JavaScript function is triggered in the following three ways:

  1. When an event occurs i.e. when a user clicks a button
  2. The function is called by another JavaScript function
  3. Automatically (self-invoked) [In case, function is triggered by JavaScript events]

JavaScript Function Return

The JavaScript return statement is used to return the result of a function. This is mainly used whenever the function is called from another function or variable.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author