lemmonlola
lemmonlola

Reputation: 17

chrome cannot run console.log() Uncaught SyntaxError: Invalid or unexpected token

That is my html code


     <body>
        <script src="../js/myjscode.js"></script>
    </body>

This is myjscode.js


     function firstFunction() {
            console.log("
        hello world ");
    }

    firstFunction();

if I type console.log("hello world "); on myjscode.js

is perfect output hello world

but if I type

function firstFunction() {
        console.log("
    hello world ");
}

firstFunction();

on myjscode.js

it show on chrome console Uncaught SyntaxError: Invalid or unexpected token

what wrong did I got?

Upvotes: 0

Views: 1178

Answers (5)

Thomas Tallman
Thomas Tallman

Reputation: 81

you can either A: put the console.log in the same line, or B: turn it into a button. or do both!

Javascript

function firstFunction() {
     console.log("hello world");
}
firstFunction();

HTML

<button onclick="firstFunction()">click me</button>

Upvotes: 0

user7394313
user7394313

Reputation: 552

If you do multi-line (like you do since you do linebreak after the quote) you must concatenate.

This works:

console.log("" +
    "hello world "
);

or

console.log(
 "hello world"
);

or:

console.log(
     "hello" +
      "world"
);

Upvotes: 0

Diogo Peres
Diogo Peres

Reputation: 1372

You have to put the console.log text in one line on your example.

Like this:

function firstFunction() {
        console.log("hello world");
}

firstFunction();

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

That is because there is a new line carriage return when you type the string in the new line inside the console.log() and due to that you get Uncaught SyntaxError: Invalid or unexpected token. To resolve that use a backquote instead of quotes:

function firstFunction() {
  console.log(`
  hello world`);
}

firstFunction();

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

You have to use an escape sequence to indicate a line break within a string; in your case,

"\nhello world"

Upvotes: 0

Related Questions