How to get expected document.write output using function

At the start I would like to mention that I’m at the beginning stage of my journey learning JavaScript, so sorry in advance if the question looks silly:

I’ve got 2 arrays with index number assign to them: I’m trying to code a function that will return desired name and job title when I point it to desired index number from the names array, but I’m stuck.

My function looks like this and my imagined output would be, for example if i call
name_and_job(names[1]),
it’ll return:

Michael, It Director

var job_title = new Array();
job_title[0] = "IT Specialist";
job_title[1] = "IT Director";
job_title[2] = "Administration Specialist";
job_title[3] = "Payroll Specialist";

var names = new Array();
names[0] = "Peter";
names[1] = "Michael"
names[2] = "Elizabeth";
names[3] = "Scotty";


function name_and_job() {
  if (names == 0)  {
    document.write(names[0] + " ," + job_title[0])
  } else if (names == 1) {
    document.write(names[1] + " ," + job_title[1])
  } else if (names == 2) {
    document.write(names[2] + " ," + job_title[2])
  } else if (names == 3) {
    document.write(names[3] + " ," + job_title[03])
  }
}

name_and_job() 

Answer

But names is an array and not == 0

You might mean

var job_title = new Array();
job_title[0] = "IT Specialist";
job_title[1] = "IT Director";
job_title[2] = "Administration Specialist";
job_title[3] = "Payroll Specialist";

var names = new Array();
names[0] = "Peter";
names[1] = "Michael"
names[2] = "Elizabeth";
names[3] = "Scotty";


function name_and_job(idx) {
  document.write(names[idx] + ", " + job_title[idx]);
}

name_and_job(1);

or better

const people = [
  {"name":  "Peter","job_title": "IT Specialist"},
  {"name": "Michael","job_title": "IT Director"},
  {"name": "Elizabeth","job_title": "Administration Specialist"},
  {"name": "Scotty","job_title": "Payroll Specialist"}
];

function name_and_job(idx) {
  const person = people[idx];
  document.getElementById("name").textContent = person.name;
  document.getElementById("job_title").textContent = person.job_title;
}

name_and_job(1);
<span id="name"></span>, <span id="job_title"></span>

or even

const people = [
  {"name":  "Peter","job_title": "IT Specialist"},
  {"name": "Michael","job_title": "IT Director"},
  {"name": "Elizabeth","job_title": "Administration Specialist"},
  {"name": "Scotty","job_title": "Payroll Specialist"}
];

document.getElementById("people").innerHTML = people.map(({name,job_title}) => `<li>${name}, ${job_title}</li>`).join('');
<ul id="people"></ul>

Leave a Reply

Your email address will not be published. Required fields are marked *