3 Ways to Create Functions in JavaScript
There are three ways to create functions in JavaScript:
1.Plain or Normal Function
2.Function Expression (function without a name stored in a variable)
3.Arrow Function (can be written in implicit or explicit style and can return objects)
- Normal Function
function sayMyName() { // `()` inside is called parameters
console.log("Sam");
}
sayMyName; // This is a reference to the function, but it does NOT run it
sayMyName(); // This calls the function and runs it
// Output: Sam
- Function Expression This is a function without a name stored in a variable.
const showNum = function(a) {
return a;
}
console.log(showNum(5)); // Output: 5
console.log(showNum()); // Output: undefined, because no argument was passed
- Arrow Function Arrow functions can be written in two ways: a) Implicit Return (no need to write return keyword)
const addNum = (a, b) => a + b;
console.log(addNum(2, 3)); // Output: 5
console.log(addNum()); // Output: NaN (because no arguments passed)
You can also use parentheses for returning an object:
const addNumTwo = (a, b) => (a + b);
console.log(addNumTwo(3, 4)); // Output: 7
b) Explicit Return (use return keyword inside braces)
const addNumOne = (a, b) => {
return a + b;
}
const result = addNumOne(2, 3);
console.log(result); // Output: 5
Arrow Function Returning Objects
You can use arrow functions to return objects like this:
const result = (str) => ({ length: str.length, uppercase: str.toUpperCase() });
console.log(result("hello"));
// Output: { length: 5, uppercase: "HELLO" }
const analyzeSentence = sentence => ({ wordCount: sentence.split(" ").length });
console.log(analyzeSentence("JavaScript is fun"));
// Output: { wordCount: 3 }
const calculateSquareAndCube = (num) => ({ square: num ** 2, cube: num ** 3 });
console.log(calculateSquareAndCube(4));
// Output: { square: 16, cube: 64 }
More Arrow Function Examples (with explicit return)
Sum of Array Elements
const arr = [1, 2, 3, 4, 5];
const sumOfArr = (arr) => {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
console.log(sumOfArr(arr)); // Output: 15
Reverse a String
const reverse = (str) => {
let rev = "";
for (let i = str.length - 1; i >= 0; i--) {
rev += str[i];
}
return rev;
}
console.log(reverse("hello")); // Output: olleh
Top comments (0)