Hello, World! Your First JavaScript Program
Write your first JavaScript program: print Hello, World! with console.log and learn how strings, comments and statements work.
console.log("Hello, World!");The essential JavaScript syntax on one page. Every snippet comes from a lesson of our interactive Learn JavaScript course — click "Practise" to write it yourself and get instant feedback.
Last updated on .
Write your first JavaScript program: print Hello, World! with console.log and learn how strings, comments and statements work.
console.log("Hello, World!");Learn how to declare JavaScript variables with let and const, when to use each, and the basic data types: strings, numbers and booleans.
const heroName = "Ada";
let score = 0;
console.log(heroName); // Ada
console.log(score); // 0Do math in JavaScript: arithmetic operators, remainder with %, exponents, rounding with the Math object and the classic floating-point gotchas.
const gold = 150;
const price = 19.99;
console.log(typeof gold, typeof price); // number numberWork with JavaScript strings: template literals, length, indexes, slice, trim, toUpperCase, includes, repeat and other essential string methods.
const realm = "Scriptoria";
console.log(realm.length); // 10
console.log(realm[0]); // S
console.log(realm[3]); // i
console.log(realm.at(-1)); // a (negative indexes count from the end)Make decisions in JavaScript with if, else if and else, compare values with === and !==, combine conditions with && and ||, and spot truthy values.
console.log(5 > 3); // true
console.log(5 < 3); // false
console.log(5 >= 5); // true
console.log(4 <= 3); // false
console.log(5 === 5); // true (strictly equal)
console.log(5 !== 3); // true (strictly not equal)Repeat code with JavaScript for and while loops, use break and continue, loop over the characters of a string and avoid off-by-one errors.
for (let i = 1; i <= 3; i++) {
console.log(`Round ${i}`);
}
// Round 1
// Round 2
// Round 3Learn how JavaScript functions work: declare and call them, pass parameters, return values and give parameters default values.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Ada")); // Hello, Ada!
console.log(greet("Linus")); // Hello, Linus!Write shorter JavaScript functions with arrow syntax: implicit returns, parameters, function expressions and when arrow functions behave differently.
const add = function (a, b) {
return a + b;
};
console.log(add(2, 3)); // 5Understand JavaScript scope (global, function and block) and closures: functions that remember variables, used for counters and private state.
const realm = "Scriptoria"; // global
function enterTavern() {
const drink = "cider"; // function scope
if (realm === "Scriptoria") {
const song = "ballad"; // block scope
console.log(drink, song); // cider ballad
}
// console.log(song); // ReferenceError: song is not defined
}
enterTavern();
// console.log(drink); // ReferenceError: drink is not definedLearn JavaScript callbacks and higher-order functions: pass functions as arguments, call them later and build flexible, reusable helpers.
function levelUp(level, notify) {
const newLevel = level + 1;
notify(`You reached level ${newLevel}!`);
return newLevel;
}
levelUp(4, (message) => console.log(message));
// You reached level 5!
levelUp(9, (message) => console.log(`*** ${message.toUpperCase()} ***`));
// *** YOU REACHED LEVEL 10! ***Learn JavaScript arrays: indexes and length, push, pop, slice, includes and indexOf, and looping with for...of and forEach.
const party = ["Ada", "Linus", "Grace"];
console.log(party[0]); // Ada
console.log(party[2]); // Grace
console.log(party.length); // 3
console.log(party[3]); // undefined (no item there)
console.log(party.at(-1)); // Grace (negative indexes count from the end)Master JavaScript's map, filter and reduce: transform arrays, keep matching items, combine values into one result and chain them together.
const prices = [10, 25, 40];
const withTax = prices.map((price) => price * 1.2);
console.log(withTax); // [ 12, 30, 48 ]
const names = ["ada", "linus"];
console.log(names.map((name) => name.toUpperCase())); // [ 'ADA', 'LINUS' ]Search and order JavaScript arrays with find, findIndex, some, every and sort, including compare functions and the default sort trap.
const levels = [3, 18, 7, 25];
console.log(levels.find((level) => level > 10)); // 18
console.log(levels.find((level) => level > 99)); // undefinedUse the JavaScript spread operator to copy and merge arrays, rest parameters to accept any number of arguments, and destructuring to unpack values.
const warriors = ["Conan", "Xena"];
const mages = ["Merlin"];
const party = [...warriors, ...mages];
console.log(party); // [ 'Conan', 'Xena', 'Merlin' ]
const copy = [...warriors];
const withHealer = [...warriors, "Mercy"]; // add an item without mutating
console.log(warriors); // [ 'Conan', 'Xena' ] (unchanged)Learn JavaScript objects: create object literals, read and update properties with dot and bracket notation, write methods and understand this.
const hero = {
name: "Ada",
level: 7,
isOnline: true,
inventory: ["sword", "map"],
};Unpack JavaScript objects with destructuring, set default values, collect the rest, and copy or merge objects immutably with the spread operator.
const hero = { name: "Ada", level: 7, guild: "Coders" };
const { name, level } = hero;
console.log(name, level); // Ada 7Loop over JavaScript objects with Object.keys, values and entries, rebuild them with Object.fromEntries, and convert data with JSON.stringify and JSON.parse.
const stats = { str: 12, dex: 9, int: 15 };
console.log(Object.keys(stats)); // [ 'str', 'dex', 'int' ]
console.log(Object.values(stats)); // [ 12, 9, 15 ]
console.log(Object.entries(stats)); // [ [ 'str', 12 ], [ 'dex', 9 ], [ 'int', 15 ] ]Learn when to use JavaScript Map and Set instead of objects and arrays: unique values, fast lookups, any type of key and removing duplicates.
const visitors = new Set();
visitors.add("Ada");
visitors.add("Linus");
visitors.add("Ada"); // ignored: already in the set
console.log(visitors.size); // 2
console.log(visitors.has("Linus")); // true
visitors.delete("Linus");
console.log(visitors); // Set(1) { 'Ada' }Learn JavaScript classes: constructors, methods, class fields, private #fields, and getters and setters that validate and compute values.
class Monster {
constructor(name, hp) {
this.name = name;
this.hp = hp;
}
roar() {
return `${this.name} roars!`;
}
}
const goblin = new Monster("Goblin", 30);
const troll = new Monster("Troll", 120);
console.log(goblin.roar()); // Goblin roars!
console.log(troll.hp); // 120
console.log(goblin instanceof Monster); // trueReuse code with JavaScript class inheritance: extends, super(), overriding methods, calling parent methods with super, and static methods and fields.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
fetch() {
return `${this.name} fetches the stick!`;
}
}
const rex = new Dog("Rex");
console.log(rex.speak()); // Rex makes a sound. (inherited from Animal)
console.log(rex.fetch()); // Rex fetches the stick!
console.log(rex instanceof Dog, rex instanceof Animal); // true trueHandle JavaScript errors with try, catch and finally, throw your own errors, and create custom error classes by extending Error.
const hero = null;
console.log(hero.name); // TypeError: Cannot read properties of null (reading 'name')Understand the JavaScript event loop: the call stack, task queue and microtasks, and schedule code for later with setTimeout and setInterval.
console.log("Brewing potion...");
setTimeout(() => {
console.log("Potion ready!");
}, 1000);
console.log("Meanwhile, sharpening sword.");Learn JavaScript promises: create them with new Promise, handle results with then, catch and finally, chain async steps and handle errors.
function rollDice() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const roll = Math.floor(Math.random() * 6) + 1;
if (roll === 1) {
reject(new Error("Critical failure!"));
} else {
resolve(roll);
}
}, 500);
});
}Write clean asynchronous JavaScript with async/await, handle errors with try/catch, and run tasks in parallel with Promise.all and Promise.allSettled.
async function getAnswer() {
return 42;
}
getAnswer().then((value) => console.log(value)); // 42