functions in javascript

Syntax

Functions in JavaScript have the following syntax:

index.tsx
function functionName(parameters) {
  //code to be executed
  return result; //optional
}
90 chars
5 lines

Parameters

Parameters are optional, and are enclosed within parentheses following the function name. They are used to pass values to the function.

index.tsx
function greet(name) {
  console.log("Hello " + name);
}
greet("John"); //output: Hello John
93 chars
5 lines

Return

The return statement is used to specify the value that a function should return.

index.tsx
function multiply(num1, num2) {
  return num1 * num2;
}
console.log(multiply(2, 3)); //output: 6
97 chars
5 lines

Functions can also be assigned to variables or passed as arguments to other functions:

index.tsx
var sum = function(num1, num2) {
  return num1 + num2;
}
console.log(sum(2, 3)); //output: 5

function calculator(num1, num2, operation) {
  return operation(num1, num2);
}
console.log(calculator(4, 5, sum)); //output: 9
221 chars
10 lines

In summary, functions are a fundamental part of JavaScript and allow for reusable code that can be executed with different parameters and return values.

gistlibby LogSnag