Skip to main content

Javascript basics in 20 min


 











1. Variables

  • var, let, and const are used to declare variables.
    var x = 5; // Function-scoped (old way, use with caution) let y = 10; // Block-scoped (preferable) const z = 15; // Block-scoped, cannot be reassigned
  • const is used when you know the value won’t change.

2. Data Types

  • Primitive Types: string, number, boolean, null, undefined, symbol, bigint

    let name = "John"; // String let age = 25; // Number let isActive = true; // Boolean let data = null; // Null let notAssigned; // Undefined
  • Reference Types: Objects, Arrays, Functions.

    let person = { name: "John", age: 25 }; // Object let numbers = [1, 2, 3]; // Array

3. Functions

  • Functions can be declared and invoked:

    function greet(name) { return "Hello, " + name; } console.log(greet("Alice"));
  • Arrow Functions (ES6):

    const greet = (name) => "Hello, " + name; console.log(greet("Bob"));

4. Control Flow (if-else, switch)

  • If-else:

    let age = 18; if (age >= 18) { console.log("Adult"); } else { console.log("Minor"); }
  • Switch:

    let day = 3; switch (day) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; case 3: console.log("Wednesday"); break; default: console.log("Invalid day"); }

5. 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++; }
  • For...of loop (for iterating arrays):

    let arr = [10, 20, 30]; for (let num of arr) { console.log(num); }

6. Arrays and Objects

  • Arrays are ordered collections:

    let fruits = ["apple", "banana", "cherry"]; console.log(fruits[0]); // "apple"
  • Objects are key-value pairs:
    let person = { name: "John", age: 30 }; console.log(person.name); // "John"

7. Events (Browser-Specific)

  • JavaScript can interact with the DOM (Document Object Model) to handle events:

    document.getElementById("myButton").onclick = function() { alert("Button clicked!"); };

8. Array Methods

  • map (creates a new array by applying a function):

    let numbers = [1, 2, 3]; let doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6]
  • filter (creates a new array with values passing the test):

    let numbers = [1, 2, 3, 4]; let even = numbers.filter(num => num % 2 === 0); console.log(even); // [2, 4]

9. Error Handling (Try-Catch)

  • Try-Catch blocks are used for error handling:

    try { let result = riskyFunction(); } catch (error) { console.log("Error: " + error.message); }

10. ES6 Features

  • Template Literals (for string interpolation):

    let name = "John"; console.log(`Hello, ${name}!`);
  • Destructuring:

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

11. Promises and Async-Await (for Asynchronous Code)

  • Promise:

    let promise = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Success!"); } else { reject("Error!"); } }); promise.then(result => console.log(result)).catch(error => console.log(error));
  • Async-Await (modern approach to handling promises):

    async function fetchData() { let response = await fetch('https://api.example.com'); let data = await response.json(); console.log(data); } fetchData();

12. Object-Oriented Programming (OOP)

  • Classes:

    class Car { constructor(make, model) { this.make = make; this.model = model; } drive() { console.log(`${this.make} ${this.model} is driving`); } } const car = new Car("Toyota", "Corolla"); car.drive();





Comments

Popular posts from this blog

8 Mistakes Every Beginner Programmer Makes (and How to Avoid Them)

  Starting with programming can be exciting but also challenging. Every beginner makes mistakes—it's part of the learning process! However, knowing common pitfalls can help you improve faster. Here are eight mistakes every beginner programmer makes and how to avoid them. 1. Not Understanding the Problem Before Coding ❌ Mistake: Jumping straight into coding without fully understanding the problem can lead to messy, inefficient, or incorrect solutions. ✅ Solution: Take a step back and analyze the problem . Break it into smaller parts and think about the logic before writing any code. Use flowcharts, pseudocode, or even pen and paper to sketch out your solution. 📌 Example: Instead of diving into loops, first clarify what needs to be repeated and under what conditions. 2. Ignoring Error Messages ❌ Mistake: Many beginners panic when they see an error message and either ignore it or randomly change things to make the error disappear. ✅ Solution: Read the error message carefully —it of...

Understanding SQL Query Execution Order

When writing SQL queries, understanding the execution order is crucial for writing efficient and optimized code. Many beginners assume that queries execute in the order they are written, but in reality, SQL follows a specific sequence of execution. SQL Execution Order SQL queries run in the following order: 1️⃣ FROM + JOIN 2️⃣ WHERE 3️⃣ GROUP BY 4️⃣ HAVING 5️⃣ SELECT (including window functions) 6️⃣ ORDER BY 7️⃣ LIMIT Let’s break down each step with examples. 1. FROM + JOIN (Data Retrieval) The SQL engine first retrieves data from the specified table(s) and applies any JOIN operations. 🔹 Example: SELECT employees.name, departments.department_name FROM employees JOIN departments ON employees.department_id = departments.id; Here, the JOIN happens before any filtering ( WHERE ) or grouping ( GROUP BY ). 2. WHERE (Filtering Data) Once data is retrieved, the WHERE clause filters rows before aggregation occurs. 🔹 Example: SELECT * FROM employees WHERE salary > 50000 ; Thi...

Exploring the Latest AI Tools: Revolutionizing Productivity and Creativity

Artificial Intelligence (AI) continues to revolutionize various industries by providing powerful tools that enhance creativity, productivity, and efficiency. Here’s a curated list of the latest AI tools across different domains in 2024: Design Tools AI-powered design tools help streamline the creative process, making it easier to create stunning visuals, graphics, and branding materials. Autodraw – AI-assisted sketching tool. Flair AI – Generates high-quality product mockups. Booth AI – AI-driven photoshoot generator. Content Creation These tools assist in generating and enhancing content, from text to multimedia, making content production more efficient. Writesonic – AI-powered writing assistant for blogs and ads. Beautiful AI – Smart presentation design tool. Stocking AI – Generates realistic stock images. Clipdrop – Enhances and removes background from images. Steve AI – Converts text into animated videos. Tome – AI storytelling and presentation software. Murf AI – AI voic...