var salaries = { "Вася": 100, "Петя": 300, "Даша": 250 }; function maxsalary(obj){ var sum = 0; for(var key in salaries){ if(sum < salaries[key]){ sum = salaries[key] } } var d = sum + ' ' + key; return d; } console.log(maxsalary(salaries)); 

There is an object salaries with salaries. Write the code that displays the name of the employee who has the highest salary.

If the object is empty, then let it display “no employees”.

I do not know how to make it display "no employees" if the object is empty

3 answers 3

 var salaries = { "Вася": 100, "Петя": 300, "Даша": 350 }; function maxsalary(obj){ var max = null,name =''; for(key in salaries){ if (max <= salaries[key]) { max = salaries[key]; name = key; } } return name ? max + ' ' + name : 'нет сотрудников'; } console.log(maxsalary(salaries)); 

    It is enough to set the default value for d , before the loop.

    In this case, if the object is empty, the loop will not enter and the value of d will not change.

    In addition, the function now does not use the passed parameter, but uses a global variable. This also needs to be fixed.

    Example:

     var salaries = { "Вася": 100, "Петя": 300, "Даша": 250 }; var salariesEmpty = {}; function maxsalary(obj) { var sum = 0; var d = 'нет сотрудников'; for (var key in obj) { if (sum < obj[key]) { sum = obj[key]; d = sum + ' ' + key; } } return d; } console.log(maxsalary(salaries)); console.log(maxsalary(salariesEmpty)); 

       function maxsalary(obj){ var t = Object.keys(salaries).length == 0; var sum = 0; [salaries].filter((v, i, e) => { cobst arr = []; const keys = Object.keys(obj); for(const key of keys) { arr.push(v[key]); } const max = arr.sort().reverse()[0]; sum = max; return v; }) return t ? 'Нит никаво' : sum; }