Please, Can someone help me on this issue?

They both are functions but work differently. Why?

test(); //output is 'fun'

  function test(){
    console.log('fun');

  }
test2();//output is 'reference error'

const test2=()=>{
  console.log('fun2');

}

function declarations are hoisted to the top of the scope before anything runs, so even though running the function test before you’ve even declared it is confusing to read, it will work. It means you can do things like declare utility functions at the bottom of a file after all the rest of the code and they’ll work fine if you call them further up the file.

Variables (const and let) are evaluated in the order they are declared, logically, top to bottom in the code. There’s no variable called “test2” declared when that code runs, you’re trying to run the function assigned to it before it exists. A reference error means you’re trying to access a variable that doesn’t exist: there isn’t a reference to test2, error.

1 Like

From what i understand in the second case when you do function call the const test2 variable isn’t initialized yet therefore you get ReferenceError,
you need to do function call after test2 initialization.

const test2=()=>{
  console.log('fun2');
}

test2();//output is 'fun2'

Can’t explain any better i’m a novice myself, srry

1 Like

Thank you man got it.

1 Like

no worries thank you for your reply.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.