JavaScript: Basic to Advanced

Jun 27, 2024

JavaScript: Basic to Advanced

Overview

Projects

  • Digital clock
  • Stopwatch
  • Calculator
  • Rock Paper Scissors game
  • Image slider
  • Weather app using API

JavaScript Basics

  • Definition: JavaScript is a programming language for dynamic and interactive web pages.
  • Environment: Runs on web browsers like Chrome, Safari, Edge, etc.
  • Functionality: Interactive responses to user actions, user input transformations.

Setting Up

Prerequisites

  • Knowledge in HTML and CSS recommended.

Tools

  • Text Editor: Suggested - VS Code.
  • Extension: Live Server for real-time view updates.

Basics

Creating Files

  1. Create a project folder.
  2. Needed files: index.html, style.css, index.js.
  3. Use ! + tab in VS Code to auto-generate HTML structure.
  4. Link CSS and JavaScript files within index.html.
    • CSS: <link rel="stylesheet" href="style.css">
    • JavaScript: <script src="index.js"></script>

Live Server Setup

  • Install Live Server extension in VS Code.
  • Right-click HTML file in VS Code > Open with Live Server.
  • Saves changes automatically update the web page.

Manipulating HTML with JavaScript

Basic Elements

  • Headers (H1): <h1>Hello</h1>
  • Paragraph: <p>Lorem ipsum...</p>

Styling Elements with CSS

  • Body Styling: body { font-family: Verdana; font-size: 2em; }
  • Styles Outside HTML: Linked via <link> tag in the <head> section.

JavaScript Basics

Output Methods

  • Console Log: console.log('Hello'); to check values in Developer Tools.
  • Alerts: window.alert('This is an alert'); for basic prompts.
  • Comments:
    • Single-line: // This is a comment.
    • Multi-line: /* This is a multi-line comment. */

Interactivity

Basic Structure

  • HTML: Elements to interact with.
  • JavaScript: Functions to manipulate HTML/CSS.

Example: Populating Text

  1. HTML: ID Attribute
    <h1 id="myH1"></h1>
    <p id="myP"></p>
    
  2. JavaScript: DOM Selection and Text Content
    document.getElementById('myH1').textContent = 'Hello';
    document.getElementById('myP').textContent = 'I like JavaScript!';
    

Key Topics

Variables

  • Definition: Containers storing values.
  • Declaration: let, const, var.
    • Example: let x = 100;
  • Types: Numbers, Strings, Booleans.
  • Data Types Length Check: typeof keyword.

Operators

  • Arithmetic: +, -, *, /, % (modulus).
  • Increment/Decrement: ++, --.
  • Assignment Operators: +=, -=, *=, /=, %= (augmented assignment).
  • Order of Operations: Follows math precedence (PEMDAS).

User Input

  • Prompt Method: window.prompt('Enter your age');

Type Conversion

  • Process: Changing one data type to another.
  • Common Uses: Number(), String(), Boolean()

Constants

  • Definition: Variables that cannot be changed once set.
  • Declaration: const PI = 3.14;

Basic JavaScript Functions Projects

  1. Counter Program
    • Use of buttons to increment, decrement, reset values.
  2. Math Operations
    • Use Math methods like Math.PI, Math.round(), Math.ceil(), etc.
  3. Random Number Generator
    • Using Math.random() method.
  4. If Statements
    • Conditional logic comparison.

Advanced JavaScript Sections

If Statements

  • Syntax:
    if (condition) {
        // code block
    } else if (condition) {
        // code block
    } else {
        // code block
    }
    
  • Logical Operators: &&, ||, !

Accepting User Input

  • Easy Way: Using window.prompt()
  • Professional Way: HTML forms with input fields and submitting via a button.

Other Key Topics

Functions

  • Function Declaration: function functionName(params) { // code }
  • Function Expression: const functionName = function(params) { // code }.
  • Arrow Functions: Shorter syntax.
    const greet = (name) => `Hello ${name}`;
    
  • Callbacks:
    • Definition: Functions passed as arguments.
    • Usage: Asynchronous operations (e.g., reading files).
  • Closures:
    • Definition: Function within another function. The inner function has access to the outer function scope.

HTML & CSS Series

Projects

  1. Digital Clock
  2. Stopwatch
  3. Calculator
  4. Rock Paper Scissors
  5. Image Slider
  6. Weather App

Advanced JavaScript Topics

Promises

  • Definition: Objects representing the eventual completion or failure of asynchronous operations.
  • States: Pending, Resolved, Rejected.
  • Syntax:
    let promise = new Promise((resolve, reject) => {
        // async code
        if (success) resolve('Success!');
        else reject('Failure!');
    });
    promise.then((value) => { // code }).catch((error) => { // code });
    

Async/Await

  • Async: Marks function as returning a promise.
  • Await: Pauses function execution until the promise is settled.
  • Syntax:
    async function example() {
        let result = await someAsyncOperation();
        console.log(result);
    }
    

Error Handling

  • Try-Catch: Handling runtime errors.
  • Syntax:
    try {
        // code
    } catch (error) {
        console.log(error);
    } finally {
        // cleanup code
    }
    

Weather App Project

APIs and JSON

Fetch API

  • Usage:
    fetch('https://api.weatherapi.com/data').then(response => response.json()).then(data => console.log(data));
    
  • Error Handling: Should include .catch() for handling errors.
  • Practical Application: Fetching data for the Weather App.

JSON Basics

  • Stringify: Converts object to JSON string.
  • Parse: Converts JSON string back to object.