skip to Main Content

What I learned is there are three ways function can be defined : a) Function Declaration b) Function Expression c) Arrow Function

Function Expression and arrow function can be simply defined and assigned to a variable but we cant do this for Function Declaration.. Am i right?

but I tried a code as follow:

const square_a_num = function square_the_num(num){
    return num**2
}
const square_45 = square_a_num(45)
console.log(square_45);

I think the way I defined the function above is Function declaration but still I was able to assign it to a variable., and it is still working.

I hoped if I declared it like a function expression like below then only I can assign it to a variable :

const square_a_num = function(num){
    return num**2
}
const square_45 = square_a_num(45)
console.log(square_45);

Where I am making mistake?
Thanks

I thought it should have given me an error message but rather it gave me the output as 2025 .

2

Answers


  1. Chosen as BEST ANSWER

    const square_a_num = function square_the_num(num){ // this is function expression not a function declaration. 
        return num**2
    }
    const square_45 = square_a_num(45)
    console.log(square_45);   
    
    const sq_100 = square_the_num(100)  
    console.log(sq_100)

    This will give error when function is defined as expression i.e. assigned to a variable then original name of function is not the actual function rather the variable name becomes the funciton name

    Doubt : how the above code worked , if it was defined like function declaration , how could we assign it to a variable

    Answer : function expression means when we declare a function and assign it to a variable, in such case the name of function is irrelevant because the variable name (square_a_num) now becomes the function name and function can now be called only with this variable name and not with the function name (square_the_num)that we gave , so its better not to give name.


  2.    const square_a_num = function square_the_num(num){
           return num**2
       }
       const square_45 = square_a_num(45)
       console.log(square_45);
    

    I think the way I defined the function above is Function declaration but still I was able to assign it to a variable., and it is still working.

    This is still interpreted as a function expression, except that it has a name.

    This allows function expressions to be recursive.

    Read more here

    If you try to execute square_the_num() outside of it’s own scope, you will get:

    ReferenceError: square_the_num is not defined

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search