JavaScript Code Examples: A Comprehensive Guide

JavaScript is a versatile and powerful programming language that powers the interactivity of websites and web applications. Whether you’re a beginner or an experienced developer, having a solid understanding of JavaScript is essential. In this article, we’ll explore various JavaScript code examples, covering a wide range of topics from basic syntax to advanced concepts.

Table of Contents

  1. Basic Syntax
  2. Control Structures
  3. Functions
  4. Arrays
  5. Objects
  6. DOM Manipulation
  7. Events
  8. AJAX
  9. Promises
  10. FAQs

Basic Syntax

Let’s start with some basic JavaScript syntax. Here are a few examples:

1. Outputting to the Console

// Output a message to the console
console.log("Hello, JavaScript!");

2. Variables and Data Types

// Declare a variable
let greeting = "Hello, World!";

// Output the variable
console.log(greeting);

3. Comments

// Single-line comment
/* Multi-line comment
This is a multi-line comment
*/

Control Structures

Control structures allow you to control the flow of your JavaScript code. Here are some examples:

1. If-Else Statement

let age = 18;

if (age >= 18) {
    console.log("You are eligible to vote!");
} else {
    console.log("You are not eligible to vote yet.");
}

2. Switch Statement

let day = "Monday";

switch (day) {
    case "Monday":
        console.log("Start of the week");
        break;
    case "Friday":
        console.log("End of the week");
        break;
    default:
        console.log("It's another day");
}

Functions

Functions are reusable blocks of code that perform a specific task. Here are some examples:

1. Function Declaration

function sayHello() {
    console.log("Hello, everyone!");
}

sayHello();

2. Function Expression

const multiply = function(a, b) {
    return a * b;
};

console.log(multiply(5, 3)); // Output: 15

Arrays

Arrays are used to store collections of data. Here are some examples:

1. Creating an Array

let fruits = ["apple", "banana", "orange"]; 
console.log(fruits); // Output: [ 'apple', 'banana', 'orange' ]

2. Array Methods

let numbers = [1, 2, 3, 4, 5];

// Add an element to the end
numbers.push(6);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]

// Remove the last element
numbers.pop();
console.log(numbers); // Output: [1, 2, 3, 4, 5]

Objects

Objects are used to store collections of data in key-value pairs. Here are some examples:

1. Creating an Object

let person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    isStudent: false
};

console.log(person.firstName); // Output: John

2. Object Methods

let car = {
    brand: "Toyota",
    model: "Corolla",
    year: 2020,
    start: function() {
        console.log("Car is starting");
    }
};

console.log(car.brand); // Output: Toyota
// Call the method
 car.start(); // Output: Car is starting

DOM Manipulation

DOM manipulation allows you to interact with and modify the content of a web page. Here are some examples:

1. Changing Text Content

// Get the element by ID
let heading = document.getElementById("myHeading");

// Change the text content
heading.textContent = "New Heading";

2. Adding Elements

// Create a new paragraph element
let newPara = document.createElement("p");

// Set the text content
newPara.textContent = "This is a new paragraph.");

// Get the body element
let body = document.body;

// Append the new paragraph to the body
body.appendChild(newPara);

Events

Events are actions that occur as a result of user interaction or browser actions. Here are some examples:

1. Click Event

// Get the element by ID
let button = document.getElementById("myButton");

// Add a click event listener
button.addEventListener("click", function() {
    console.log("Button clicked!");
});

2. Form Submission

// Get the form element
let form = document.getElementById("myForm");

// Add a submit event listener
form.addEventListener("submit", function(e) {
    e.preventDefault();
    console.log("Form submitted!");
});

AJAX

AJAX (Asynchronous JavaScript and XML) allows you to send and receive data from a server asynchronously. Here are some examples:

1. GET Request

let xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText);
    }
};

xhr.open("GET", "https://api.example.com/data", true);
xhr.send();

2. POST Request

let xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText);
    }
};

xhr.open("POST", "https://api.example.com/data", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("name=John&age=30");

Promises

Promises are used to handle asynchronous operations in a cleaner and more manageable way. Here are some examples:

1. Creating a Promise

let myPromise = new Promise(function(resolve, reject) {
    // Simulate an asynchronous operation
    setTimeout(function() {
        resolve("Success!");
    }, 1000);
});

myPromise.then(function(message) {
    console.log(message); // Output: Success!
});

2. Chaining Promises

function firstFunction() {
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve("First function executed");
        }, 1000);
    });
}

function secondFunction() {
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve("Second function executed");
        }, 1000);
    });
}

firstFunction().then(function(result) {
    console.log(result); // Output: First function executed
    return secondFunction();
}).then(function(result) {
    console.log(result); // Output: Second function executed
});

FAQs

1. What is JavaScript?

JavaScript is a programming language used to create interactive web pages, web applications, and dynamic user interfaces.

2. What can I do with JavaScript?

You can use JavaScript to add interactivity to websites, create dynamic content, manipulate the DOM, handle user interactions, perform AJAX requests, and much more.

3. How do I start learning JavaScript?

You can start by learning the basics of JavaScript syntax, control structures, functions, arrays, and objects. Practice by writing small scripts and gradually move to more complex projects.

4. What is the difference between let and var?

let is block-scoped, meaning it is only accessible within the block it is declared in. var is function-scoped and can be accessed throughout the entire function.

5. How do I handle errors in JavaScript?

You can use try...catch statements to catch and handle errors. Additionally, you can use the finally block to execute code regardless of whether an error occurred or not.

6. What is the purpose of async and await?

async and await are used to simplify working with promises and asynchronous operations. async functions return a promise, and await allows you to wait for a promise to resolve before continuing execution.

Conclusion

This article has provided you with a wide range of JavaScript code examples, covering various aspects of the language. By practicing these examples and experimenting with different scenarios, you can enhance your JavaScript skills and become a more confident developer. Happy coding!

Index
Scroll to Top