JavaScript Fundamentals
JavaScript is a versatile and powerful programming language that is essential for modern web development. It allows you to create dynamic and interactive content on websites, build complex web applications, and even develop server-side applications with Node.js.
This documentation provides a comprehensive overview of JavaScript fundamentals, covering the core concepts that every developer needs to understand.
Variables and Data Types
Variables are containers for storing data values. In JavaScript, you can declare variables using var
, let
, and const
.
var
: Declares a variable that is function-scoped or globally scoped. It can be re-declared and updated.let
: Declares a variable that is block-scoped. It can be updated but not re-declared within the same scope.const
: Declares a variable that is block-scoped and cannot be reassigned after initialization. It must be initialized when declared.
JavaScript has several primitive data types:
- String: Represents textual data (e.g.,
"Hello, World!"
). - Number: Represents numeric values, including integers and floating-point numbers (e.g.,
42
,3.14
). - Boolean: Represents truth values, either
true
orfalse
. - Null: Represents the intentional absence of any object value.
- Undefined: Represents a variable that has not been assigned a value.
- Symbol: A unique and immutable primitive value, often used as keys for object properties. (ES6+)
- BigInt: For integers with arbitrary precision. (ES2020+)
Non-primitive data types include Object, which can store collections of data and more complex entities.
let message = "Welcome to JavaScript!"; // String
const year = 2023; // Number
var isLearning = true; // Boolean
let nothing = null; // Null
let notDefined; // Undefined
console.log(message);
console.log(year);
console.log(isLearning);
console.log(nothing);
console.log(notDefined);
Operators
Operators are special symbols that perform operations on operands (values and variables).
- Arithmetic Operators:
+
,-
,*
,/
,%
(modulo),++
(increment),--
(decrement). - Assignment Operators:
=
,+=
,-=
,*=
,/=
,%=
. - Comparison Operators:
==
(equal value),===
(equal value and type),!=
,!==
,>
,<
,>=
,<=
. - Logical Operators:
&&
(AND),||
(OR),!
(NOT). - String Operators:
+
(concatenation).
Control Flow
Control flow statements allow you to control the execution path of your code.
- Conditional Statements:
if
,else if
,else
,switch
. - Loops:
for
,while
,do...while
,for...in
,for...of
.
let score = 85;
if (score >= 90) {
console.log("Excellent!");
} else if (score >= 75) {
console.log("Good job!");
} else {
console.log("Keep practicing.");
}
for (let i = 0; i < 5; i++) {
console.log(`Iteration: ${i}`);
}
Functions
Functions are reusable blocks of code that perform a specific task. They help in organizing code and reducing redundancy.
Functions can be defined using function declarations, function expressions, or arrow functions.
// Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function Expression
const multiply = function(a, b) {
return a * b;
};
// Arrow Function
const add = (x, y) => x + y;
console.log(greet("Alice"));
console.log(multiply(5, 4));
console.log(add(10, 20));
Objects
Objects are fundamental data structures in JavaScript. They are collections of properties, where each property is a key-value pair. Keys are typically strings, and values can be any data type, including other objects and functions.
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
isStudent: false,
address: {
street: "123 Main St",
city: "Anytown"
},
greet: function() {
return `Hello, my name is ${this.firstName} ${this.lastName}.`;
}
};
console.log(person.firstName); // John
console.log(person['age']); // 30
console.log(person.greet()); // Hello, my name is John Doe.
console.log(person.address.city); // Anytown
Arrays
Arrays are ordered lists of values. They are a special type of object in JavaScript.
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Apple
console.log(fruits.length); // 3
fruits.push("Date"); // Add to end
console.log(fruits); // ["Apple", "Banana", "Cherry", "Date"]
fruits.pop(); // Remove from end
console.log(fruits); // ["Apple", "Banana", "Cherry"]
fruits.forEach(fruit => {
console.log(`I like ${fruit}`);
});
Asynchronous JavaScript
Asynchronous JavaScript allows you to perform operations (like fetching data from a server) without blocking the main thread of execution. This keeps your application responsive.
- Callbacks: Functions passed as arguments to other functions, to be executed later.
- Promises: Objects representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
- Async/Await: Syntactic sugar built on top of Promises, providing a more synchronous-looking way to write asynchronous code.
// Example using Promises
function fetchData(url) {
return new Promise((resolve, reject) => {
setTimeout(() => { // Simulate network delay
if (url === "https://api.example.com/data") {
resolve({ data: "Sample data from API" });
} else {
reject(new Error("Failed to fetch data"));
}
}, 1000);
});
}
fetchData("https://api.example.com/data")
.then(result => console.log("Success:", result.data))
.catch(error => console.error("Error:", error.message));
// Example using Async/Await
async function processData() {
try {
const response = await fetchData("https://api.example.com/data");
console.log("Async/Await Success:", response.data);
} catch (error) {
console.error("Async/Await Error:", error.message);
}
}
processData();
DOM Manipulation
The Document Object Model (DOM) is a programming interface for HTML and XML documents. JavaScript can interact with the DOM to change the structure, style, and content of a web page dynamically.
- Selecting elements:
document.getElementById()
,document.querySelector()
,document.querySelectorAll()
. - Modifying elements:
.innerHTML
,.textContent
,.style
,.setAttribute()
. - Creating and appending elements:
document.createElement()
,.appendChild()
. - Event handling:
.addEventListener()
.
// Example: Changing text content and style
const heading = document.getElementById('introduction');
if (heading) {
heading.textContent = "Mastering JavaScript Fundamentals!";
heading.style.color = "var(--accent-color)";
}
// Example: Adding an event listener
const button = document.createElement('button');
button.textContent = "Click Me";
document.body.appendChild(button);
button.addEventListener('click', () => {
alert("Button clicked!");
});
Error Handling
Error handling is crucial for robust applications. JavaScript provides mechanisms to gracefully handle runtime errors.
try...catch...finally
: Allows you to test a block of code for errors and specify a response if an error occurs.throw
: Used to throw an exception (error).
try {
// Code that might throw an error
let result = 10 / 0;
if (!isFinite(result)) {
throw new Error("Division by zero is not allowed.");
}
console.log("Result:", result);
} catch (error) {
console.error("An error occurred:", error.message);
} finally {
console.log("This will always execute.");
}
Modules
Modules allow you to break down your JavaScript code into smaller, reusable pieces. This improves organization, maintainability, and prevents naming conflicts.
- ES Modules (
import
/export
): The standard way to handle modules in modern JavaScript. - CommonJS (
require
/module.exports
): Primarily used in Node.js environments.
Example (ES Modules):
mathUtils.js
export const PI = 3.14159;
export function square(x) {
return x * x;
}
main.js
import { PI, square } from './mathUtils.js';
console.log("Value of PI:", PI);
console.log("Square of 5:", square(5));
This section covers the foundational elements of JavaScript. As you progress, explore advanced topics like prototypes, closures, event loops, and web APIs.