How do you pass a global merge field type $User into javascript?

I'm able to pull the User First Name into the HTML with the below HTML, but I would like to pass the User First Name into the Javascript within Visualforce.

How would I go about doing that? I've tried the below, but I get the following error:

  Uncaught ReferenceError: Chris is not defined

Chris is my name which I want it to alert me of. I've tried to turn this into a string with no luck either.

Below is what I'm trying

<apex:page >
        Hello {!$User.FirstName}



1 Answer 1


You need to surround the expression with {! } to let Visualforce know to evaluate the expression and output the text into the page. Then, because you want the output to be a valid JavaScript string, quotes are also needed. (Without the quotes JavaScript assumes the name is an existing variable.)

So altogether:


Use your browser's "View Source" or "Inspect Element" feature to check what is being output into the HTML page.

PS Corrected answer based on comments that JSENCODE is also needed. Avoids a JavaScript error if the string contains the same quote that is used to indicate that its a JavaScript string, and avoids the security risk of the text containing executable JavaScript.

  • 1
    Humbly recommend using JSENCODE() function too Commented Dec 14, 2014 at 23:41
  • Not using JSENCODE had bitten me before; that's definitely necessary for text fields.
    – Mike Chale
    Commented Dec 15, 2014 at 2:43
  • @bigassforce and Mike Chale I've added that correction to the answer - thanks.
    – Keith C
    Commented Dec 15, 2014 at 8:55

You must log in to answer this question.

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