JavaScript Code Examples: A Comprehensive Guide

JavaScript is a versatile programming language used primarily for web development. It allows you to create interactive websites, dynamic content, and powerful web applications. In this guide, we will explore various JavaScript code examples, from basic syntax to advanced concepts.

Table of Contents

  1. Basic JavaScript Syntax
  2. Variables and Data Types
  3. Control Structures
  4. Functions
  5. Arrays
  6. Objects
  7. DOM Manipulation
  8. Events
  9. Asynchronous Programming
  10. FAQs

Basic JavaScript Syntax

JavaScript code is written within <script> tags in an HTML file or linked externally. Here’s a simple example:

// Basic JavaScript Output
console.log("Hello, World!");

This code will output “Hello, World!” in the browser’s console.

Variables and Data Types

Variables are used to store data. JavaScript has three ways to declare variables: let, const, and var.

Let

let greeting = "Hello";
console.log(greeting); // Output: Hello

Const

const PI = 3.14159;
console.log(PI); // Output: 3.14159

Var

var name = "John";
console.log(name); // Output: John

Data Types

JavaScript has several data types, including:
String: Text
Number: Integers and decimals
Boolean: true or false
Null: Represents a null value
Undefined: Represents an undefined value
Object: A collection of key-value pairs
Array: A special type of object for storing multiple values

let str = "Hello"; // String
let num = 42; // Number
let bool = true; // Boolean
let nullVal = null; // Null
let undef = undefined; // Undefined

Control Structures

Control structures determine the flow of execution in a program.

If-Else Statement

let age = 18;
if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}
// Output: You are an adult.

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("Other day.");
}
// Output: Start of the week.

Loops

For Loop

for (let i = 0; i < 5; i++) {
  console.log(i); // Outputs 0,1,2,3,4
}

While Loop

let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}
// Outputs 0,1,2,3,4

Functions

Functions are reusable blocks of code.

Function Declaration

function addNumbers(a, b) {
  return a + b;
}
console.log(addNumbers(5, 3)); // Output: 8

Function Expression

const multiply = function(a, b) {
  return a * b;
};
console.log(multiply(4, 5)); // Output: 20

Arrow Function

const greet = (name) => {
  return "Hello, " + name;
};
console.log(greet("Alice")); // Output: Hello, Alice

Arrays

Arrays are used to store multiple values in a single variable.

Creating an Array

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

Array Methods

Push

fruits.push("date");
console.log(fruits); // Output: [ 'apple', 'banana', 'cherry', 'date' ]

Pop

fruits.pop();
console.log(fruits); // Output: [ 'apple', 'banana', 'cherry' ]

Map

let numbers = [1, 2, 3, 4];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [ 2, 4, 6, 8 ]

Filter

let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [ 2, 4 ]

Reduce

let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 10

Objects

Objects are used to store key-value pairs.

Creating an Object

let person = {
  name: "John",
  age: 30,
  occupation: "Engineer"
};
console.log(person); // Output: { name: 'John', age: 30, occupation: 'Engineer' }

Accessing Properties

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

Adding Properties

person.city = "New York";
console.log(person); // Output: { name: 'John', age: 30, occupation: 'Engineer', city: 'New York' }

DOM Manipulation

DOM manipulation allows you to interact with HTML elements.

Accessing Elements

let heading = document.getElementById("myHeading");
console.log(heading); // Outputs the heading element

Modifying Content

heading.textContent = "New Heading";

Changing Styles

heading.style.color = "red";

Adding Classes

heading.classList.add("highlight");

Events

Events are actions that happen in the browser.

Adding Event Listeners

let button = document.getElementById("myButton");

button.addEventListener("click", function() {
  console.log("Button clicked!");
});

Asynchronous Programming

Asynchronous programming allows you to perform tasks without blocking the main thread.

Callbacks

function processData(callback) {
  setTimeout(function() {
    callback("Data processed");
  }, 1000);
}

processData(function(result) {
  console.log(result); // Output: Data processed
});

Promises

function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Data fetched");
    }, 1000);
  });
}

getData().then(result => {
  console.log(result); // Output: Data fetched
});

Async/Await

async function fetchAsync() {
  try {
    let result = await getData();
    console.log(result); // Output: Data fetched
  } catch (error) {
    console.error(error);
  }
}

fetchAsync();

Fetch API

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

FAQs

1. What is the difference between let, const, and var?

  • let: Block-scoped, can be reassigned.
  • const: Block-scoped, cannot be reassigned.
  • var: Function-scoped, can be reassigned.

2. What is hoisting in JavaScript?

Hoisting is a behavior where variable and function declarations are moved to the top of their scope during compilation.

3. What is the difference between a function and an arrow function?

  • Functions: Have their own this context, can be used as constructors.
  • Arrow Functions: Use the this context of their surrounding scope, cannot be used as constructors.

4. How do I handle errors in JavaScript?

Use try...catch blocks to handle synchronous errors and Promise.catch() for asynchronous errors.

5. How do I work with APIs in JavaScript?

Use the fetch API or libraries like Axios to make HTTP requests.

Conclusion

JavaScript is a powerful language with a wide range of applications. By understanding the basics and practicing with code examples, you can become proficient in JavaScript and create dynamic web applications. Keep practicing and building projects to enhance your skills!

Index
Scroll to Top