0

Here, lastname const variable is declared later for understanding purpose. it is not accessed from the top in hoistedName obvisously with a hoisting concept. But how can it be read from a function inside?


const hoistedName = "Adam" + " " + lastname // cannot read lastname

var hello = (name) => {
  const fullname = name + " " + lastname // can read lastname delared afterward
  console.log(`hello ${fullname}`)
}

const lastname = "Smith" // variable declared

hello("John")  // => hello John Smith

console.log(hoistedName) // => Adam null

Eric
  • 754
  • 6
  • 5

2 Answers2

1

It's the execution order, because since hello is a function it doesn't execute right away, but only when it's called and by the time hello is executed, lastName has already been given a value. You can verify this by calling hello before the variable is initialized:

hello('John') // hello John null

const lastname = "Smith" // variable declared

hello("John")  // => hello John Smith

console.log(hoistedName) // => Adam null
JuanG
  • 41
  • 5
  • Thanks a lot! I was buried in a concept of variable hoisting with var/const/let and function declaration/expression so I was confused. Your explanation really makes sense. Appreciate it! – Eric Aug 24 '22 at 21:28
0

You can create a function to do that. For example: const hoistedName = () => "Adam" + " " + lastname;.

const hoistedName = () => "Adam" + " " + lastname; // cannot read lastname

var hello = (name) => {
  const fullname = name + " " + lastname // can read lastname delared afterward
  console.log(`hello ${fullname}`)
}

const lastname = "Smith" // variable declared

hello("John")  // => hello John Smith

console.log(hoistedName()) // => Adam null
anayarojo
  • 1,121
  • 2
  • 19
  • 27
  • Yes, I can understand that it is possible the same way in hello function. I just want to better understand the variable scoping and hoisting. How is the function scope keeping const/let variables so that they are read to access? – Eric Aug 24 '22 at 20:48
  • 1
    You can find documentation and some examples here: https://www.w3schools.com/js/js_scope.asp – anayarojo Aug 24 '22 at 20:56