JS Syntax Basics
beginnerPart 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 variablesconst— block-scoped, cannot be reassigned, preferred for constants and referencesvar— function-scoped, can be redeclared, hoisted withundefinedinitialization. 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).
Exercises
Fix Variable Declarations
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