Uncaught SyntaxError: Unexpected token 'if'

paresh shiyal

i'm New in Javascript

Code :-

$('#similar-artist').append('<div class="chip" data-uuid="'+ item.artist_id +'" >'+ item.name  + '  ' + if (item.last_name){ item.last_name }else{}  +'</div>');

Errore :- Uncaught SyntaxError: Unexpected token 'if'

Thank You

CertainPerformance

You need the conditional operator instead, because it resolves to an expression (if cannot be used in an expression context):

+'" >'+ item.name  + '  ' + (item.last_name ? item.last_name : '') +'</div>'

That's for the general case - you can alternate between item.last_name and ''. If you want to interpolate something only if it's truthy, like here, you can use || as a shortcut:

+'" >'+ item.name  + '  ' + (item.last_name || '') +'</div>'

But, even better, consider using a template literal instead, for improved readability:

const html = `<div class="chip" data-uuid="${item.artist_id}">${item.name}  ${item.last_name || ''}</div>`;
$('#similar-artist').append(html);

Also keep in mind that concatenating arbitrary HTML is a potential security risk. Unless the item is coming from a secure, trusted source of your own, you might want to do:

$(`<div class="chip" />`)
  .attr('data-uuid', item.artist_id)
  .text(`${item.name}  ${item.last_name || ''}`)
  .appendTo('#similar-artist');

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive