JavaScript Basics
Learn the fundamentals of JavaScript programming
Introduction to JavaScript
JavaScript is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB, and Adobe Acrobat.
JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented, imperative, and declarative (e.g., functional programming) styles.
Adding JavaScript to HTML
JavaScript can be added to your HTML in several ways:
1. Inline JavaScript:
<button onclick="alert('Hello World!')">Click Me</button>
2. Internal JavaScript (using the script tag):
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello JavaScript!";
}
</script>
3. External JavaScript (linking to an external .js file):
<script src="script.js"></script>
It's generally best practice to place your JavaScript at the bottom of the body element or use the defer
attribute to ensure the HTML is fully loaded before the JavaScript runs.
Variables and Data Types
In JavaScript, you can declare variables using var
, let
, or const
:
// Using var (older way, function-scoped)
var name = "John";
// Using let (block-scoped, can be reassigned)
let age = 30;
// Using const (block-scoped, cannot be reassigned)
const PI = 3.14159;
JavaScript has several data types:
- String:
"Hello World"
or'Hello World'
- Number:
42
or3.14
- Boolean:
true
orfalse
- Undefined:
undefined
(a variable that has been declared but not assigned a value) - Null:
null
(represents the intentional absence of any object value) - Object:
{ name: "John", age: 30 }
- Array:
[1, 2, 3, 4]
(a special type of object) - Symbol: Used for creating unique identifiers
- BigInt: For integers larger than the Number type can handle
Operators
JavaScript includes various operators for performing operations on values.
Arithmetic Operators
let a = 10;
let b = 5;
// Addition
let sum = a + b; // 15
// Subtraction
let difference = a - b; // 5
// Multiplication
let product = a * b; // 50
// Division
let quotient = a / b; // 2
// Modulus (remainder)
let remainder = a % b; // 0
// Increment
a++; // a is now 11
// Decrement
b--; // b is now 4
// Exponentiation
let power = a ** 2; // 121 (11^2)
Comparison Operators
let x = 5;
let y = "5";
// Equal to (value only)
console.log(x == y); // true
// Equal to (value and type)
console.log(x === y); // false
// Not equal to (value only)
console.log(x != y); // false
// Not equal to (value and type)
console.log(x !== y); // true
// Greater than
console.log(x > 3); // true
// Less than
console.log(x < 10); // true
// Greater than or equal to
console.log(x >= 5); // true
// Less than or equal to
console.log(x <= 4); // false
Logical Operators
let isAdult = true;
let hasLicense = false;
// AND operator
console.log(isAdult && hasLicense); // false
// OR operator
console.log(isAdult || hasLicense); // true
// NOT operator
console.log(!isAdult); // false
Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
let age = 18;
// if statement
if (age >= 18) {
console.log("You are an adult");
}
// if-else statement
if (age >= 18) {
console.log("You are an adult");
} else {
console.log("You are a minor");
}
// if-else if-else statement
if (age < 13) {
console.log("You are a child");
} else if (age < 18) {
console.log("You are a teenager");
} else {
console.log("You are an adult");
}
// switch statement
let day = 2;
switch (day) {
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Another day");
}
Loops
Loops are used to execute a block of code multiple times.
// for loop
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// while loop
let i = 0;
while (i < 5) {
console.log(i); // 0, 1, 2, 3, 4
i++;
}
// do-while loop
let j = 0;
do {
console.log(j); // 0, 1, 2, 3, 4
j++;
} while (j < 5);
// for...of loop (for iterating over array values)
const numbers = [1, 2, 3, 4, 5];
for (const num of numbers) {
console.log(num); // 1, 2, 3, 4, 5
}
// for...in loop (for iterating over object properties)
const person = { name: "John", age: 30 };
for (const key in person) {
console.log(key + ": " + person[key]); // "name: John", "age: 30"
}
Functions
Functions are blocks of code designed to perform a particular task and are executed when "called".
// Function declaration
function greet(name) {
return "Hello, " + name + "!";
}
// Function expression
const sayHello = function(name) {
return "Hello, " + name + "!";
};
// Arrow function
const welcome = (name) => {
return "Welcome, " + name + "!";
};
// Simplified arrow function (for single expressions)
const goodbye = name => "Goodbye, " + name + "!";
// Calling functions
console.log(greet("John")); // "Hello, John!"
console.log(sayHello("Jane")); // "Hello, Jane!"
console.log(welcome("Bob")); // "Welcome, Bob!"
console.log(goodbye("Alice")); // "Goodbye, Alice!"
Objects
Objects are collections of key-value pairs and are used to store multiple values in a single variable.
// Creating an object
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
email: "john.doe@example.com",
// Method
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
// Accessing object properties
console.log(person.firstName); // "John"
console.log(person["lastName"]); // "Doe"
// Calling object methods
console.log(person.fullName()); // "John Doe"
// Adding new properties
person.address = "123 Main St";
// Deleting properties
delete person.email;
Arrays
Arrays are used to store multiple values in a single variable.
// Creating an array
const fruits = ["Apple", "Banana", "Orange", "Mango"];
// Accessing array elements
console.log(fruits[0]); // "Apple"
console.log(fruits[2]); // "Orange"
// Array length
console.log(fruits.length); // 4
// Adding elements to an array
fruits.push("Strawberry"); // Adds to the end
fruits.unshift("Pineapple"); // Adds to the beginning
// Removing elements from an array
fruits.pop(); // Removes from the end
fruits.shift(); // Removes from the beginning
// Finding elements
console.log(fruits.indexOf("Banana")); // 1
// Iterating over an array
fruits.forEach(function(fruit) {
console.log(fruit);
});
// Mapping an array
const upperFruits = fruits.map(function(fruit) {
return fruit.toUpperCase();
});
// Filtering an array
const longFruits = fruits.filter(function(fruit) {
return fruit.length > 5;
});
// Sorting an array
fruits.sort();
Best Practices
Here are some best practices to follow when writing JavaScript:
- Use
const
for variables that don't change, andlet
for variables that do - Avoid using
var
in modern JavaScript - Use strict equality (
===
) instead of loose equality (==
) - Use meaningful variable and function names
- Comment your code, but focus on why rather than what
- Keep functions small and focused on a single task
- Use arrow functions for short, simple functions
- Use template literals for string concatenation
- Use destructuring for cleaner code
- Handle errors with try/catch blocks
- Use modern ES6+ features when possible