Introduction
Variables
Operators
Functions
DOM
Loops
Ethics
What is JavaScript?
- A programming language for the web that makes pages interactive
- Runs in the browser (client-side)
- Works with HTML and CSS to create dynamic websites
- Can also run on servers (Node.js)
Example Uses: Form validation, animations, dynamic content updates, AJAX requests
How to Add JavaScript?
1. Inline JavaScript (Inside HTML Tag)
JavaScript code written directly within HTML elements using event attributes:
<button class="hero-btn" onclick="alert('Hello!')">Click Me</button>
Characteristics:
- Best for small, single-use scripts
- Directly embedded in HTML elements
- Uses event attributes like
onclick
,onmouseover
, etc.
Note: While convenient for quick tests, inline JS mixes behavior with structure and is not recommended for production code.
2. Internal JavaScript (Inside <script> Tag)
JavaScript code placed within <script>
tags in the HTML document:
<script>
// This is internal JavaScript
document.write("Hello from internal JS!");
console.log("Message in console");
</script>
Best Practices:
- Typically placed just before the closing
</body>
tag for better performance - Can also be placed in
<head>
if needed early - All JavaScript for a single page is contained within the HTML file
Tip: Internal scripts are good for page-specific functionality but not reusable across multiple pages.
3. External JavaScript (Separate .js File)
JavaScript code stored in separate files and linked to HTML:
// In script.js file:
function showAlert() {
alert("This is from an external file!");
}
<!-- In HTML file -->
<script src="script.js"></script>
Advantages:
- Better code organization and separation of concerns
- Reusable across multiple pages
- Browser can cache the file for better performance
- Easier maintenance and collaboration
Recommendations:
- Place
<script>
tags before closing</body>
- Use the
defer
attribute if scripts must be in<head>
- For modern projects, this is the preferred method
Comparison Table
Method | Use Case | Pros | Cons |
---|---|---|---|
Inline | Quick tests, simple interactions | Fast to implement | Mixes HTML/JS, hard to maintain |
Internal | Page-specific scripts | No extra files needed | Not reusable, can slow rendering |
External | Production code, complex projects | Reusable, cacheable, organized | Extra HTTP request |
Modern Best Practice: For production websites, use external JavaScript files with
defer
or async
attributes for optimal loading performance.
Variables & Data Types
Variable Declaration:
let
- changeable value (block scope)const
- constant value (cannot be reassigned)var
- old way (avoid in modern JS, function scope)
Data Types:
- Number - integers or decimals (10, 3.14)
- String - text ("Hello")
- Boolean - true/false
- Array - list of values ([1, 2, 3])
- Object - key-value pairs ({name: "John"})
- null/undefined - special types
// Try changing these values!
let age = 20;
const name = "Alice";
var score = 95.5; // try to avoid var
let isStudent = true;
const colors = ["red", "green", "blue"];
const person = { firstName: "John", age: 30 };
// Display the values
displayOutput("name: " + name);
displayOutput("age: " + age);
displayOutput("isStudent: " + isStudent);
displayOutput("colors: " + colors);
displayOutput("person: " + JSON.stringify(person));
name: Alice
age: 20
isStudent: true
colors: red,green,blue
person: {"firstName":"John","age":30}
age: 20
isStudent: true
colors: red,green,blue
person: {"firstName":"John","age":30}
Operators & Conditions
Operators:
- Arithmetic: +, -, *, /, %, ** (exponent)
- Comparison: ==, ===, !=, !==, >, <, >=, <=
- Logical: && (AND), || (OR), ! (NOT)
Important: === checks value AND type ("5" == 5 is true, but "5" === 5 is false)
Conditional Statements:
let x = 10;
let y = "10";
// Arithmetic
displayOutput("x + 5 = " + (x + 5));
displayOutput("x * 2 = " + (x * 2));
// Comparison
displayOutput("x == y: " + (x == y)); // true (value)
displayOutput("x === y: " + (x === y)); // false (type)
// Logical
displayOutput("true && false: " + (true && false));
displayOutput("true || false: " + (true || false));
// If-else
if (x > 15) {
displayOutput("x is greater than 15");
} else if (x > 5) {
displayOutput("x is between 5 and 15");
} else {
displayOutput("x is 5 or less");
}
Functions
Functions are reusable blocks of code that perform specific tasks.
Function Types:
- Function Declaration:
function name() {}
- Function Expression:
const name = function() {}
- Arrow Function:
const name = () => {}
(ES6+)
// Function declaration
function greet(name) {
return "Hello, " + name + "!";
}
// Function expression
const add = function(a, b) {
return a + b;
};
// Arrow function
const square = x => x * x;
// Using the functions
displayOutput(greet("Coding Club"));
displayOutput("5 + 7 = " + add(5, 7));
displayOutput("Square of 4: " + square(4));
// Function with default parameter
function multiply(a, b = 1) {
return a * b;
}
displayOutput("Multiply (default): " + multiply(5));
DOM Manipulation
The Document Object Model (DOM) represents your webpage as a tree structure.
Selecting Elements:
document.getElementById("id")
document.querySelector(".class")
(first match)document.querySelectorAll("div")
(all matches)
Modifying Elements:
// Create a demo button class="hero-btn" if it doesn't exist
if (!document.getElementById('demoBtn')) {
const btn = document.createElement('button class="hero-btn"');
btn.id = 'demoBtn';
btn.textContent = 'DOM Demo button class="hero-btn"';
document.body.appendChild(btn);
}
// Get elements
const heading = document.querySelector('h1');
const demoBtn = document.getElementById('demoBtn');
const outputDiv = document.getElementById('dom-output');
// Change properties
heading.style.color = 'blue';
demoBtn.style.backgroundColor = '#ff9800';
demoBtn.style.padding = '10px 20px';
// Create new element
const newPara = document.createElement('p');
newPara.textContent = 'This paragraph was created with JavaScript!';
newPara.style.color = 'green';
document.body.appendChild(newPara);
// Event listener
demoBtn.addEventListener('click', function() {
outputDiv.innerHTML = 'button class="hero-btn" was clicked!';
this.style.backgroundColor = '#4CAF50';
});
Loops & Arrays
Loop Types:
for
- when you know how many iterationswhile
- when condition is unknownfor...of
- for arrays (ES6+)for...in
- for object properties
Array Methods:
push()
/pop()
- add/remove from endshift()
/unshift()
- add/remove from startforEach()
- execute function for each itemmap()
- transform array items
const fruits = ["Apple", "Banana", "Cherry"];
// For loop
displayOutput("For loop:");
for (let i = 0; i < fruits.length; i++) {
displayOutput(i + ": " + fruits[i]);
}
// While loop
displayOutput("\nWhile loop:");
let count = 0;
while (count < 2) {
displayOutput(fruits[count]);
count++;
}
// For...of loop (ES6)
displayOutput("\nFor...of loop:");
for (const fruit of fruits) {
displayOutput(fruit);
}
// Array methods
fruits.push("Mango");
displayOutput("\nAfter push: " + fruits);
const lengths = fruits.map(fruit => fruit.length);
displayOutput("Lengths: " + lengths);
fruits.forEach((fruit, index) => {
displayOutput(`${index}: ${fruit.toUpperCase()}`);
});
Professional Ethics in Coding
Why Ethics Matter:
- Privacy: Protect user data, don't collect unnecessary information
- Security: Write secure code to prevent vulnerabilities
- Honesty: Don't plagiarize, give credit for borrowed code
- Transparency: Be clear about what your code does
- Accessibility: Ensure your code works for all users
Best Practices:
- Always test your code thoroughly
- Follow the principle of least privilege
- Keep dependencies updated
- Document your code properly
- Respect open-source licenses
- Report security issues responsibly
Remember:
With great coding power comes great responsibility. Your code can impact millions of people - write it with care!
0 Comments