C'ant fix that!

Hi everyone! Can’t understand what’s the problem with that?

function monitorCount(rows, columns) {
  return rows * columns;
  const numOfMonitors = monitorCount(5, 4);
}

console.log(numOfMonitors);

/home/ccuser/workspace/learn-javascript-functions-functions-returnV2/main.js:6
console.log(numOfMonitors);
^

ReferenceError: numOfMonitors is not defined
at Object. (/home/ccuser/workspace/learn-javascript-functions-functions-returnV2/main.js:6:13)
at Module._compile (module.js:571:32)
at Object.Module._extensions…js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
at bootstrap_node.js:542:3

Hi there, welcome to the forums.

JavaScript has a feature called “scoping”; what this means is that if you create something inside a block of code, such a function definition, then it only exists within that block.

In effect, this means that any variables you declare within your function only exist - and so can only be accessed - inside the function.

You’re attempting to access a function-scoped variable, numOfMonitors, from outside of the function where it is declared and so you’re getting an error.

I don’t think that your const numOfMonitors line is meant to be inside the function definition, is it? :slight_smile:


There’s more on the concept of scope in JavaScript available here, on the Mozilla Dev Network.

1 Like

Hit there! Thanks for your comprehensive explanation!

1 Like