skip to Main Content

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

2

Answers


  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}`);
    
    
    Login or Signup to reply.
  2. 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]}`)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search