MSDN Documentation

Your comprehensive resource for Microsoft technologies and beyond.

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.

JavaScript has several primitive data types:

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).

Control Flow

Control flow statements allow you to control the execution path of your code.


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.


// 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.


// 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 {
    // 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.

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.