Functions in javascript

Functions in javascript

Function declaration and accessing:

In javascript, we can declare and access the function in the following way

function sayMyName() {
    console.log("U");
    console.log("D");
    console.log("A");
    console.log("Y");
    console.log("R");
    console.log("A");
    console.log("J");
} //Declaration of function

sayMyName() //Function calling

Function with parameters:

We can declare and access the functions with parameters as shown below

function addTwoNumbers(number1, number2){
 console.log(number1+number2)
}  //Declaring the function body

addTwoNumbers(3,5) //Function calling

Function with the return statement

If we want to return anything from the function we can do that by below way

function addTwoNumbersAnother(number1, number2){
    //If we write anything before it will execute
    return number1+number2
   //If we write anything after the return statement it won't execute
   } 
   const result = addTwoNumbersAnother(3,5) //function calling and holding the returned value in result variable
   console.log(result);

Function with default parameter if not passed any other parameter:

We can have a parameterized function with a default value as well in case the parameter is not passed then this default value can be used for further operation. The example of the function with a default parameter is shown below.


   function loginUserMsg(username = "sam"){
    return `${username} just logged in`
   }

   let valueReturned = loginUserMsg("Alex"); //If we pass parameter the function will take this argument
   console.log(valueReturned); //Output: Alex just logged in
   valueReturned = loginUserMsg(); //If we don't pass parameter the function will take the default argument i.e. Sam
   console.log(valueReturned); //Output: Sam just logged in

Using the spread operator to get multiple arguments store them in an array

The following example shows the use of the spread operator to get the multiple function parameters and then store them in an array with the help of the spread operator. Here we are treturning the resultant num1 array/.

function calculateCartPrice(...num1){
    return num1
} //The function takes the multiple arguments and stores it in array

console.log(calculateCartPrice(100,200,400,500,2000)); // returns array of all values

Function with Objects as parameters:

The function can also accept the Object as an argument as shown in the example below. once passed the Object argument we can use it for any operation. The example below shows the printing of the object elements of an Object.

const user = {
    username:"User1",
    CurseOffered: "JS",
    price:199
}

function handleObject(anyObject){
console.log(`username is ${anyObject.username}, course offered is ${anyObject.CurseOffered}, and price is ${anyObject.price}`);
}

handleObject(user) //Output: username is User1, course offered is JS, and price is 199

Functions with array as an argument

The function can also accept the array as an argument as shown in the example below. once passed the array argument we can use it for any operation. The example below shows the return of 2nd element of an array.


const myNewArr = [200, 400, 40000, 100]

function getSecondValue(getArray){
   return getArray[1]

}
console.log(getSecondValue(myNewArr)) //Output: 400
console.log(getSecondValue([200,300,400,500])) //Output: 300

Arrow Functions:

Declaration of the arrow function: The arrow functions can be declared in many ways as shown below.

  1. Named arrow function: The syntax of the named arrow function is as shown below.

     const sayHello= () => {
         console.log("Hello");
     } 
     sayHello() //Output: Hello
    
  2. Parameterized arrow function: Arrow functions accept arguments in the same way as regular functions. To pass arguments to an arrow function, simply list them inside the parentheses after the arrow. For example:

     const addNumbers= (num1,num2) => {
         console.log(num1+num2);
     } 
     addNumbers(5,3) //Output: 8
    
  3. Arrow function with the return keyword: The return from the arrow function is similar to the return from a regular function the example is shown below:

     const addNumbers= (num1,num2) => {
       return num1+num2
     }
     let result = addNumbers(5,3)
     console.log(result) //Output: 8
    
  4. Arrow function with implicit return method 1: If the arrow function has a single expression as its body, then the return statement is implicit. This means that the value of the expression will be returned from the function. For example:

     const addNumbers =  (num1,num2) => num1+num2
     console.log(addNumbers(7,5)) //Output: 12
    
  5. Arrow function with implicit return method 2: The second way of implicit return is by adding "()" brackets around the expression as shown below example:

     const addNumbers =  (num1,num2) => (num1+num2)
     console.log(addNumbers(7,5)) //Output: 12
    
  6. How to return the Object in an arrow function in an implicit return way: The Objects can be returned by implicit return way by wrapping the object in the "{}" curly brackets(braces) around the expression as shown below example:

     const returnObject = () => ({username:"Udayraj"})
     console.log(returnObject()) //output: { username: 'Udayraj' }
    

IIFE functions:

The Immediately invoked function expressions [IIFE] allow you to create a private scope for your code. Variables declared inside an IIFE are not accessible from the outside, which helps avoid polluting the global scope and prevents naming conflicts. This is particularly important in large codebases or when multiple scripts are loaded on a page. IIFE helps minimize the use of global variables, which can lead to unintended side effects, naming collisions, and security vulnerabilities.

  1. Named IIFE function: The Named IIFE syntax is as shown below.

     (function sayHello() {
         console.log("Hello world")
     })(); //Output: Hello world
    
  2. Parameterized IIFE function: If we want to pass any parameter in the IIFE function then we can use the below syntax.

     (function sayHello2(name){
         console.log(`Hello ${name}`);
     })("Udayraj"); // Output: Hello Udayraj
    
  3. Arrow function-based IIFE function: Below is an example of the arrow function-based IIFE function

     (() => {
         console.log("Hello from arrow function")
     })(); //Output: Hello from arrow function
    
  4. Arrow function-based IIFE function with parameters: If we want to pass any argument/parameter in an arrow function-based IIFE function then we can achieve that by the below method.

     ((name) => {
         console.log(`Hello ${name} from arrow function`)
     })("Udayraj"); //Output: Hello from arrow function