programming / FIELD NOTE
JavaScript Basics
Updated 10 March 2024
JavaScript Fundamentals
JavaScript is a versatile programming language primarily used for web development. It enables interactive web pages and is an essential part of web applications.
Variables and Data Types
Primitive Types
- String: Textual data
- Number: Numeric values
- Boolean: True/False values
- Undefined: Variable declared but not assigned
- Null: Intentional absence of value
- Symbol: Unique identifiers
Reference Types
- Objects: Key-value pairs
- Arrays: Ordered collections
- Functions: Reusable code blocks
// Variables
let name = "John";
const age = 30;
var isStudent = true;
// Objects
const person = {
name: "John",
age: 30,
hobbies: ["reading", "coding"]
};
// Arrays
const numbers = [1, 2, 3, 4, 5];Functions
Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}Arrow Functions
const add = (a, b) => a + b;
const multiply = (x, y) => {
return x * y;
};Control Flow
Conditional Statements
// If-Else
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
// Ternary
const status = age >= 18 ? "Adult" : "Minor";Loops
// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While loop
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
// For...of (arrays)
for (const num of numbers) {
console.log(num);
}Error Handling
try {
// Code that might throw an error
const result = riskyOperation();
} catch (error) {
// Handle the error
console.error("Error occurred:", error);
} finally {
// Always execute
console.log("Cleanup");
}Best Practices
- Use
constby default,letwhen reassignment is needed - Use descriptive variable and function names
- Write modular, reusable code
- Add proper error handling
- Follow consistent code style