GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR
← Back to Tutorials

🟡 JavaScript - Step by Step

Master the language of the web - from basic interactivity to complex DOM manipulation and asynchronous programming.

What is JavaScript?

JavaScript is a versatile, lightweight programming language primarily used to make web pages interactive. It runs in web browsers and can also run on servers using Node.js.

Key Features:

  • Client-side Scripting: Execute code in the browser
  • Interactive UI: Create responsive and interactive interfaces
  • Dynamic Content: Modify page content without reloading
  • Event Handling: Respond to user interactions
  • Full-Stack Development: Use with Node.js for backend

Getting Started

Adding JavaScript to HTML:

<!DOCTYPE html>
<html>
<head>
    <title>My Page</title>
</head>
<body>
    <h1>Hello, World!</h1>
    
    <!-- Inline JavaScript -->
    <script>
        console.log("Hello from JavaScript!");
    </script>
    
    <!-- Or external file -->
    <script src="script.js"></script>
</body>
</html>

Your First Program:

// Print to console
console.log("Hello, JavaScript!");

// Alert box
alert("Welcome to JavaScript!");

// Prompt user
let name = prompt("What is your name?");
console.log("Hello, " + name);

Variables & Data Types

// Variables
let age = 25;           // block scope, can be reassigned
const name = "John";    // block scope, cannot be reassigned
var city = "NYC";       // function scope (avoid using)

// Data Types
let num = 42;           // Number
let str = "Hello";      // String
let bool = true;        // Boolean
let arr = [1, 2, 3];   // Array
let obj = {name: "John", age: 25}; // Object
let undef;              // undefined
let empty = null;       // null

// Type checking
console.log(typeof num);    // "number"
console.log(typeof str);    // "string"

// String operations
let greeting = "Hello" + " " + "World";
let greeting2 = `Hello ${name}`; // Template literals

// Array operations
arr.push(4);            // Add element
arr.pop();              // Remove last element
let length = arr.length; // Get length

Functions

// Function declaration
function add(a, b) {
    return a + b;
}

console.log(add(5, 3)); // 8

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

// Arrow function (ES6)
const divide = (a, b) => a / b;
const greet = (name) => `Hello, ${name}!`;

// Default parameters
function introduce(name = "Guest") {
    console.log(`Hello, ${name}!`);
}

// Rest parameters
function sum(...numbers) {
    return numbers.reduce((a, b) => a + b, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

DOM Manipulation

Selecting Elements:

// By ID
const elem = document.getElementById("myId");

// By class
const elems = document.querySelectorAll(".myClass");

// By tag
const divs = document.getElementsByTagName("div");

// Modifying content
elem.textContent = "New text";
elem.innerHTML = "<strong>Bold text</strong>";

// Modifying attributes
elem.setAttribute("class", "new-class");
elem.style.color = "red";
elem.classList.add("active");
elem.classList.remove("inactive");

// Creating elements
const newDiv = document.createElement("div");
newDiv.textContent = "I'm new!";
document.body.appendChild(newDiv);

Events

// Event listeners
const button = document.getElementById("myBtn");

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

// Arrow function
button.addEventListener("click", () => {
    console.log("Button clicked again!");
});

// Mouse events
button.addEventListener("mouseover", () => {
    button.style.backgroundColor = "blue";
});

button.addEventListener("mouseout", () => {
    button.style.backgroundColor = "gray";
});

// Keyboard events
document.addEventListener("keydown", (event) => {
    console.log("Key pressed:", event.key);
});

// Form events
const form = document.getElementById("myForm");
form.addEventListener("submit", (event) => {
    event.preventDefault(); // Prevent page reload
    console.log("Form submitted!");
});

Async Programming

Promises:

// Creating a promise
const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Done!");
    }, 1000);
});

myPromise.then((result) => {
    console.log(result); // "Done!"
}).catch((error) => {
    console.log(error);
});

Async/Await:

async function getData() {
    try {
        const response = await fetch("https://api.example.com/data");
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.log("Error:", error);
    }
}

getData();

ES6+ Features

// Destructuring
const person = {name: "John", age: 30};
const {name, age} = person;

const arr = [1, 2, 3];
const [first, second] = arr;

// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

// Classes
class Animal {
    constructor(name) {
        this.name = name;
    }
    
    speak() {
        console.log(`${this.name} makes a sound`);
    }
}

class Dog extends Animal {
    speak() {
        console.log(`${this.name} barks`);
    }
}

// Template literals
const greeting = `Hello, ${name}!`;

// Map & filter
const nums = [1, 2, 3, 4];
const doubled = nums.map(n => n * 2);
const evens = nums.filter(n => n % 2 === 0);

APIs & Fetch

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

// Fetch with POST
fetch("https://api.example.com/users", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: "John",
        email: "john@example.com"
    })
})
.then(response => response.json())
.then(data => console.log(data));

// Async/await approach
async function getUsers() {
    const response = await fetch("https://api.example.com/users");
    const data = await response.json();
    return data;
}

Projects & Practice

Beginner Projects:

  • To-Do List App
  • Calculator
  • Weather Display (using API)
  • Quiz Application
  • Image Gallery

Intermediate Projects:

  • Real-time Chat
  • Note-taking App
  • Movie Database Browser
  • Expense Tracker
  • Kanban Board

Advanced Projects:

  • Single Page Application (SPA)
  • Social Media Clone
  • Real-time Collaboration Tool
  • Progressive Web App
  • Complex Web Game