0

In an online course, I'm following on Udemy, the instructor is putting semicolons after lines and says they are needed. I forgot to put some because I'm just getting off of Python and the code still ran.

var firstName = 'John';
console.log(firstName);

var lastName = 'Smith';
var age = 28;

console.log(lastName)
console.log(age)

When I right click on the browser and click on console the first, last name and age are displayed. Can anyone help explain why its working without the semicolons? I'm assuming they are needed when writing Javascript.

OdatNurd
  • 21,371
  • 3
  • 50
  • 68
Kar900
  • 47
  • 1
  • 1
  • 6

2 Answers2

1

JavaScript doesn't actually need semicolons. Unless you're writing more than one statement on the same line (please don't, with the exception of for loops)

shiruken
  • 25
  • 4
1

This is because Javascript parser will automatically insert semicolon for you in the following situations:

Copypasta from Flavio Copes' Let’s talk about semicolons in JavaScript

  1. when the next line starts with code that breaks the current one (code can spawn on multiple lines)
  2. when the next line starts with a }, closing the current block
  3. when the end of the source code file is reached
  4. when there is a return statement on its own line
  5. when there is a break statement on its own line
  6. when there is a throw statement on its own line
  7. when there is a continue statement on its own line

For best practices, semicolons should be manually inserted.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Steven Luo
  • 2,350
  • 3
  • 18
  • 35