JavaScript Fundamentals and Advanced Concepts
Introduction to JavaScript
JavaScript (JS) is a versatile scripting language that runs in web browsers and environments like Node.js. Its widely used for client-side and server-side development due to its flexibility and integration capabilities.
Key Features of JavaScript
- Single-threaded: JS executes one task at a time, which simplifies concurrency management. HTML5 introduces Web Workers for multi-threaded operations, but DOM manipulation remains restricted to the main thread.
- ECMAScript Standard: JS adheres to the ECMAScript specification, maintained by Ecma International.
- Interpreted Language: JS is executed line-by-line, which simplifies development but may impact performance compared to compiled languages.
- Event-driven: Interaction with HTML is managed through events, enabling dynamic web applications.
- Weak Typing: Variables can hold any data type and can change type dynamically.
- Cross-platform: JS runs on any device with a compatible browser or runtime environment.
Execution Flow
- Syntax Parsing: The JS engine checks for syntax errors.
- Pre-compilation: Function and variable declarations are hoisted. Functions declared with function declarations are hoisted fully, while function expressions are not.
- Execution: Code is executed line by line after parsing and hoisting.
Example: Hoisting Behavior
// Function declaration is fully hoisted
sayHello(); // Outputs: Hello!
function sayHello() {
console.log('Hello!');
}
// Function expression is not hoisted
try {
greet(); // Throws error: greet is not a function
} catch (e) {
console.error(e);
}
const greet = function() {
console.log('Hi!');
};
Core Concepts
Data Types
JS supports primitive types (number, string, boolean, null, undefined, symbol) and reference types (objects, arrays, functions).
Variable Declarations
- var: Function-scoped, subject to hoisting.
- let: Block-scoped, avoids hoisting issues.
- const: Block-scoped and immutable reference.
Scope and Closures
Scope defines variable accessibility. Closures allow inner functions to access variables from outer scopes even after the outer function has completed execution.
Functions
Functions in JS are first-class citizens and can be assigned to variables, passed as arguments, and returned from other functions.
Objects and Prototypes
JS uses prototypes instead of classical inheritance. Each object has an internal link to another object called its prototype, enabling property and method sharing.
Asynchronous Programming
JS handles asynchronous operations using callbacks, promises, and async/await. Understanding the event loop, microtasks, and macrotasks is crucial for managing execution order.
Example: Promise-based Fetch
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Advanced Topics
Modules
ES6 introduced native module support, allowing code organization into reusable components using import and export.
Iterators and Generators
Iterators provide a way to access elements of a collection sequentially. Generators are functions that can be paused and resumed, allowing custom iteration logic.
Error Handling
Use try...catch to handle runtime errors and throw to raise custom exceptions.
Memory Management
JS uses automatic garbage collection to reclaim unused memory. Developers should be aware of memory leaks caused by unintended object retention.
Practical Examples
Dynamic Script Loading
function loadScript(url) {
const script = document.createElement('script');
script.src = url;
document.head.appendChild(script);
}
Phone Number Masking
function maskPhone(phone) {
return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}
console.log(maskPhone('13812345678')); // Outputs: 138****5678
Debugging Techniques
Use browser developer tools to inspect elements, monitor network activity, and debug JavaScript code. The console object provides methods for logging and timing execution.
Using Console for Timing
console.time('loop');
for (let i = 0; i < 1000000; i++) {}
console.timeEnd('loop');