Variable not displayed in console.log



here is my code.

let userName = 'dave'
userName = userName ? console.log(`Hello, ${userName}`) : console.log('Hello!')

let userQuestion = 'Am I crazy'
console.log(`${userName} asked: ${userQuestion}`)

expected output

Hello, dave
dave asked: Am I crazy

actual output

Hello, dave
undefined asked: Am I crazy

Why is it showing ‘undefined` ?

Answer

you are trying to assign the console.log to userName and using it. change the code to

let userName = 'dave'
console.log(userName ? `Hello, ${userName}` : 'Hello!');

let userQuestion = 'Am I crazy'
console.log(`${userName} asked: ${userQuestion}`)

or you can use the line as follows.

userName ? console.log(`Hello, ${userName}`) : console.log('Hello!')

let userName = 'dave'
userName ? console.log(`Hello, ${userName}`) : console.log('Hello!');


let userQuestion = 'Am I crazy'
console.log(`${userName} asked: ${userQuestion}`)


Source: stackoverflow