Dasar JavaScript - Memulai dengan JavaScript
JavaScript adalah bahasa pemrograman yang membuat website menjadi interaktif dan dinamis. Mari kita mulai dengan dasar-dasar JavaScript.
Apa itu JavaScript?
JavaScript adalah bahasa pemrograman high-level, interpreted, dan multi-paradigm yang digunakan untuk membuat website yang interaktif.
Keunggulan JavaScript
- Client-side: Berjalan di browser
- Server-side: Node.js untuk backend
- Versatile: Web, mobile, desktop apps
- Large Ecosystem: NPM dengan ribuan packages
- Modern: ES6+ features yang powerful
- Community: Komunitas yang besar dan aktif
Cara Menambahkan JavaScript
1. Inline JavaScript
1
|
<button onclick="alert('Hello World!')">Click Me</button>
|
2. Internal JavaScript
1
2
3
4
5
6
7
|
<head>
<script>
function greet() {
alert('Hello World!');
}
</script>
</head>
|
3. External JavaScript (Recommended)
1
2
3
|
<head>
<script src="script.js"></script>
</head>
|
Variables dan Data Types
1. Variable Declaration
1
2
3
4
5
6
7
8
|
// var (old way, not recommended)
var name = "John";
// let (block-scoped)
let age = 25;
// const (constant, cannot be reassigned)
const PI = 3.14159;
|
2. Data Types
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
// String
let name = "John Doe";
let message = 'Hello World';
// Number
let age = 25;
let price = 19.99;
// Boolean
let isStudent = true;
let isWorking = false;
// Undefined
let notDefined;
// Null
let empty = null;
// Object
let person = {
name: "John",
age: 25
};
// Array
let fruits = ["Apple", "Banana", "Orange"];
// Function
function greet() {
return "Hello!";
}
|
Operators
1. Arithmetic Operators
1
2
3
4
5
6
7
8
9
|
let a = 10;
let b = 5;
console.log(a + b); // 15 (Addition)
console.log(a - b); // 5 (Subtraction)
console.log(a * b); // 50 (Multiplication)
console.log(a / b); // 2 (Division)
console.log(a % b); // 0 (Modulus)
console.log(a ** b); // 100000 (Exponentiation)
|
2. Comparison Operators
1
2
3
4
5
6
7
8
9
|
let x = 5;
let y = "5";
console.log(x == y); // true (loose equality)
console.log(x === y); // false (strict equality)
console.log(x != y); // false
console.log(x !== y); // true
console.log(x > 3); // true
console.log(x <= 5); // true
|
3. Logical Operators
1
2
3
4
5
6
|
let isAdult = true;
let hasLicense = false;
console.log(isAdult && hasLicense); // false (AND)
console.log(isAdult || hasLicense); // true (OR)
console.log(!isAdult); // false (NOT)
|
Control Structures
1. Conditional Statements
1
2
3
4
5
6
7
8
9
10
11
12
|
let age = 18;
if (age >= 18) {
console.log("You are an adult");
} else if (age >= 13) {
console.log("You are a teenager");
} else {
console.log("You are a child");
}
// Ternary operator
let status = age >= 18 ? "adult" : "minor";
|
2. Loops
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// 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 (arrays)
let fruits = ["Apple", "Banana", "Orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// For...in loop (objects)
let person = { name: "John", age: 25 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
|
Functions
1. Function Declaration
1
2
3
4
5
|
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("John")); // Hello, John!
|
2. Function Expression
1
2
3
4
5
|
let greet = function(name) {
return "Hello, " + name + "!";
};
console.log(greet("John")); // Hello, John!
|
3. Arrow Functions (ES6)
1
2
3
4
5
6
7
8
|
let greet = (name) => {
return "Hello, " + name + "!";
};
// Shorter syntax
let greet = name => "Hello, " + name + "!";
console.log(greet("John")); // Hello, John!
|
4. Default Parameters
1
2
3
4
5
6
|
function greet(name = "Guest") {
return "Hello, " + name + "!";
}
console.log(greet()); // Hello, Guest!
console.log(greet("John")); // Hello, John!
|
Arrays
1. Array Methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
let fruits = ["Apple", "Banana", "Orange"];
// Adding elements
fruits.push("Mango"); // Add to end
fruits.unshift("Strawberry"); // Add to beginning
// Removing elements
fruits.pop(); // Remove from end
fruits.shift(); // Remove from beginning
// Finding elements
console.log(fruits.indexOf("Banana")); // 1
console.log(fruits.includes("Apple")); // true
// Array iteration
fruits.forEach(fruit => {
console.log(fruit);
});
// Map (creates new array)
let upperFruits = fruits.map(fruit => fruit.toUpperCase());
// Filter (creates new array)
let longFruits = fruits.filter(fruit => fruit.length > 5);
|
Objects
1. Object Creation
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// Object literal
let person = {
name: "John",
age: 25,
greet: function() {
return "Hello, I'm " + this.name;
}
};
// Accessing properties
console.log(person.name); // John
console.log(person["age"]); // 25
console.log(person.greet()); // Hello, I'm John
|
2. Object Methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
let person = {
name: "John",
age: 25,
// Method shorthand (ES6)
greet() {
return "Hello, I'm " + this.name;
},
// Arrow function (no 'this' binding)
sayAge: () => {
return "I'm " + person.age + " years old";
}
};
|
DOM Manipulation
1. Selecting Elements
1
2
3
4
5
6
7
8
9
10
11
12
|
// By ID
let element = document.getElementById("myId");
// By class
let elements = document.getElementsByClassName("myClass");
// By tag name
let paragraphs = document.getElementsByTagName("p");
// Query selector (CSS selector)
let element = document.querySelector(".myClass");
let elements = document.querySelectorAll(".myClass");
|
2. Modifying Elements
1
2
3
4
5
6
7
8
9
10
11
12
13
|
let element = document.getElementById("myElement");
// Changing content
element.innerHTML = "New content";
element.textContent = "New text";
// Changing attributes
element.setAttribute("class", "newClass");
element.className = "newClass";
// Changing styles
element.style.backgroundColor = "red";
element.style.fontSize = "20px";
|
3. Event Handling
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
let button = document.getElementById("myButton");
// Adding event listener
button.addEventListener("click", function() {
alert("Button clicked!");
});
// Arrow function
button.addEventListener("click", () => {
console.log("Button clicked!");
});
// Removing event listener
button.removeEventListener("click", handler);
|
Error Handling
1. Try-Catch
1
2
3
4
5
6
7
8
9
10
11
|
try {
// Code that might throw an error
let result = 10 / 0;
console.log(result);
} catch (error) {
// Handle the error
console.error("An error occurred:", error.message);
} finally {
// Code that always runs
console.log("This always executes");
}
|
2. Custom Errors
1
2
3
4
5
6
7
8
9
10
11
12
|
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
return a / b;
}
try {
let result = divide(10, 0);
} catch (error) {
console.error("Error:", error.message);
}
|
Next Steps
Di modul selanjutnya, kita akan mempelajari:
- ES6+ Features (Destructuring, Spread, Rest)
- Asynchronous JavaScript (Promises, async/await)
- AJAX dan Fetch API
- Local Storage dan Session Storage
- JavaScript Frameworks (React, Vue.js)
Mari lanjutkan ke modul berikutnya!