Back To Home
Code Newb

Learn JavaScript!

Lesson 1: JavaScript Basics

1.1 Introduction to JavaScript

JavaScript is a versatile programming language used for web development, server-side programming, and even mobile app development. It is known for its ability to make web pages interactive.

1.2 Why Learn JavaScript?

  • Client-Side Scripting: JavaScript runs in the browser, making web pages dynamic and interactive.
  • Versatile: Used for front-end, back-end (Node.js), and mobile app development (React Native).
  • Large Community: Extensive libraries and frameworks like React, Angular, and Vue.js.
  • Beginner-Friendly: Easy to learn and widely supported.

1.3 Setting Up JavaScript

JavaScript can be run directly in the browser or using Node.js for server-side development.

Step 1: Running JavaScript in the Browser

  1. Open your browser's developer tools (F12).
  2. Go to the Console tab.
  3. Type the following code and press Enter:
  4. console.log("Hello, World!");

1.4 Variables and Data Types

JavaScript uses let, const, and var to declare variables.

let name = "Alice";
const age = 25;
var isStudent = true;

Data Types:

  • Number: Integers and decimals (e.g., 10, 3.14).
  • String: Text (e.g., "Hello").
  • Boolean: true or false.
  • Object: Key-value pairs (e.g., { name: "Alice", age: 25 }).
  • Array: Ordered lists (e.g., [1, 2, 3]).

1.5 Basic Operations

JavaScript supports basic mathematical operations:

let x = 10;
let y = 5;
console.log(x + y);  // Addition
console.log(x - y);  // Subtraction
console.log(x * y);  // Multiplication
console.log(x / y);  // Division

1.6 Coding Challenge: Simple Math Calculator

Task: Write a JavaScript program that asks the user for two numbers and prints their sum, difference, product, and quotient.

Example Output:

Enter first number: 8
Enter second number: 2
Sum: 10
Difference: 6
Product: 16
Quotient: 4

Use prompt() to get user input and console.log() to display the results.

Lesson 2: Control Flow in JavaScript

2.1 Conditional Statements (if, else if, else)

JavaScript uses if, else if, and else to make decisions.

let age = 18;

if (age < 18) {
    console.log("You are a minor.");
} else if (age === 18) {
    console.log("You just became an adult!");
} else {
    console.log("You are an adult.");
}

2.2 Logical Operators

JavaScript supports && (AND), || (OR), and ! (NOT).

let x = 10;

if (x > 0 && x < 20) {
    console.log("x is between 0 and 20.");
}

2.3 Loops

JavaScript has for, while, and do-while loops.

// For loop
for (let i = 0; i < 5; i++) {
    console.log(i);
}

// While loop
let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}

2.4 Loop Control Statements

Use break to exit a loop and continue to skip the current iteration.

for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;  // Exit the loop
    }
    console.log(i);
}

2.5 Coding Challenge: FizzBuzz

Write a program that prints numbers from 1 to 20 but:

Expected Output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
...

Lesson 3: Functions in JavaScript

3.1 Defining Functions

Functions are reusable blocks of code.

function greet(name) {
    console.log(`Hello, ${name}!`);
}

greet("Alice");  // Output: Hello, Alice!

3.2 Arrow Functions

Arrow functions provide a shorter syntax for writing functions.

const greet = (name) => {
    console.log(`Hello, ${name}!`);
};

greet("Bob");  // Output: Hello, Bob!

3.3 Function Scope

Variables declared inside a function are local to that function.

function myFunction() {
    let x = 10;  // Local variable
    console.log(x);
}

myFunction();  // Output: 10
console.log(x);  // Error: x is not defined

3.4 Coding Challenge: Even or Odd Checker

Write a function that:

Expected Output:

console.log(checkNumber(7));  // Output: Odd
console.log(checkNumber(10)); // Output: Even

Lesson 4: Arrays and Objects

4.1 Arrays

Arrays are ordered lists of values.

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

4.2 Array Methods

JavaScript provides many built-in methods for arrays.

fruits.push("orange");  // Adds "orange" to the end
fruits.pop();  // Removes the last element
fruits.forEach(fruit => console.log(fruit));  // Iterates over the array

