Introduction to JavaScript
JavaScript (JS) is a dynamic, high-level, and interpreted programming language that adds interactivity to web pages. It is widely used for frontend and backend development.
1️⃣ What Can JavaScript Do?
✔ Manipulate HTML & CSS – Update page content dynamically.
✔ Handle Events – Respond to user actions like clicks or keypresses.
✔ Validate Forms – Ensure correct user input before submitting data.
✔ Work with APIs – Fetch and display data from servers.
✔ Create Animations – Add interactive motion to elements.
✔ Build Web Apps – Full-fledged applications with frameworks like React, Vue, and Angular.
2️⃣ Adding JavaScript to HTML
✅ Inline JavaScript (not recommended)
✅ Internal JavaScript (inside <script>
tags)
✅ External JavaScript (Best Practice)
Save the JavaScript in a separate file (script.js
) and link it in HTML.
🔹 Benefit: Keeps HTML clean and allows code reuse.
3️⃣ Variables in JavaScript
JavaScript uses three keywords for declaring variables:
Keyword | Scope | Can Reassign? | Can Redeclare? |
---|---|---|---|
var | Function-scoped | ✅ Yes | ✅ Yes |
let | Block-scoped | ✅ Yes | ❌ No |
const | Block-scoped | ❌ No | ❌ No |
✅ Example:
4️⃣ Data Types in JavaScript
Type | Example |
---|---|
String | "Hello" or 'World' |
Number | 42 , 3.14 |
Boolean | true , false |
Array | [1, 2, 3] |
Object | {name: "John", age: 25} |
Undefined | let a; (value not assigned) |
Null | let b = null; (empty value) |
🔹 typeof checks a variable’s type:
5️⃣ Operators in JavaScript
Operator | Example | Description |
---|---|---|
+ | 5 + 3 | Addition |
- | 5 - 3 | Subtraction |
* | 5 * 3 | Multiplication |
/ | 5 / 3 | Division |
% | 5 % 3 | Modulus (Remainder) |
++ | x++ | Increment |
-- | x-- | Decrement |
Comparison Operators
Operator | Example | Description |
---|---|---|
== | 5 == "5" | Equal (loose) |
=== | 5 === "5" | Equal (strict, checks type) |
!= | 5 != "5" | Not equal |
!== | 5 !== "5" | Not equal (strict) |
> | 5 > 3 | Greater than |
< | 5 < 3 | Less than |
6️⃣ Control Structures (if-else, loops)
✅ If-else statement
✅ For Loop
✅ While Loop
7️⃣ Functions in JavaScript
✅ Regular Function
✅ Arrow Function (ES6)
8️⃣ Arrays & Objects
✅ Arrays
✅ Objects
9️⃣ Event Handling (Click Event Example)
🔟 JavaScript in the Browser
✔ document.getElementById("id")
– Selects an element by ID.
✔ document.querySelector(".class")
– Selects the first element with the class.
✔ document.createElement("div")
– Creates a new HTML element.
✔ element.innerHTML
– Sets or gets HTML content.
✔ element.style.color = "red"
– Changes an element’s CSS.
🔹 Summary
✔ JavaScript is used for dynamic, interactive web pages.
✔ Variables are declared with var
, let
, or const
.
✔ Data types include strings, numbers, booleans, arrays, and objects.
✔ Operators perform arithmetic and logical operations.
✔ Control structures (if
, loops
) control program flow.
✔ Functions perform reusable actions.
✔ Events handle user interactions.
🚀 Want to explore more? Let me know!