Array Item With Quotations

let condiments = [‘Ketchup’, ‘Mustard’, ‘Soy Sauce’, ‘Sriracha’];

const utensils = [‘Fork’, ‘Knife’, ‘Chopsticks’, ‘Spork’];

condiments.push(‘Frank’s Red Hot’);

I was wondering how I would go about adding an item to an array that has quotation marks. For example, I wanted to add Frank’s Red Hot to the condiments array. However when printed to the console I get [Ketchup, Mustard, Soy Sauce, Sriracha, Frank’s Red Hot] with the backslash and everything. I even tried “Frank’s Red Hot”. Same thing happened. Why? And, how can I go about doing this correctly?

Thank you.

First, it is important to note that anything in quotes is a String object. So we have an array of strings.

Since the appostrophe doubles as a quote mark, is must be escaped when enclosed in a single quoted string.

'Frank\'s Red Hot'

However, when enclosed by double quotes, escapement is not required and the apostrophe is treated as a printable character.

"Frank's Red Hot"

Even if we write all the entries in double quotes, the console translates all strings to single quoted, so automatically escapes the apostrophe found inside one of the strings.

let condiments = ["Ketchup", "Mustard", "Soy Sauce", "Sriracha"];

condiments.push( "Frank's Red Hot");

[ 'Ketchup',
  'Soy Sauce',
  'Frank\'s Red Hot' ]

Now when we iterate over the array and log out each item separately,

condiments.forEach(x => console.log(x));
Soy Sauce
Frank's Red Hot

All is well. Since it is not very common for an array to be logged in a single statement (except for inspecting and debugging) this does not represent a problem.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.