Learn JavaScript in 10 minutes
JavaScript is a high-level, interpreted programming language known for its versatility and widespread use in web development. This tutorial covers modern JavaScript (ES6+) features to help you quickly learn the language.
1. Writing Your First JavaScript Program
Let’s start with a simple program. Create a file named hello.js
and enter the following code:
console.log("Hello, World!");
Save the file and run the following command in the terminal or command line:
node hello.js
Or include it in an HTML file:
<script>
console.log("Hello, World!");
</script>
The output will be:
Hello, World!
This simple program demonstrates JavaScript’s basic output functionality. The console.log()
function is used to display text information in the console.
2. Basic Syntax
JavaScript’s syntax is similar to other C-style languages. It uses semicolons to end statements and curly braces {}
to define code blocks.
// This is a single-line comment
console.log("Hello, World!");
/*
This is a multi-line comment
spanning multiple lines.
*/
Basic syntax rules in JavaScript:
- Semicolons: Optional but recommended to end statements
- Comments: Single-line comments start with
//
, multi-line with/* */
- Case Sensitivity: JavaScript is case-sensitive
- Code Blocks: Defined by curly braces
{}
3. Variables and Data Types
In JavaScript, variables are declared using let
, const
, or var
. Modern JavaScript prefers let
and const
.
Variable declaration:
let name = "John"; // Mutable variable
const age = 25; // Immutable constant
var oldWay = "deprecated"; // Avoid using var
JavaScript’s main data types:
- Number:
42
,3.14
,-10
- String:
"hello"
,'world'
,`template`
- Boolean:
true
,false
- Undefined:
undefined
(variable declared but not assigned) - Null:
null
(intentional absence of value) - Object:
{key: "value"}
,[1, 2, 3]
- Symbol:
Symbol("description")
(ES6+) - BigInt:
1234567890123456789012345678901234567890n
(ES2020+)
3.1 Number Type
JavaScript uses 64-bit floating point numbers for all numeric values.
let integer = 42;
let float = 3.14159;
let scientific = 2.5e3; // 2500
let hex = 0xFF; // 255
let binary = 0b1010; // 10
let octal = 0o10; // 8
3.2 String Type
Strings can be created with single quotes, double quotes, or template literals.
let single = 'Single quote string';
let double = "Double quote string";
let template = `Template literal`;
// Template literals with interpolation
let name = "Alice";
let greeting = `Hello, ${name}!`; // "Hello, Alice!"
String operations:
let text = "JavaScript programming";
console.log(text.length); // String length: 21
console.log(text.toUpperCase()); // "JAVASCRIPT PROGRAMMING"
console.log(text.toLowerCase()); // "javascript programming"
console.log(text[0]); // First character: "J"
console.log(text.slice(0, 10)); // "JavaScript"
3.3 Boolean Type
Boolean type has two values: true
and false
.
let isActive = true;
let isComplete = false;
// Boolean operations
let result1 = true && false; // false
let result2 = true || false; // true
let result3 = !true; // false
3.4 Undefined and Null
undefined
means a variable has been declared but not assigned a value. null
is an intentional absence of any value.
let unassigned; // undefined
let empty = null;
if (unassigned === undefined) {
console.log("Variable is undefined");
}
if (empty === null) {
console.log("Value is null");
}
4. Data Structures
4.1 Array
Arrays are ordered, mutable collections of values.
let numbers = [1, 2, 3, 4, 5];
numbers.push(6); // Add element: [1, 2, 3, 4, 5, 6]
numbers.pop(); // Remove last: [1, 2, 3, 4, 5]
numbers.unshift(0); // Add to start: [0, 1, 2, 3, 4, 5]
numbers.shift(); // Remove first: [1, 2, 3, 4, 5]
numbers[0] = 10; // Modify: [10, 2, 3, 4, 5]
Array methods:
let fruits = ["apple", "banana", "orange"];
// Iteration
fruits.forEach(fruit => console.log(fruit));
// Transformation
let lengths = fruits.map(fruit => fruit.length); // [5, 6, 6]
// Filtering
let longFruits = fruits.filter(fruit => fruit.length > 5); // ["banana", "orange"]
// Finding
let hasApple = fruits.includes("apple"); // true
let bananaIndex = fruits.indexOf("banana"); // 1
4.2 Object
Objects are collections of key-value pairs.
let person = {
name: "John",
age: 30,
city: "New York",
isStudent: false
};
// Accessing properties
console.log(person.name); // "John"
console.log(person["age"]); // 30
// Adding properties
person.country = "USA";
person["occupation"] = "Developer";
// Removing properties
delete person.isStudent;
// Object methods
let keys = Object.keys(person); // ["name", "age", "city", "country", "occupation"]
let values = Object.values(person); // ["John", 30, "New York", "USA", "Developer"]
let entries = Object.entries(person); // [["name", "John"], ["age", 30], ...]
4.3 Set
Sets are collections of unique values.
let numbers = new Set([1, 2, 3, 3, 4, 4, 5]);
console.log(numbers); // Set {1, 2, 3, 4, 5}
// Set operations
numbers.add(6); // Add value
numbers.delete(1); // Remove value
numbers.has(2); // true
numbers.size; // 5
// Iterating
numbers.forEach(num => console.log(num));
4.4 Map
Maps are collections of key-value pairs with any data type as keys.
let map = new Map();
map.set("name", "Alice");
map.set(1, "number one");
map.set(true, "boolean true");
console.log(map.get("name")); // "Alice"
console.log(map.has(1)); // true
console.log(map.size); // 3
// Iterating
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
5. Operations and Operators
JavaScript provides various operators for computations and comparisons.
- Arithmetic:
+
,-
,*
,/
,%
,**
(exponentiation) - Comparison:
==
,===
,!=
,!==
,>
,<
,>=
,<=
- Logical:
&&
,||
,!
- Assignment:
=
,+=
,-=
,*=
,/=
,%=
- Ternary:
condition ? expr1 : expr2
5.1 Arithmetic Operators
let a = 10, b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.333...
console.log(a % b); // 1
console.log(a ** b); // 1000
5.2 Comparison Operators
let x = 5, y = 10;
console.log(x == y); // false
console.log(x === y); // false (strict equality)
console.log(x != y); // true
console.log(x !== y); // true (strict inequality)
console.log(x > y); // false
console.log(x < y); // true
console.log(x >= y); // false
console.log(x <= y); // true
5.3 Logical Operators
let a = true, b = false;
console.log(a && b); // false
console.log(a || b); // true
console.log(!a); // false
6. Control Flow
6.1 if Statements
let age = 20;
if (age >= 18) {
console.log("Adult");
} else if (age >= 13) {
console.log("Teen");
} else {
console.log("Child");
}
6.2 Switch Statement
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of week");
break;
case "Friday":
console.log("Weekend almost here");
break;
default:
console.log("Regular day");
}
6.3 for Loops
// Traditional for loop
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// for...of loop (arrays, strings)
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// for...in loop (object properties)
let person = {name: "John", age: 30};
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
6.4 while Loops
// while loop
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
// do...while loop
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
6.5 break and continue
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit loop
}
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // 1, 3
}
7. Functions
Functions are reusable blocks of code.
7.1 Function Declarations
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // "Hello, Alice!"
7.2 Function Expressions
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 5)); // 20
7.3 Arrow Functions (ES6+)
const add = (a, b) => a + b;
const square = x => x * x;
const greet = name => `Hello, ${name}!`;
console.log(add(2, 3)); // 5
console.log(square(4)); // 16
console.log(greet("Bob")); // "Hello, Bob!"
7.4 Default Parameters
function createUser(name, age = 18, isActive = true) {
return {name, age, isActive};
}
console.log(createUser("John")); // {name: "John", age: 18, isActive: true}
console.log(createUser("Alice", 25)); // {name: "Alice", age: 25, isActive: true}
7.5 Rest Parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
console.log(sum(5, 10, 15)); // 30
7.6 Spread Operator
let numbers = [1, 2, 3];
let moreNumbers = [4, 5, 6];
let allNumbers = [...numbers, ...moreNumbers]; // [1, 2, 3, 4, 5, 6]
let person = {name: "John", age: 30};
let updatedPerson = {...person, city: "New York"}; // {name: "John", age: 30, city: "New York"}
8. Classes and Objects (ES6+)
8.1 Class Declaration
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
return `I am ${this.name}, ${this.age} years old`;
}
haveBirthday() {
this.age++;
return `${this.name} had a birthday, now ${this.age} years old`;
}
}
let person = new Person("John", 25);
console.log(person.introduce()); // "I am John, 25 years old"
console.log(person.haveBirthday()); // "John had a birthday, now 26 years old"
8.2 Inheritance
class Animal {
constructor(name, species) {
this.name = name;
this.species = species;
}
makeSound() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name, "Dog");
this.breed = breed;
}
makeSound() {
return `${this.name} barks`;
}
fetch() {
return `${this.name} fetches the ball`;
}
}
let dog = new Dog("Buddy", "Golden Retriever");
console.log(dog.makeSound()); // "Buddy barks"
console.log(dog.fetch()); // "Buddy fetches the ball"
8.3 Getters and Setters
class Circle {
constructor(radius) {
this.radius = radius;
}
get diameter() {
return this.radius * 2;
}
set diameter(diameter) {
this.radius = diameter / 2;
}
get area() {
return Math.PI * this.radius ** 2;
}
}
let circle = new Circle(5);
console.log(circle.diameter); // 10
console.log(circle.area); // 78.53981633974483
circle.diameter = 20;
console.log(circle.radius); // 10
9. Asynchronous JavaScript
9.1 Callbacks
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
fetchData(data => {
console.log(data); // "Data received" after 1 second
});
9.2 Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
// reject("Error occurred");
}, 1000);
});
}
fetchData()
.then(data => console.log(data)) // "Data received"
.catch(error => console.error(error));
9.3 async/await (ES2017+)
async function getData() {
try {
let data = await fetchData();
console.log(data); // "Data received"
} catch (error) {
console.error(error);
}
}
getData();
9.4 Fetch API
async function getUser() {
try {
let response = await fetch('https://api.example.com/user');
let user = await response.json();
console.log(user);
} catch (error) {
console.error('Error:', error);
}
}
10. Error Handling
try {
let result = 10 / 0;
if (!isFinite(result)) {
throw new Error("Division by zero");
}
console.log(result);
} catch (error) {
console.error("Error:", error.message);
} finally {
console.log("This always runs");
}
11. Modules (ES6+)
11.1 Exporting
// math.js
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export default function multiply(a, b) {
return a * b;
}
11.2 Importing
// main.js
import multiply, { PI, add } from './math.js';
console.log(PI); // 3.14159
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
12. Modern JavaScript Features
12.1 Destructuring
// Array destructuring
let [first, second, third] = [1, 2, 3];
console.log(first, second, third); // 1 2 3
// Object destructuring
let {name, age} = {name: "John", age: 30, city: "NY"};
console.log(name, age); // John 30
// Function parameter destructuring
function greet({name, age}) {
return `Hello ${name}, you are ${age} years old`;
}
12.2 Template Literals
let name = "Alice";
let age = 25;
// Basic interpolation
let greeting = `Hello, ${name}!`;
// Multi-line strings
let message = `
Name: ${name}
Age: ${age}
Status: ${age >= 18 ? "Adult" : "Minor"}
`;
// Expression evaluation
let calculation = `2 + 3 = ${2 + 3}`; // "2 + 3 = 5"
12.3 Optional Chaining (?.)
let user = {
profile: {
name: "John",
address: {
city: "New York"
}
}
};
console.log(user?.profile?.name); // "John"
console.log(user?.profile?.age); // undefined
console.log(user?.profile?.address?.city); // "New York"
console.log(user?.employment?.company); // undefined (no error)
12.4 Nullish Coalescing (??)
let name = "";
let age = 0;
let city = null;
let country = undefined;
console.log(name || "Unknown"); // "Unknown" (empty string is falsy)
console.log(name ?? "Unknown"); // "" (only null/undefined)
console.log(age || 18); // 18 (0 is falsy)
console.log(age ?? 18); // 0 (only null/undefined)
console.log(city ?? "Unknown"); // "Unknown"
console.log(country ?? "USA"); // "USA"
13. Useful Array Methods
let numbers = [1, 2, 3, 4, 5];
// map: transform each element
let squares = numbers.map(n => n * n); // [1, 4, 9, 16, 25]
// filter: select elements
let evens = numbers.filter(n => n % 2 === 0); // [2, 4]
// reduce: accumulate values
let sum = numbers.reduce((total, n) => total + n, 0); // 15
// find: find first matching element
let firstEven = numbers.find(n => n % 2 === 0); // 2
// some: check if any element matches
let hasEven = numbers.some(n => n % 2 === 0); // true
// every: check if all elements match
let allPositive = numbers.every(n => n > 0); // true
// sort: sort elements
let sorted = numbers.sort((a, b) => b - a); // [5, 4, 3, 2, 1]
14. Date and Time
let now = new Date();
console.log(now.toString()); // Current date and time
console.log(now.getFullYear()); // Current year
console.log(now.getMonth()); // Current month (0-11)
console.log(now.getDate()); // Current day (1-31)
console.log(now.getHours()); // Current hour (0-23)
// Formatting dates
console.log(now.toLocaleDateString()); // Localized date string
console.log(now.toLocaleTimeString()); // Localized time string
console.log(now.toISOString()); // ISO format string
// Creating specific dates
let specificDate = new Date(2025, 0, 1); // January 1, 2025
let timestamp = new Date(1640995200000); // From timestamp
15. Regular Expressions
let text = "Hello, my email is [email protected] and phone is 123-456-7890";
// Email pattern
let emailPattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
let emails = text.match(emailPattern); // ["[email protected]"]
// Phone pattern
let phonePattern = /\d{3}-\d{3}-\d{4}/g;
let phones = text.match(phonePattern); // ["123-456-7890"]
// Test method
let isValidEmail = emailPattern.test("[email protected]"); // true
// Replace method
let maskedText = text.replace(phonePattern, "XXX-XXX-XXXX");
console.log(maskedText);
JavaScript is a powerful and versatile language that continues to evolve. This tutorial covers the essential concepts to get you started, but there’s much more to explore including advanced topics like generators, proxies, and web APIs.