1

I wrote a simple bit of JavaScript to create a HTML table.
It is populated by iterating over an array

var resultSet;
for (var i = 0, i < questions.length;; i++){ 
   ...
    resultSet += '<tr>' + '<td>' + i + '</td><td>' + questions[i].question + '</td><td>' + questions[i].userAnswer + '</td><td>' +
questions[i].correctAnswer + '</td>' + '</tr>';
}

So this an imperative approach. I was reading about Scala where an example to something similar would be:

questions.map(n => '<tr>' + '<td>' + '</td><td>' + questions[i].question  + ...);

Which is a functional. The emphasis being on the what rather than the how.

So I am wondering how to make my JavaScript more functional?

Use of JQuery of course permitted.

2 Answers 2

3

Javascript has Array.forEach however with limited compatibility: While all other browsers support it, IE only supports it from IE9 on - so you might need a shim for the other IEs.

Basically you could write:

questions.forEach(function(a){
resultSet += '<tr><td>' + a.question + '</td><td>' + 
             a.userAnswer + '</td><td>' +
             a.correctAnswer + '</td></tr>';
});

jQuery provides .each() which gives you the same functionality:

$.each(questions, function(index, value) {
  /* Do your stuff*/
});
Sign up to request clarification or add additional context in comments.

1 Comment

Does JQuery support something very similar which make allowances for all IE?
2

First, correct Scala will be

questions.map(q => '<tr>' + '<td>' + '</td><td>' + q.question  + ...);

where q is an element of questions, not an index.

JavaScript also has map (see Browser Compatibility at the end for browsers which support this method). So it's the same:

questions.map(function(q) { 
  return '<tr>' + '<td>' + '</td><td>' + q.question + ... 
});

2 Comments

Javascripts map is for mapping one array to another, not for the purpose the OP wants. Also beware the Compatibility.
@Christoph Same in Scala, so I assumed resultSet was an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.