Syntax Basics
Chapter 2 • Beginner
Understanding statements, variable naming, whitespace, and other basic JavaScript syntax.
Variable Declaration
Variables are containers for storing data values. In JavaScript, you can declare variables using var, let, or const.
var Declaration
var is the traditional way to declare variables in JavaScript:
var name = 'John';
var age = 25;
let Declaration
let is the modern way to declare variables that can be reassigned:
let name = 'John';
let age = 25;
const Declaration
const is used for variables that won't change:
const PI = 3.14159;
const companyName = 'Schoolabe';
Whitespace and Formatting
JavaScript is generally forgiving about whitespace, but good formatting makes your code more readable.
Indentation
Use consistent indentation (spaces or tabs) to show code structure:
function greetUser(name) {
if (name) {
console.log('Hello, ' + name + '!');
} else {
console.log('Hello, stranger!');
}
}
Comments
Comments help explain your code and are ignored by JavaScript:
// This is a single-line comment/* This is a multi-line comment */var name = 'John'; // Inline comment
Hands-on Examples
Variable Declaration Examples
// Using var
var firstName = 'John';
var lastName = 'Doe';
// Using let
let age = 25;
let city = 'New York';
// Using const
const PI = 3.14159;
const COMPANY_NAME = 'Schoolabe';
console.log(firstName, lastName);
console.log(age, city);
console.log(PI, COMPANY_NAME);This example shows the three ways to declare variables in JavaScript. var is function-scoped, let is block-scoped, and const creates a constant that cannot be reassigned.