1

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 Answers3

3

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);
solimanware
  • 2,952
  • 4
  • 20
  • 40
1

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);
Bruno
  • 2,889
  • 1
  • 18
  • 25
Tps
  • 194
  • 5
  • Nice! I like the ternary solution. For those who might not know which one I mean: `condition ? exprIfTrue : exprIfFalse` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator - Conditional (ternary) operator - JavaScript | MDN – iAmOren Jul 10 '20 at 00:59
1

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);
dave
  • 62,300
  • 5
  • 72
  • 93