Search code examples
javascriptarraystemplate-strings

How to access elements of a Javascript array using Template Strings?


I have a Javascript Array whose value I need to access in a Template String, how can I do that?

I have something like this,

//an array named link globally defined
function formatter(row,value){
    return `<a href = $link[$row]>Abc</a>`;
}

Solution

  • If you are plainly asking about 'Accessing an array value inside a template string', then:

    const arr = [1,2,3]
    
    console.log(`${arr[0]}`) // 0
    

    If you want to have an index as a variable, then you go

    const arr = [1,2,3]
    const index = 0
    console.log(`${arr[index]}`) // 1
    

    And to answer your code:

    const link = [1,2,3]
    
    function formatter(row,value){
        return `<a href = ${link[row]}>Abc</a>`;
    }
    

    would just work.

    for example

    formatter(0) // "<a href = 1>Abc</a>"