javascript variable declaration in the if/else loop

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);
}

Upvotes: 1

Views: 2129

Answers (3)

Tps
Tps

Reputation: 194

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);

Upvotes: 1

solimanware
solimanware

Reputation: 3051

You can just declare let hello='' at the beginning of the code:

As let variable have the scope inside the brackets of them { }...

The let statement declares a block-scoped local variable, optionally initializing it to a value.

Read More:

What's the difference between using "let" and "var"?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

var test = 4;
let hello = "";

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

console.log(hello);

Upvotes: 3

dave
dave

Reputation: 64657

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);

Upvotes: 1

Related Questions