Use Names Before Their Line

In the last lesson, you found which declaration a name refers to by walking outward from where the code is written. That walk answers where JavaScript looks, but not when a name is ready to use. Marco likes his scorekeeping script to read top-down, with the main steps first and the helpers at the bottom. Sometimes that layout works, and sometimes it stops the script on its first call.

In this lesson, you’ll learn to predict whether code runs, throws, or logs undefined when it uses a name before its declaration line runs, and to explain why. Start with the layout Marco tried first.

Call a Helper Before Its Line

Marco wants to see at a glance what his script does. He first writes the loop that introduces the teams and puts the function declaration below it:

Language: JavaScript Filename: introductions.js
const teams = [
  { name: "The Lamplighters", captain: "Priya" },
  { name: "Know-It-Owls", captain: "Kwame" },
];

for (const team of teams) {
  console.log(introduce(team));
}

function introduce(team) {
  return `${team.name}, captained by ${team.captain}`;
}

When the loop calls introduce(), JavaScript hasn’t reached its declaration yet. Run it anyway:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.