Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Syntax — Complete Guide

JavaScript syntax defines the rules for writing valid code.

Mastering syntax helps you avoid errors and write clean, professional programs.

Why We Need It

Strong syntax fundamentals prevent bugs and make debugging faster.

Syntax knowledge is essential for interviews and real-world development.

Syntax

const name = "John";
if (name) { console.log(name); }
for (let i = 0; i < 3; i++) { console.log(i); }

Basic Example

1. Valid vs Invalid Syntax

// Valid syntax
const name = "John";
console.log(name);

// Invalid syntax - missing quotation mark
// const name = "John;  // SyntaxError!

Valid syntax follows JavaScript rules. Invalid syntax throws SyntaxError.

Real World Example

2. Statements vs Expressions

let name = "Alice";      // Statement
5 + 10;                  // Expression
let result = 5 + 10;      // Expression inside statement

Statements perform actions. Expressions produce values.

Multiple Use Cases

What Is JavaScript Syntax?

JavaScript syntax defines the rules for writing valid JavaScript programs.

It's similar to grammar in human language - if syntax is incorrect, the program won't execute.

The JavaScript engine reads and parses your code according to these syntax rules before execution.

Understanding syntax is the foundation for writing clean, error-free, and professional code.

Statements and Expressions

A statement is a complete instruction that performs an action.

An expression is any code that produces a value.

Statements end with semicolons (usually), while expressions produce results.

Understanding the difference helps you write clearer code and avoid common mistakes.

Variables: let, const, and var

Variables are named containers that store values in memory.

JavaScript has three keywords for declaring variables: const, let, and var.

const declares a constant that cannot be reassigned after initialization.

let declares a block-scoped variable that can be reassigned.

var declares a function-scoped variable and should be avoided in modern code.

Data Types and Type Checking

JavaScript has seven primitive types and one complex type (object).

Primitive types are immutable and stored directly in memory.

Objects are reference types and stored as references in memory.

Use typeof operator to check variable types.

JavaScript is dynamically typed - the same variable can hold different types at different times.

Naming Conventions and Identifiers

Identifiers are names for variables, functions, classes, and objects.

JavaScript has naming rules and conventions that improve code readability.

Following conventions makes code more maintainable and professional.

Clear naming reduces bugs and makes collaboration easier.

Operators and Operator Precedence

Operators perform operations on values and return results.

JavaScript has arithmetic, comparison, logical, assignment, and other operators.

Operator precedence determines the order operations execute.

Understanding precedence prevents unexpected behavior.

Code Blocks and Scope

Code blocks are sections enclosed in curly braces {}.

Blocks define scope for variables declared with let and const.

Block scope prevents variable pollution and accidental overwrites.

Understanding scope is crucial for avoiding bugs and writing maintainable code.

Keywords and Reserved Words

Keywords are words that have special meaning in JavaScript.

Reserved words cannot be used as variable names.

Some words are reserved for future use.

Using keywords as identifiers causes SyntaxError.

Strict Mode

Strict mode enforces stricter parsing and error handling.

It prevents certain unsafe actions and throws errors early.

Enable strict mode with 'use strict' directive.

Modern frameworks like Next.js use strict mode by default.

More Examples

3. Variables: let, const, var

const PI = 3.14;
let counter = 0;
counter = counter + 1;

// Avoid var in modern code
var legacy = "old";

Use const by default, let for reassignment, avoid var.

4. Operators and Precedence

5 + 10 * 2;    // 25
(5 + 10) * 2; // 30

Multiplication happens before addition unless you use parentheses.

5. Blocks and Scope

if (true) {
  let x = 10;
  console.log(x);
}
// console.log(x); // Error

let and const are block-scoped, preventing accidental access outside blocks.

Comparison

Without

// Invalid syntax
const name = "John;

With

// Valid syntax
const name = "John";

Common Mistakes and Fixes

Relying too heavily on ASI (Automatic Semicolon Insertion)

Use semicolons consistently to avoid edge cases and improve code clarity.

Using var instead of let/const

var has function scope and hoisting issues. Always use const first, then let. Avoid var.

Confusing == (loose equality) with === (strict equality)

Always use === to avoid type coercion surprises. Use == only when explicitly needed.

Using unclear variable names

Use descriptive names that explain the variable's purpose. Avoid single letters except in loops.

Not understanding operator precedence

Use parentheses to make precedence explicit and avoid relying on implicit precedence rules.

Interview Questions

What is JavaScript syntax?

It is the set of rules that define valid JavaScript code structure.

Is semicolon mandatory?

Not strictly, but consistent semicolons help prevent edge cases.

What is the difference between statement and expression?

Statements perform actions; expressions produce values.

Practice Problem

Practice: Declare a const and log it only if it is truthy.

const value = "JavaScript";

// TODO: log the value if it exists

One Possible Solution

const value = "JavaScript";

if (value) {
  console.log(value);
}

Frequently Asked Questions

Is semicolon mandatory in JavaScript?

No, Automatic Semicolon Insertion handles missing semicolons in most cases. However, using semicolons consistently is a professional best practice.

Should I use var, let, or const?

Use const by default for immutability. Use let when you need to reassign. Avoid var entirely in modern code.

What's the difference between == and ===?

== performs type coercion and can cause unexpected results. === compares both value and type strictly. Always prefer ===.

Why is typeof null returning 'object'?

It's a quirk in JavaScript's design. null is actually a primitive type, but typeof has a bug treating it as 'object'.

What's the scope difference between let and var?

let has block scope (safer). var has function scope and exhibits unexpected hoisting behavior. Prefer let.

Do I need to memorize operator precedence?

No. Use parentheses to make intent explicit. Code readability is more important than relying on precedence memory.

Is strict mode mandatory?

Modern frameworks enable it by default. It's recommended to always enable it explicitly in your code.

Can I declare variables without const/let/var?

You can, but it creates a global variable (or error in strict mode). Always declare with const, let, or var.

Try It Yourself

Run the valid vs invalid syntax sample and adjust it.