JavaScript Basics: Fundamentals for Modern Development
On this page
On this page
JavaScript is the programming language of the web, powering interactive websites and modern web applications. Whether you're building frontend interfaces or backend servers with Node.js, JavaScript is essential for modern development. This comprehensive guide covers JavaScript fundamentals with practical examples for beginners.
What is JavaScript?
JavaScript (JS) is a high-level, interpreted programming language that was created by Brendan Eich in 1995. Initially designed for web browsers, JavaScript has evolved into a versatile language used for:
- Frontend web development (React, Vue, Angular)
- Backend development (Node.js)
- Mobile app development (React Native)
- Desktop applications (Electron)
- Game development
JavaScript is the only programming language that runs natively in web browsers, making it essential for web development.
Setting Up JavaScript
You can run JavaScript in several ways:
- Browser Console: Open DevTools (F12) and use the Console tab
- Node.js: Install Node.js to run JavaScript on your computer
- HTML File: Embed JavaScript in HTML using
<script>tags
Running JavaScript in HTML:
<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<h1>Hello World</h1>
<script>
console.log("Hello from JavaScript!");
alert("Welcome to JavaScript!");
</script>
</body>
</html>Install Node.js: Download from nodejs.org to run JavaScript files from the command line.
Variables and Data Types
JavaScript has three ways to declare variables: var, let, and const. Modern JavaScript uses let and const.
Variables and data types:
// let - for variables that can be reassigned
let name = "JavaScript";
let age = 25;
let price = 19.99;
// const - for constants (cannot be reassigned)
const PI = 3.14159;
const API_URL = "https://api.example.com";
// Data Types
// Numbers
let integer = 42;
let float = 3.14;
let negative = -10;
// Strings
let singleQuote = 'Hello';
let doubleQuote = "World";
let templateLiteral = `Hello, ${name}!`; // ES6 template literals
// Booleans
let isActive = true;
let isComplete = false;
// Arrays
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "hello", true, null];
// Objects
let person = {
name: "John",
age: 30,
city: "New York",
isActive: true
};
// null and undefined
let empty = null; // Explicitly empty
let notDefined; // undefined (no value assigned)
// typeof operator
console.log(typeof name); // "string"
console.log(typeof age); // "number"
console.log(typeof isActive); // "boolean"
console.log(typeof person); // "object"
console.log(typeof notDefined); // "undefined"Operators
JavaScript operators:
// Arithmetic operators
let a = 10;
let b = 3;
console.log(a + b); // 13 (addition)
console.log(a - b); // 7 (subtraction)
console.log(a * b); // 30 (multiplication)
console.log(a / b); // 3.333... (division)
console.log(a % b); // 1 (modulus/remainder)
console.log(a ** b); // 1000 (exponentiation)
// Assignment operators
let x = 10;
x += 5; // x = x + 5 (15)
x -= 3; // x = x - 3 (12)
x *= 2; // x = x * 2 (24)
x /= 4; // x = x / 4 (6)
// Comparison operators
console.log(5 > 3); // true
console.log(5 < 3); // false
console.log(5 >= 5); // true
console.log(5 <= 3); // false
console.log(5 === 5); // true (strict equality)
console.log(5 !== 3); // true (strict inequality)
console.log(5 == "5"); // true (loose equality - avoid!)
console.log(5 === "5"); // false (strict equality - preferred)
// Logical operators
let isLoggedIn = true;
let hasPermission = false;
console.log(isLoggedIn && hasPermission); // false (AND)
console.log(isLoggedIn || hasPermission); // true (OR)
console.log(!isLoggedIn); // false (NOT)
// Ternary operator (conditional)
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"Control Structures
If-else statements:
// Basic if statement
let age = 18;
if (age >= 18) {
console.log("You are an adult");
}
// If-else
let temperature = 25;
if (temperature > 30) {
console.log("It's hot");
} else {
console.log("It's not too hot");
}
// If-else if-else
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
// Switch statement
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of work week");
break;
case "Friday":
console.log("TGIF!");
break;
default:
console.log("Regular day");
}Loops:
// For loop
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// For...of loop (arrays)
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// For...in loop (objects)
let person = { name: "John", age: 30 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
// While loop
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
// Do-while loop
let x = 0;
do {
console.log(x);
x++;
} while (x < 3);
// Array methods (modern approach)
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});Functions
Functions are reusable blocks of code. JavaScript supports multiple function declaration styles:
Function declarations:
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("JavaScript")); // "Hello, JavaScript!"
// Function expression
const add = function(a, b) {
return a + b;
};
console.log(add(3, 4)); // 7
// Arrow function (ES6) - modern and concise
const multiply = (a, b) => {
return a * b;
};
// Arrow function with single expression (implicit return)
const divide = (a, b) => a / b;
// Arrow function with single parameter
const square = x => x * x;
// Arrow function with no parameters
const sayHello = () => console.log("Hello!");
// Default parameters
function greetUser(name = "Guest") {
return `Hello, ${name}!`;
}
console.log(greetUser()); // "Hello, Guest!"
console.log(greetUser("John")); // "Hello, John!"
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10Working with Arrays
Arrays are fundamental in JavaScript. Here are essential array methods:
Array methods:
let fruits = ["apple", "banana", "orange"];
// Adding/removing elements
fruits.push("grape"); // Add to end
fruits.pop(); // Remove from end
fruits.unshift("kiwi"); // Add to beginning
fruits.shift(); // Remove from beginning
// Finding elements
let index = fruits.indexOf("banana"); // 1
let found = fruits.find(fruit => fruit.length > 5); // "orange"
// Transforming arrays
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]
let evens = numbers.filter(num => num % 2 === 0); // [2, 4]
let sum = numbers.reduce((acc, num) => acc + num, 0); // 15
// Checking arrays
let hasEven = numbers.some(num => num % 2 === 0); // true
let allPositive = numbers.every(num => num > 0); // true
// Array destructuring (ES6)
let [first, second, ...rest] = fruits;
console.log(first); // "apple"
console.log(rest); // ["orange"]Working with Objects
Object operations:
// Creating objects
let person = {
name: "John",
age: 30,
city: "New York",
greet: function() {
return `Hello, I'm ${this.name}`;
}
};
// Accessing properties
console.log(person.name); // "John"
console.log(person["age"]); // 30
console.log(person.greet()); // "Hello, I'm John"
// Adding/modifying properties
person.email = "john@example.com";
person.age = 31;
// Object destructuring (ES6)
let { name, age, city } = person;
console.log(name); // "John"
// Spread operator (ES6)
let updatedPerson = { ...person, age: 32, country: "USA" };
// Object methods
let keys = Object.keys(person); // ["name", "age", "city", "greet"]
let values = Object.values(person); // ["John", 30, "New York", function]
let entries = Object.entries(person); // [["name", "John"], ...]ES6+ Modern Features
ES6 (ES2015) introduced many modern features. Here are the most important ones:
ES6+ features:
// Template literals
let name = "JavaScript";
let message = `Hello, ${name}! Welcome to ES6.`;
// Arrow functions (already covered)
// Destructuring
let [a, b] = [1, 2];
let { x, y } = { x: 10, y: 20 };
// Spread operator
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// Classes
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
}
let john = new Person("John", 30);
console.log(john.greet());
// Promises
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Success!");
}, 1000);
});
promise.then(result => console.log(result));
// Async/await (ES2017)
async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
return data;
} catch (error) {
console.error("Error:", error);
}
}Learning Resources
Continue your JavaScript learning journey:
- W3Schools JavaScript: Comprehensive JavaScript tutorial
- FreeCodeCamp JavaScript: Free interactive JavaScript course
- MDN Web Docs: Official JavaScript documentation
- JavaScript.info: Modern JavaScript tutorial
Share Your Feedback
Your thoughts help me improve my content.