If I have two simple apex methods in my controller:

 public String getStringOne() {
    String returnStringOne = 'this is the string';
    return returnStringOne;

 public String getStringTwo() {
    String returnStringTwo = 'this is the other string';
    return returnStringTwo;

And I have an array in my js file:

var myArray = [];

How do I pass the results of both of these methods into my array?

['this is the string', 'this is the other string']

2 Answers 2


@Poet's answer handles most of the cases except where the StringOne contains Single quotes in it.

If there is a single quote like StringOne='Lewi\'s' it will break your Javascript execution, because it will render to

     var myArray = ['Lewi's']

Better approach is:

 var myArray = ['{!JSENCODE(StringOne)}', '{!JSENCODE(StringTwo)}'];


If the object you want to render becomes bigger and complicated, I would recommend Serializing and Deserializing it as below:

    public string getMyArrayContent() {
         List<String> myArray = new List<String>();
         return JSON.serialize(myArray);

In Javascript:

   var myArray = JSON.parse('{!JSENCODE(myArrayContent)}');
  • The JSENCODE function encodes text strings and merge field values for use in JavaScript by inserting escape characters, such as a backslash (\), before unsafe JavaScript characters, such as the apostrophe (').

  • {!JSENCODE(text)} and replace text with the merge field or text string that contains the unsafe JavaScript characters. So it not just prevents you from broken JS but also prevents XSS vulnerability if the string contains unsafe JavaScript code.

  • JSON.parse(str) is a Javascript method which takes a String and converts it into Javascript object (Array here)

  • 2
    Good point! I always forget about those little buggers!
    – Dan Jones
    Commented Feb 24, 2016 at 14:28
  • An explanation of why the JSENCODE/parse can make sense would be helpful here.
    – Keith C
    Commented Feb 24, 2016 at 14:43
  • Poet thank you, I have faced this issue on Production org, so I became cautious now :) Daft glad that it helped you @KeithC Updated the explanation, please let me know if that would help people Commented Feb 24, 2016 at 14:51
  • 2
    I was really looking for why what you have is better than var myArray = {!myArrayContent};...
    – Keith C
    Commented Feb 24, 2016 at 15:24

You should be able to simply do the following:

var myArray = ['{!StringOne}', '{!StringTwo}'];


var myArray = [];


Effectively because your two methods are just returning a String, you can just render them into the JS on your page and it'll work the same.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .