4. Basic Syntax
Statements and Expressions
Statements
Statements perform actions and don't return values:
let x = 5; // Variable declaration
console.log(x); // Function call
if (x > 3) { // Conditional
x = x + 1;
}
Expressions
Expressions return values:
5 + 3 // Arithmetic expression
x > 3 // Comparison expression
"Hello " + "World" // String concatenation
Semicolons
Semicolons are optional in JavaScript, but recommended:
// Good practice
let a = 1;
let b = 2;
// Also valid (automatic semicolon insertion)
let c = 3
let d = 4
Comments
// Single-line comment
/*
Multi-line
comment
*/
/**
* JSDoc comment
* @param {string} name - The name parameter
*/
function greet(name) {
return `Hello, ${name}!`;
}
Case Sensitivity
JavaScript is case-sensitive:
let myVariable = "Hello";
let myvariable = "World"; // Different variable
Whitespace
Whitespace is generally ignored:
// All these are equivalent
let x=1+2;
let x = 1 + 2;
let x = 1 + 2;
// But be consistent for readability
Code Blocks
Code blocks are enclosed in curly braces:
if (condition) {
// Code here runs if condition is true
statement1;
statement2;
}
Identifiers
Rules for naming variables, functions, etc.:
- Must start with letter, underscore (_), or dollar sign ($)
- Can contain letters, numbers, underscores, dollar signs
- Cannot be reserved words
- Case-sensitive
Valid identifiers:
myVariable
_myVariable
$myVariable
myVariable123
Invalid:
123variable // Cannot start with number
my-variable // Hyphens not allowed
var // Reserved word
Reserved Words
Some words are reserved and cannot be used as identifiers:
// Complete list of reserved words:
break, case, catch, class, const, continue, debugger, default, delete,
do, else, enum, export, extends, false, finally, for, function, if,
implements, import, in, instanceof, interface, let, new, null, package,
private, protected, public, return, static, super, switch, this,
throw, true, try, typeof, var, void, while, with, yield
Literals
Literals are fixed values:
// Number literals
42
3.14
0xFF // Hexadecimal
0b1010 // Binary
0o777 // Octal
// String literals
"Hello World"
'Hello World'
`Hello ${name}` // Template literal
// Boolean literals
true
false
// Object literal
{ name: "John", age: 30 }
// Array literal
[1, 2, 3, 4, 5]
// Regular expression literal
/pattern/flags
Next Steps
Now that you understand the basic syntax, let's explore variables and scope.