SQLite " vs ' vs ` just need clarification

I got stuck on the Cumulative Project ‘Codestrips’ with creating a new table in the sql.js file.
I wrote it like this:

db.run('DROP TABLE IF EXITS Strip', error => {

  db.run(`
    CREATE TABLE Strip (
    id INTEGER PRIMARY KEY,
    head TEXT NOT NULL,
    body TEXT NOT NULL,
    background TEXT NOT NULL,
    bubble TEXT NOT NULL,
    bubble_text TEXT NOT NULL DEFAULT '',
    caption TEXT NOT NULL DEFAULT '')
  `);
})

And, it would throw an error:

 db.run('CREATE TABLE Strip (
         ^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Invalid or unexpected token

I eventually figured out that if I put in a backtick (`) rather than a single quote (’), then it did not throw an error and worked fine.

The thing is that I know I’ve used the single quote before in previous lessons and it worked:
db.run('CREATE TABLE Average (id INTEGER PRIMARY KEY, year INTEGER NOT NULL, temperature REAL NOT NULL)', logNodeError);

So, is this a rule that I should always use backticks?
Do I have to use them on db.get, db.all, etc.?
What is the protocol for using double quotes, single quotes and backticks in SQLite?

Thanks in advance,

Chip

It’s a JavaScript thing, not SQLite or anything else. Those commands accept strings, but JavaScript didn’t know what to do when you used multiple lines for a single-quote string.

Putting all the SQLite stuff side, consider the following:

const myStringOne = `
  I can be multiple lines
  because I'm using backticks.
  
  Here too.
`;

console.log(myStringOne);
/* outputs to console:

  I can be multiple lines
  because I'm using backticks.
  
  Here too.
*/
const myStringTwo = '
 I am about to be an error
 because I used a single-quote
';

/* results in:

const myStringTwo = '
                    ^
SyntaxError: Invalid or unexpected token
*/

If you did want to use multiple lines with single quotes, then you’d need to use concatenation to accomplish it.

const myStringThree = '' +
 'This will work ' +
 'because of concatenation, ' +
 'but I need to be careful with spacing ' +
 'due to it all being put together on one line. ' +
 'It is possible to add line-breaks though. Watch this\n\n' +
 'Each backslash n added a line break.';

console.log(myStringThree);
/* outputs to console:

This will work because of concatenation, but I need to be careful with spacing due to it all being put together on one line. It is possible to add line-breaks though. Watch this

Each backslash n added a line break.
*/
1 Like

That is exactly what I needed!
I don’t remember that ever being explained before.
Syntax seems to be where I usually get tripped up, so thank you for the clarification. It will help avoid a lot of future errors.

1 Like