JavaScript is a versatile programming language that powers dynamic web content. This guide introduces JavaScript fundamentals with practical examples.
Introduction
JavaScript is essential for web development, enabling interactivity and dynamic content. This article covers core concepts with examples.
Basic Syntax
Output
Use console.log()
to display messages:
console.log("Hello, JavaScript!"); // Outputs to console
Semicolons
Semicolons are optional but recommended for readability:
console.log("Hello"); // With semicolon
console.log("World"); // Without semicolon
Code Blocks
Blocks are defined by curly braces:
if (true) {
console.log("This is a block");
}
Variables and Data Types
Declaration
Use let
, const
, or var
:
let greeting = "Hello"; // Mutable
const PI = 3.14; // Immutable
var legacy = 2023; // Legacy
Data Types
Primitive types include string
, number
, boolean
, null
, undefined
, bigint
, and symbol
:
let str = "Hello"; // String
let num = 42; // Number
let bool = true; // Boolean
let n = null; // Null
let u = undefined; // Undefined
let big = 9007199254740991n; // BigInt
let sym = Symbol('id'); // Symbol
Control Structures
If-Else
Conditionally execute code:
let age = 18;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
Switch
Use switch
for multiple conditions:
let day = 'Monday';
switch (day) {
case 'Monday':
console.log("Start of week");
break;
case 'Friday':
console.log("End of week");
break;
default:
console.log("Other day");
}
Loops
For Loop
Repeat code a specific number of times:
for (let i = 0; i < 5; i++) {
console.log(i);
}
While Loop
Repeat while a condition is true:
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
Do-While Loop
Guarantees execution at least once:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Break and Continue
Control loop flow:
for (let i = 0; i < 10; i++) {
if (i === 5) break; // Exits loop
if (i % 2 === 0) continue; // Skips even numbers
console.log(i);
}
Functions
Declaration
Define reusable code blocks:
function greet(name) {
console.log("Hello, " + name);
}
greet("Alice");
Function Expression
Assign functions to variables:
const add = function(a, b) {
return a + b;
};
console.log(add(2, 3)); // Outputs 5
Return Values
Functions can return values:
function calculateArea(radius) {
return Math.PI * radius * radius;
}
console.log(calculateArea(2)); // Outputs ~12.566
Arrays
Creating Arrays
Store multiple values in a single variable:
let fruits = ['Apple', 'Banana', 'Cherry'];
let numbers = [1, 2, 3, 4, 5];
let mixed = ['Hello', 42, true];
Accessing Elements
Use index to access elements:
console.log(fruits[0]); // Outputs "Apple"
console.log(numbers[3]); // Outputs 4
Array Methods
Use built-in methods to manipulate arrays:
fruits.push('Date'); // Adds to end
fruits.pop(); // Removes last element
fruits.unshift('Strawberry'); // Adds to beginning
fruits.shift(); // Removes first element
let newFruits = fruits.slice(1, 3); // Creates a new array
let joined = fruits.join(', '); // Joins elements into a string
Objects
Creating Objects
Store key-value pairs:
let person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
hobbies: ['Reading', 'Hiking'],
greet: function() {
console.log("Hello! My name is " + this.firstName);
}
};
Accessing Properties
Access properties using dot notation or bracket notation:
console.log(person.firstName); // Outputs "John"
console.log(person['lastName']); // Outputs "Doe"
Methods
Objects can have methods:
person.greet(); // Outputs "Hello! My name is John"
Object Literals
Use shorthand for properties and methods:
let fullName = 'Alice Smith';
let person = {
fullName,
greet() {
console.log("Hello! My name is " + this.fullName);
}
};
person.greet(); // Outputs "Hello! My name is Alice Smith"
Events
Event Handling
JavaScript can respond to user actions:
// HTML
<button id="clickMe">Click Me</button>
// JavaScript
let button = document.getElementById('clickMe');
button.onclick = function() {
console.log("Button clicked");
};
Conclusion
This guide covered JavaScript basics, including syntax, variables, control structures, functions, arrays, objects, and events. Practice these concepts to master JavaScript.
FAQs
What is the difference between let
and var
?
let
declares variables with block scope, while var
uses function scope. Use let
for better scoping control.
Do I need to use semicolons in JavaScript?
Semicolons are optional, but using them improves readability and prevents potential errors.
How do I handle errors in JavaScript?
Use try...catch
to handle errors gracefully:
try {
// Code that might throw an error
} catch (error) {
// Handle the error
} finally {
// Optional: Code that runs regardless of error
}
What are arrow functions?
Arrow functions are a concise syntax for writing functions:
const greet = () => {
console.log("Hello, World!");
};
For single expressions, you can omit the curly braces:
const add = (a, b) => a + b;
How do I work with dates in JavaScript?
Use the Date
object to handle dates and times:
let now = new Date();
console.log(now.getFullYear()); // Outputs current year
console.log(now.getMonth()); // Outputs current month (0-11)
console.log(now.getDate()); // Outputs current day of the month