JavaScript Syntax: Statements, Semicolons, Comments and Strict Mode

Every language has grammar rules, and JavaScript is no exception. Most “my code does not work” moments for beginners come from small syntax issues: a capital letter, a missing bracket, a line break after return. In this lesson you will learn the rules that every JavaScript file follows, how to write comments, when semicolons matter, and why every modern script runs in strict mode.

Advertisement

📖 What You’ll Learn: statements, expressions and blocks, case sensitivity, valid identifiers and reserved words, single-line, multi-line and JSDoc comments, semicolons and automatic semicolon insertion (ASI), strict mode and what it changes, and naming and style conventions.


🧱 Statements, Expressions and Blocks

Definition: a statement is one instruction that the program performs, such as declaring a variable or running an if. An expression is any piece of code that produces a value, such as 2 + 3 or price * 0.9. A block is a group of statements inside curly braces { }.

📄 statements.js

let price = 100;           // declaration statement
price = price * 0.9;       // expression statement (assignment)
console.log(price);        // expression statement (function call)

if (price < 95) {          // if statement with a block
  console.log("Discount applied");
  console.log("New price:", price);
}

⌨️ Terminal

node statements.js

🖥️ Output

90
Discount applied
New price: 90
  • price * 0.9 is an expression: it produces the value 90.
  • Statements run from top to bottom, one after another.
  • The two lines inside { } form one block. They run only when the condition is true.

💡 Tip: A quick test: if you can put the code on the right side of const x = ..., it is an expression. const x = 2 + 3 works; const x = if (...) does not, because if is a statement.


🔠 Case Sensitivity and Whitespace

JavaScript is case-sensitive: total, Total and TOTAL are three different names. Keywords are always lowercase (let, if, function).

📄 case.js

let total = 10;
let Total = 20;
console.log(total, Total);

⌨️ Terminal

node case.js

🖥️ Output

10 20

Spaces, tabs and line breaks between tokens are ignored, so the two statements below are identical. Use whitespace to make code readable, not to change its meaning.

📄 whitespace.js

const sum=1+2;
const   sum2   =   1   +   2  ;
console.log(sum === sum2);

⌨️ Terminal

node whitespace.js

🖥️ Output

true

🏷️ Identifiers and Reserved Words

Definition: an identifier is a name you give to a variable, function or class. The rules:

  • It may contain letters, digits, _ and $.
  • It must not start with a digit.
  • It must not be a reserved word such as let, class, return, if, new or function.
ValidInvalidWhy invalid
userNameuser-name- is the minus operator
_count, $price2ndUserStarts with a digit
item2classReserved word

Using a reserved word as a name is a syntax error, so the file does not run at all:

📄 reserved.js

let class = "QA";
console.log(class);

⌨️ Terminal

node reserved.js

🖥️ Output

/home/you/js-course/reserved.js:1
let class = "QA";
    ^^^^^

SyntaxError: Unexpected token 'class'

Node.js v26.13.0

Advertisement

💬 Comments: Single-Line, Multi-Line and JSDoc

Definition: a comment is text that JavaScript ignores. Use comments to explain why code does something, not to repeat what it does.

📄 comments.js

// Single-line comment: everything after // is ignored

/*
  Multi-line comment.
  Useful for longer notes or for temporarily disabling code.
*/

/**
 * JSDoc comment: documents a function for editors and tools.
 * @param {number} price - Original price
 * @param {number} percent - Discount from 0 to 100
 * @returns {number} Price after discount
 */
function applyDiscount(price, percent) {
  return price - (price * percent) / 100; // percent of the price
}

console.log(applyDiscount(250, 20));

⌨️ Terminal

node comments.js

🖥️ Output

200
  • // comments run to the end of the line, so they can follow code on the same line.
  • /* ... */ comments can span many lines but cannot be nested.
  • /** ... */ JSDoc comments are read by VS Code: hover over applyDiscount to see the description and parameter types.

💡 Tip: In VS Code, select lines and press Ctrl+/ to comment or uncomment them all at once.


🔚 Semicolons and Automatic Semicolon Insertion (ASI)

Statements end with a semicolon ;. If you leave it out, JavaScript usually inserts it for you at the line break. This is called Automatic Semicolon Insertion (ASI). It works most of the time, but two cases surprise everyone.

Trap 1: a line break after return

📄 asi-return.js

function getUser() {
  return
  { name: "Asha" };
}

console.log(getUser());

⌨️ Terminal

node asi-return.js

🖥️ Output

undefined

