Why can’t I access the variable within a function?

Asked

Viewed 55 times

2

var n1 = 10;

if (n1 == 10) {
  var n2 = 45;
}

console.log(n2);

The above example works perfectly by printing the value of n2 in the console browser in this n2 is within the command if and is accessible, but when trying to pick up a variable within a function it is no longer accessible and I can no longer get the value of the variable n2 and an error is returned (Uncaught ReferenceError: n2 is not defined).

var n1 = 10;

function a() {
  var n2 = 45;
}

console.log(n2);

My question is why I can’t access the variable of a function, but of command if can I? sorry for the simplicity of the code, but I’m a complete beginner, I left the Portugol and I’m trying to learn Javascript.

1 answer

3


In "old" Javascript it is possible to declare functions within a block, i.e.: {} and access that declared variable with var off the block.

This is not possible in functions (neither in old Javascript nor in modern) because the function creates its own scope. In other words, what is declared within the function is within the function. This is one of the characteristics of functions. Imagine if this were not so the mess it would be in large codes to find names for all variables that were unique and security problems to be able to access all values within functions...

With that said, you should no longer use var, in Modern Javascript you have let and const that allow block scope, i.e.: variables declared with let or const inside blocks are no longer accessible outside it.

var n1 = 10;
let n3 = 33;

if (n1 == 10) {
  var n2 = 45;
  let n4 = 44;
}

console.log(n1, n2, n3); // 10 45 33
console.log(n4); // <- vai dar erro

  • then it is only in the functions that a scope is created automatically in the case of other commands not?

  • 2

    @draw in the case of var, yes

  • @guijob, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.