In JavaScript, a function is defined using the keyword function
, followed by a name for the function (optional), a list of parameters (also optional) enclosed in parentheses, and the function body enclosed in curly braces {}
. Here is the basic syntax:
index.tsx89 chars5 lines
The function name and parameters are optional, but the function body must always be enclosed in curly braces. The return
keyword is used to specify the value that the function should return when it is called.
Here is an example of a simple function that takes two parameters and returns their sum:
index.tsx75 chars5 lines
You can call this function by passing in two arguments and capturing the return value:
index.tsx65 chars3 lines
In this example, the function addNumbers
takes two parameters (num1
and num2
) and returns their sum. The result of calling the function with arguments 2 and 3 is assigned to the variable result
, which is then printed to the console using console.log()
.
gistlibby LogSnag