Basic Syntax and Variables
Understanding JavaScript’s basic
syntax and how to work with variables is essential for writing effective code.
Statements
and Semicolons
- A statement is a single instruction that tells
the browser to do something.
- In JavaScript, statements typically end with a semicolon
(;).
- Although semicolons are optional in many cases due to
Automatic Semicolon Insertion (ASI), it’s good practice to include them to
avoid unexpected errors.
Example:
let
message = "Hello, world!";
console.log(message);
Comments
Comments help you document your code
and make it easier to understand. JavaScript supports two types:
- Single-line comments
start with //
//
This is a single-line comment
- Multi-line comments
are wrapped between /* and */
/*
This is a
multi-line comment
*/
Variables:
var, let, and const
Variables store data values.
JavaScript provides three keywords to declare variables:
- var
The old way to declare variables. Function-scoped and allows redeclaration. Generally avoided in modern code. - let
Block-scoped and allows reassignment but not redeclaration in the same scope. Preferred for variables that change. - const
Block-scoped and cannot be reassigned after initial assignment. Used for constants or values that shouldn’t change.
Example:
var
age = 25;
let
name = "Alice";
const
PI = 3.14159;
Data
Types
JavaScript variables can hold
different types of data:
- String:
Text enclosed in quotes
"Hello", 'World' - Number:
Numeric values (integers or decimals)
42, 3.14 - Boolean:
Logical values true or false
- Null:
Represents an intentional absence of any value
let data = null; - Undefined:
A variable declared but not assigned a value yet
let result; // undefined - Symbol:
A unique and immutable primitive value used for identifiers
let id = Symbol('id');