Is it possible to declare local variables within a lambda?

1

I have a lambda function (arrow or anonymous function) in JavaScript , which declares a variable, but the problem is that it declares it as a global variable, and I I would like it to be local (only accessible within lambda).

(x=>(
  a=2,
  console.log(a)
))()
console.log(a)

If I try to put var a = 2 within the function, I throw error. Is it possible to declare it locally? and if so, how to implement it?

The first log , should give 2 , and the second, should give error, because the variable should not exist globally, but the problem is that it always accesses the declared within the function.

    
asked by ArtEze 21.03.2018 в 03:32
source

1 answer

3

Greetings with the ES6 standard have different ways to declare the scope of a variable, for example in your exercise you want the first console of 2 and the second error since outside the context of the arrow function you will not know of the creation or existence of said variable.

Use the let identifier since with the declare the variable only at the level of the context where it is located and outside it will mark that it does not exist:

const is similar in behavior to let but apart from the fact that the value must be declared from the beginning, its value must be immutable ie it will mark you error if you later decide to change it intentionally

Try this

(x => {
      let a = 2
      console.log(a) //aquí dará 2
})()
 console.log(a) //aquí dará un error de que a is not defined que es lo que tu buscas suceda
    
answered by 21.03.2018 / 03:40
source