JavaScript Learning Notes: Functions


                    function addTwoNumbers(number1, number2){

                        console.log(number1 + number2);
                    }
                    const result = addTwoNumbers(3, 5)
                

Console Output:
8




                    function addTwoNumbers(number1, number2){

                        console.log(number1 + number2);
                    }
                    const result = addTwoNumbers(3, 5)

                    console.log("Result: ", result);
                

Console Output:
8
Result: undefined

Result is undefined in this case because we not returning anything from the function in this case.



                    function addTwoNumbers(number1, number2){
                        return number1 + number2
                    }

                    const result = addTwoNumbers(3, 5)

                    console.log("Result: ", result);
                

Console Output:
Result: 8



                    function loginUserMessage(username){
                    
                       // if(username === undefined){
                       //     console.log("PLease enter a username");
                       //     return
                       // }
                    
                        if(!username){
                            console.log("PLease enter a username");
                            return
                        }
                        return `${username} just logged in`
                    }

                    console.log(loginUserMessage())
                

function loginUserMessage(username="sam"){ In this case default value is sam

Console Output:
PLease enter a username
undefined

  • If we don't pass any argument in funtion then it returns Undefined

  • 
                        function calculateCartPrice(val1, val2, ...num1){
                            return num1
                        }
    
                        console.log(calculateCartPrice(200, 400, 500, 2000, 5000))
                    

    Console Output:
    [ 500, 2000, 5000 ]

  • ...num1 is the rest operator which takes all the arguments and stores them in an array
  • The function receives the first two arguments (val1, val2), and the remaining arguments are captured in the array num1.