javascript variable declaration in the if/else loop

Viewed 794

I'm a very beginner in javascript. I'm declaring the string variable 'hello' based on the if condition. I want to print the variable 'hello' outside the if/else loop, how can I make this work?

var test = 4;
if (test > 3) {
    let hello = "hello world";
}
else {
    let hello = "hello gold";
}

console.log(hello);

I don't want this way

var test = 4;
if (test > 3) {
    let hello = "hello world";
    console.log(hello);
}
else {
    let hello = "hello gold";
    console.log(hello);
}
3 Answers

You just need to declare the hello variable outside the if. Doing this, it will be visible for both if and else

var test = 4;
let hello
if (test > 3) {
    hello = "hello world";
}
else {
    hello = "hello gold";
}

console.log(hello);

When you use let, the variable only exists within the braces ({}) that is was declared in. You need to either do:

var test = 4;
let hello;
if (test > 3) {
    hello = "hello world";
}
else {
    hello = "hello gold";
}

console.log(hello);

Or

var test = 4;
let hello = test > 3 ? "hello world" : "hello gold";
console.log(hello);

Or

var test = 4;
let hello = "hello gold";
if (test > 3) {
    hello = "hello world";
}
console.log(hello);

Related