4.3 Objects

Objects store key-value pairs.

let person = {
    name: "Alice",
    age: 25,
    isStudent: true
};

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

4.3 Coding Challenge: Find Unique Words

Write a function that:

Expected Output:

console.log(uniqueWords("Hello world hello"));  // Output: ["Hello", "world"]

Lesson 5: DOM Manipulation

5.1 What is the DOM?

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a document as a tree of objects.

5.2 Selecting Elements

Use document.querySelector() or document.getElementById() to select elements.

let heading = document.querySelector("h1");
console.log(heading.textContent);  // Output: The text inside the h1 element

5.3 Modifying Elements

You can change the content, style, and attributes of elements.

heading.textContent = "New Heading";
heading.style.color = "red";

5.4 Event Listeners

Event listeners allow you to respond to user actions.

let button = document.querySelector("button");
button.addEventListener("click", () => {
    console.log("Button clicked!");
});

5.5 Coding Challenge: Interactive To-Do List

Build a simple to-do list where users can:

Lesson 6: Asynchronous JavaScript

6.1 Callbacks

Callbacks are functions passed as arguments to other functions.

function fetchData(callback) {
    setTimeout(() => {
        callback("Data received!");
    }, 1000);
}

fetchData((data) => {
    console.log(data);  // Output: Data received!
});

6.2 Promises

Promises provide a cleaner way to handle asynchronous operations.

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Data received!");
        }, 1000);
    });
}

fetchData().then((data) => {
    console.log(data);  // Output: Data received!
});

6.3 Async/Await

async and await make asynchronous code look synchronous.

async function fetchData() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve("Data received!");
        }, 1000);
    });
}

async function main() {
    let data = await fetchData();
    console.log(data);  // Output: Data received!
}

main();

6.4 Coding Challenge: Fetch API Data

Use the Fetch API to retrieve data from a public API (e.g., JSONPlaceholder) and display it on the page.

Lesson 7: Error Handling

7.1 Try-Catch

Use try-catch to handle errors gracefully.

try {
    let x = y + 10;  // y is not defined
} catch (error) {
    console.log("An error occurred:", error.message);
}

7.2 Custom Errors

You can throw custom errors using throw.

function divide(a, b) {
    if (b === 0) {
        throw new Error("Cannot divide by zero!");
    }
    return a / b;
}

try {
    console.log(divide(10, 0));
} catch (error) {
    console.log(error.message);  // Output: Cannot divide by zero!
}

7.3 Coding Challenge: Safe Division

Write a function that:

Lesson 8: ES6+ Features

8.1 Let and Const

let and const provide block-scoped variables.

let x = 10;
const y = 20;

8.2 Template Literals

Template literals allow embedded expressions.

let name = "Alice";
console.log(`Hello, ${name}!`);  // Output: Hello, Alice!

8.3 Destructuring

Destructuring allows unpacking values from arrays or objects.

let [a, b] = [1, 2];
let { name, age } = { name: "Alice", age: 25 };

8.4 Coding Challenge: Object Destructuring

Write a function that:

Lesson 9: Modules and Import/Export

9.1 Exporting Modules

Use export to make functions or variables available to other modules.

// math.js
export function add(a, b) {
    return a + b;
}

9.2 Importing Modules

Use import to use functions or variables from other modules.

// main.js
import { add } from './math.js';

console.log(add(2, 3));  // Output: 5

9.3 Coding Challenge: Modular Calculator

Create a modular calculator that:

Lesson 10: Advanced JavaScript

10.1 Closures

Closures allow functions to retain access to their lexical scope.

function outer() {
    let x = 10;
    function inner() {
        console.log(x);
    }
    return inner;
}

let closure = outer();
closure();  // Output: 10

10.2 Prototypes and Inheritance

JavaScript uses prototypes for inheritance.

function Person(name) {
    this.name = name;
}

Person.prototype.greet = function() {
    console.log(`Hello, ${this.name}!`);
};

let person = new Person("Alice");
person.greet();  // Output: Hello, Alice!

10.3 Coding Challenge: Prototype Chain

Create a prototype chain where: