How can I use "let" out of a block in javascript?

3

I'm experimenting with JavaScript and I came across this variable scope in JavaScript, mainly with let , which is integrated in ECMAscript 6.

The problem is this:

I have a prompt that asks the user for their age and compares it in a if if it is greater than 18 shows the page, although I know it is not very safe but it is only for testing.

The code is this:

/*Programador: Sommer0123
Version del codigo: 1.0
*/

//Este comportamiento cambia, cuando usamos la declaración let introducida en ECMAScript 6.
var user = prompt("Escribe tu edad: ");

if (user==18) {
    //me muestra este mensaje si es true
    let y = "Bienvenido usuario"+user;
    //aqui va el codigo que te manda a la pagina correspondiente (por privacidad la quite)
}else{

    alert("error usted no es mayor de edad");

}

/*mi problema es esta aqui que no me muestra el valor y*/
document.write(y); 

Possible solution I'm thinking? Use switch to compare age, but I have a lot of code.

    
asked by sommer0123 01.12.2016 в 04:52
source

1 answer

1

I think you're a bit confused with the conditional, and about the let you declare it above so that its environment is total

/*Programador: Sommer0123
Version del codigo: 1.0
*/

//Este comportamiento cambia, cuando usamos la declaración let introducida en ECMAScript 6.
var user = prompt("Escribe tu edad: ");
let y;
if (user>=18) {
    //me muestra este mensaje si es true
     y = "Bienvenido usuario"+user;
    //aqui va el codigo que te manda a la pagina correspondiente (por privacidad la quite)
}else{

    alert("error usted no es mayor de edad");

}

/*mi problema es esta aqui que no me muestra el valor y*/
document.write(y);

If you use var, the var 'and' will survive block after block, careful with its use Here's an example.

/*Programador: Sommer0123
Version del codigo: 1.0
*/

//Este comportamiento cambia, cuando usamos la declaración let introducida en ECMAScript 6.
var user = prompt("Escribe tu edad: ");

if (user>=18) {
    //me muestra este mensaje si es true
     var y = "Bienvenido usuario"+user;
    //aqui va el codigo que te manda a la pagina correspondiente (por privacidad la quite)
}else{

    alert("error usted no es mayor de edad");

}

/*mi problema es esta aqui que no me muestra el valor y*/
document.write(y);
    
answered by 01.12.2016 в 05:11