0

how to get name of variable in console.log

code1 = 3;
code2 = 1;
code3 = 2;

console.log(Math.min(code1, code2, code3))

result is 1 but want also to print in console.log as : code2 =1

4
  • 2
    You probably want to use an object... Commented Apr 4, 2023 at 21:45
  • Do you just want this for debugging or something else? Commented Apr 4, 2023 at 21:45
  • 2
    It's never going to print code2. It's going to print the return value of Math.min(). Commented Apr 4, 2023 at 21:47
  • Hard to understand how you expect your code to do that... Commented Apr 4, 2023 at 21:55

2 Answers 2

1

const codeValues = {
  code1: 3,
  code2: 1,
  code3: 2,
};

const minValue = Math.min(codeValues.code1, codeValues.code2, codeValues.code3);
const minCodeName = Object.keys(codeValues).find(key => codeValues[key] === minValue);

console.log(`${minCodeName} = ${minValue}`);

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

5 Comments

Some explanation would be nice
so, how to insert variables inside codeValues?
@KnowledgeSeeker That is another question...
@MarkSchultheiss is there any example?
Depends on what you mean but that - a question with what you tried and expected output would suffice
0

You can use it like this

const nums=[3,1,2]

const minIndex= nums.indexOf(Math.min(...nums)),
    codeName= `code${minIndex+1}`

console.log(`${codeName} = ${nums[minIndex]}`)

1 Comment

all your efforts are appreciated :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.