TutorialsJSJS Syntax Basics
Share:

JS Syntax Basics

beginner

Part of JavaScript Fundamentals

Theory

JavaScript syntax is the set of rules that defines correctly structured programs. Every program is composed of statements — individual instructions that perform actions — and expressions — code that produces a value.

Statements vs Expressions: A statement is an instruction (like let x = 5;). An expression evaluates to a value (like 2 + 3). Expressions can be part of statements. For example, in let y = 10 * 2;, 10 * 2 is an expression and the whole line is a statement.

Comments are ignored during execution. Use // for single-line and /* */ for multi-line comments. Comments document code, disable lines temporarily, and explain complex logic.

Semicolons are optional in JavaScript due to Automatic Semicolon Insertion (ASI). However, ASI can sometimes produce unexpected results. Best practice is to use semicolons explicitly, especially at the start of lines beginning with ( or [.

Strict mode ("use strict") was introduced in ES5. It prohibits unsafe actions like assigning to undeclared variables, duplicating parameter names, and using with statements. Activate it by placing "use strict"; at the top of a script or function.

Variable declarations:

  • let — block-scoped, can be reassigned, preferred for mutable variables
  • const — block-scoped, cannot be reassigned, preferred for constants and references
  • var — function-scoped, can be redeclared, hoisted with undefined initialization. Avoid in modern code

Hoisting moves declarations to the top of their scope. Functions declared with function are fully hoisted. var declarations are hoisted but not initialized. let and const are hoisted but not initialized (Temporal Dead Zone).

Syntax Examples
javascript
let vs const vs var
javascript

Exercises

Fix Variable Declarations

easy

The following code has variable declaration issues. Rewrite it using proper let and const declarations. Use const for values that shouldn't change and let for values that do: pi = 3.14; radius = 5; pi = 3.14159; area = pi * radius * radius; console.log(area);

Starter Code:

// Fix the variable declarations below\npi = 3.14;\nradius = 5;\narea = pi * radius * radius;\nconsole.log(area);

Expected Output:

78.53975

Mini Quiz

Mini Quiz