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);
}
2
  • declare let hello='' at the beginning of the codes Commented Jul 10, 2020 at 0:36
  • You don't declare things based on an if; you use the if to decide what to assign to a variable that has already been declared. Commented Jul 10, 2020 at 0:36

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

Nice! I like the ternary solution. For those who might not know which one I mean: condition ? exprIfTrue : exprIfFalse developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - Conditional (ternary) operator - JavaScript | MDN

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.