JavaScript Fundamentals
Variables and Data Types
1. Variable Declarations
// Modern variable declarations
let name = 'John'; // Block-scoped, mutable
const age = 30; // Block-scoped, immutable
var legacy = 'old'; // Function-scoped (avoid)
2. Primitive Data Types
// Numbers
const integer = 42;
const float = 3.14;
const scientific = 2.998e8;
// Strings
const single = 'Hello';
const double = 'World';
const template = `Hello ${name}`;
// Boolean
const isTrue = true;
const isFalse = false;
// Special Values
const empty = null;
const undefined_var = undefined;
3. Complex Data Types
// Arrays
const fruits = ['apple', 'banana', 'orange'];
// Objects
const person = {
name: 'John',
age: 30,
greet() {
return `Hello, I'm ${this.name}`;
},
};
Control Structures
1. Conditionals
// if-else
if (age >= 18) {
console.log('Adult');
} else {
console.log('Minor');
}
// switch
switch (fruit) {
case 'apple':
console.log('Selected apple');
break;
default:
console.log('Unknown fruit');
}
2. Loops
// for loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// for...of (arrays)
for (const fruit of fruits) {
console.log(fruit);
}
// for...in (objects)
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// while loop
let count = 0;
while (count < 5) {
console.log(count++);
}
Functions
1. Function Declarations
// Regular function
function greet(name) {
return `Hello, ${name}`;
}
// Arrow function
const greetArrow = (name) => `Hello, ${name}`;
// Function expression
const greetExpr = function (name) {
return `Hello, ${name}`;
};
2. Parameters and Arguments
// Default parameters
function multiply(a, b = 1) {
return a * b;
}
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Destructuring parameters
function printPerson({ name, age }) {
console.log(`${name} is ${age} years old`);
}
Error Handling
1. Try-Catch
try {
// Code that might throw an error
throw new Error('Something went wrong');
} catch (error) {
console.error(error.message);
} finally {
// Always executed
console.log('Cleanup');
}
2. Custom Errors
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
Best Practices
1. Code Style
- Use consistent indentation
- Follow naming conventions
- Keep functions small and focused
- Use meaningful variable names
2. Performance
- Avoid global variables
- Use appropriate data structures
- Optimize loops and conditions
- Minimize DOM manipulation
3. Debugging
- Use console methods effectively
- Implement proper error handling
- Write clear error messages
- Use debugging tools
Next Steps
- Explore Core Concepts for advanced features
- Learn about the JavaScript runtime environment
- Practice with coding exercises and projects