JavaScript inserts a semicolon right after return, so the function returns undefined and the object below it is never reached. Fix: put the opening brace on the same line: return {.

Trap 2: a line that starts with [ or (

📄 asi-array.js

const a = 1
const b = 2
[a, b].forEach((n) => console.log(n))

⌨️ Terminal

node asi-array.js

🖥️ Output

/home/you/js-course/asi-array.js:3
[a, b].forEach((n) => console.log(n))
    ^

ReferenceError: Cannot access 'b' before initialization
    at Object.<anonymous> (/home/you/js-course/asi-array.js:3:5)

Node.js v26.13.0

No semicolon is inserted after 2, because 2[a, b] could be valid code. JavaScript reads the last two lines as one statement, const b = 2[a, b].forEach(...), which uses b before it exists. Fix: end statements with semicolons.

⚠️ Watch out: Pick one style and let a tool enforce it. This course uses semicolons everywhere, which is the default in Prettier and avoids both traps.


Advertisement

🛡️ Strict Mode

Definition: strict mode is a safer version of JavaScript that turns silent mistakes into errors. Enable it by writing "use strict"; as the first statement of a file or a function.

Without strict mode (“sloppy mode”), assigning to a misspelled variable silently creates a new global variable:

📄 sloppy.js

let total = 0;

function addItem(price) {
  totl = total + price; // typo: "totl" instead of "total"
}

addItem(50);
console.log("total:", total);
console.log("accidental global:", globalThis.totl);

⌨️ Terminal

node sloppy.js

🖥️ Output

total: 0
accidental global: 50

The bug is hidden: total is still 0 and a stray global called totl appeared. With strict mode, the same typo stops the program at the exact line:

📄 strict.js

"use strict";

let total = 0;

function addItem(price) {
  totl = total + price; // typo: "totl" instead of "total"
}

addItem(50);

⌨️ Terminal

node strict.js

🖥️ Output

/home/you/js-course/strict.js:6
  totl = total + price; // typo: "totl" instead of "total"
       ^

ReferenceError: totl is not defined
    at addItem (/home/you/js-course/strict.js:6:8)
    at Object.<anonymous> (/home/you/js-course/strict.js:9:1)

Node.js v26.13.0
Strict modeWhat changes
Assigning to an undeclared variableThrows ReferenceError instead of creating a global
Duplicate parameter namesfunction f(a, a) {} is a SyntaxError
this in a plain function callIs undefined instead of the global object
Writing to a read-only propertyThrows TypeError instead of failing silently
Reserved words for the futurelet, static, implements, package and others cannot be used as names

📌 Note: You often get strict mode automatically. ES modules (files that use import/export, or .mjs files) and code inside a class are always strict. Playwright and most modern tools load your tests as modules, so strict rules apply there even without "use strict".

📄 module.mjs

// An .mjs file is an ES module, so strict mode is on automatically
count = 1;
console.log(count);

⌨️ Terminal

node module.mjs

🖥️ Output

file:///home/you/js-course/module.mjs:2
count = 1;
      ^

ReferenceError: count is not defined
    at file:///home/you/js-course/module.mjs:2:7

Node.js v26.13.0

✍️ Naming and Style Conventions

KindConventionExample
Variables and functionscamelCaseuserName, getTotalPrice()
ClassesPascalCaseLoginPage, ApiClient
Constants that never changeUPPER_SNAKE_CASEMAX_RETRIES, BASE_URL
BooleansStart with is/has/canisVisible, hasError
Fileskebab-caselogin-page.js, cart.test.js

Other widely used style rules: indent with 2 spaces, use double or single quotes consistently, put opening braces on the same line, and keep lines under about 100 characters. Prettier applies all of these for you when you save.

📄 naming.js

const MAX_RETRIES = 3;

class LoginPage {
  isLoggedIn = false;
}

function getRetryMessage(attempt) {
  return `Attempt ${attempt} of ${MAX_RETRIES}`;
}

const page = new LoginPage();
console.log(getRetryMessage(1), "| logged in:", page.isLoggedIn);

⌨️ Terminal

node naming.js

🖥️ Output

Attempt 1 of 3 | logged in: false

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Which of these identifiers are valid: firstName, 1stName, first_name, $total, first-name, new?

Show answer

Valid: firstName, first_name, $total. Invalid: 1stName (starts with a digit), first-name (contains -), new (reserved word).

Q2. Predict the output, then run the code to check.

function getStatus() {
  return
    "passed";
}
console.log(getStatus());
Show answer

📄 status.js

function getStatus() {
  return
    "passed";
}
console.log(getStatus());

🖥️ Output

undefined

ASI inserts a semicolon after return, so the function returns undefined. Put the value on the same line: return "passed";.

Q3. Add a JSDoc comment to this function describing its two parameters and return value.

function fullName(first, last) {
  return first + " " + last;
}
Show answer

📄 fullname.js

/**
 * Joins a first and last name.
 * @param {string} first - First name
 * @param {string} last - Last name
 * @returns {string} The full name
 */
function fullName(first, last) {
  return first + " " + last;
}

console.log(fullName("Asha", "Rao"));

🖥️ Output

Asha Rao

Q4. This code prints 0 instead of 15. Turn on strict mode to find the bug, then fix it.

let count = 0;
function add(n) {
  cuont = count + n;
}
add(15);
console.log(count);
Show answer

With "use strict"; at the top, Node.js throws ReferenceError: cuont is not defined and points to the typo. The fixed code:

📄 count.js

"use strict";

let count = 0;
function add(n) {
  count = count + n;
}
add(15);
console.log(count);

🖥️ Output

15

Q5. Rename these to follow conventions: a class checkout_page, a constant timeout that is always 30000, a boolean visible.

Show answer

CheckoutPage (PascalCase for classes), TIMEOUT_MS or DEFAULT_TIMEOUT (UPPER_SNAKE_CASE, and the unit in the name helps), isVisible (booleans start with is/has/can).

Q6. Fix the ASI bug so the program prints 1 and 2.

const a = 1
const b = 2
[a, b].forEach((n) => console.log(n))
Show answer

📄 fixed.js

const a = 1;
const b = 2;
[a, b].forEach((n) => console.log(n));

🖥️ Output

1
2

The semicolon after 2 ends the statement, so the array on the next line is a new statement.


🧠 MCQ Quiz: Syntax, Comments and Strict Mode

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which is an expression?
  2. Are userName and username the same variable?
  3. Which identifier is invalid?
  4. What does this return?
    function f() {
      return
      42;
    }
  5. How do you enable strict mode for a whole script file?
  6. In sloppy (non-strict) mode, what does assigning to an undeclared variable do?
  7. Which code always runs in strict mode automatically?
  8. Which comment style does VS Code show when you hover over a function?
  9. Why can const b = 2 followed by a line starting with [a, b] break?
  10. Which naming follows common JavaScript conventions?

💼 Interview Questions and Answers

Q1. What is the difference between a statement and an expression?

An expression produces a value (a + b, fn(), x > 5 ? "big" : "small") and can be used wherever a value is expected. A statement performs an action (if, for, return, a declaration). An expression followed by a semicolon is an “expression statement”. This matters for arrow functions: () => x + 1 returns the expression, but () => { x + 1 } is a block that returns undefined.

Q2. What is Automatic Semicolon Insertion, and when does it cause bugs?

ASI is the rule that inserts a semicolon at a line break when the next token cannot continue the statement, and always after return, break, continue and throw followed by a line break. Bugs appear when (1) a value is placed on the line after return, which returns undefined, and (2) a line starts with (, [ or a template literal, which joins it to the previous line. Using semicolons or a formatter avoids both.

📄 asi-fixed.js

function config() {
  return {
    retries: 2,
  };
}
console.log(config());

⌨️ Terminal

node asi-fixed.js

🖥️ Output

{ retries: 2 }

Q3. What is strict mode, and is it on in a Playwright test file?

Strict mode is an opt-in restricted variant of JavaScript, enabled with "use strict", that throws on silent errors (undeclared variables, writes to read-only properties, duplicate parameters) and makes this undefined in plain function calls. ES modules and class bodies are always strict. Playwright test files written as ES modules or in TypeScript are compiled as modules, so the strict rules apply.

Q4. Why does let class = 1 fail before any line of the file runs?

It is a syntax error, and syntax errors are found when the engine parses the whole file, before execution starts. Because class is a reserved word, the parser cannot build the program, so nothing runs, not even console.log calls above the bad line. Runtime errors such as ReferenceError, in contrast, happen only when that line executes.

Q5. How do you keep code style consistent across a test automation team?

Agree on conventions (naming, quotes, semicolons), then automate them: Prettier for formatting, ESLint for code-quality rules, an .editorconfig for indentation, format-on-save in VS Code, and a CI step (npx prettier --check . and npx eslint .) so style problems fail the build instead of code review.


Advertisement

❓ Frequently Asked Questions

🤔 Are semicolons required in JavaScript?

Not strictly, because of ASI, but leaving them out can cause the bugs shown in this lesson. Most teams use semicolons, or omit them consistently with a tool such as Prettier or ESLint that warns about the risky cases.

🤔 Should I write “use strict” in every file?

Only in classic scripts and CommonJS files. ES modules, classes and most modern tooling are strict automatically, and adding the directive there does no harm.

🤔 How many types of comments are there in JavaScript?

Two: single-line // and multi-line /* */. JSDoc comments (/** */) are multi-line comments with a special format that editors understand.

🤔 Is JavaScript whitespace-sensitive like Python?

No. Indentation does not change the meaning of JavaScript code. Line breaks matter only for ASI, which is why return followed by a line break returns undefined.


🏁 Summary

  • Statements perform actions; expressions produce values; blocks { } group statements.
  • JavaScript is case-sensitive, and identifiers cannot start with a digit or be reserved words.
  • Use // and /* */ comments to explain why, and JSDoc to document functions.
  • ASI inserts semicolons at line breaks, but never put a value on the line after return and never start a line with [ or ( without a semicolon before it.
  • Strict mode turns silent mistakes into errors; ES modules and classes are always strict.

Next, continue with Lesson 5: Console Methods and Debugging Basics.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in