javascript-fundamentals
Core JavaScript language features, patterns, and best practices including ES6+ syntax, async/await, closures, prototypes, and modern development patterns
What this skill does
# JavaScript Fundamentals
A comprehensive guide to core JavaScript concepts, modern ES6+ features, asynchronous programming patterns, and industry best practices for building robust applications.
## When to Use This Skill
This skill is essential when:
- **Writing JavaScript Code**: Building web applications, Node.js backends, or any JavaScript-based project
- **Code Reviews**: Evaluating code quality, identifying anti-patterns, suggesting improvements
- **Teaching/Mentoring**: Explaining JavaScript concepts, debugging issues, pair programming
- **Refactoring Legacy Code**: Modernizing codebases with ES6+ features and better patterns
- **Architecture Design**: Choosing appropriate patterns and structures for your application
- **Performance Optimization**: Understanding memory management, event loops, and efficient patterns
- **Debugging**: Tracing execution flow, understanding scope chains, and async behavior
- **Interview Preparation**: Mastering fundamental concepts tested in technical interviews
## Core Concepts
### Variables and Scope
JavaScript has three ways to declare variables, each with different scoping rules:
**var**: Function-scoped, hoisted, can be redeclared
```javascript
function varExample() {
var x = 1;
if (true) {
var x = 2; // Same variable!
console.log(x); // 2
}
console.log(x); // 2
}
```
**let**: Block-scoped, not hoisted to usable state, cannot be redeclared
```javascript
function letExample() {
let x = 1;
if (true) {
let x = 2; // Different variable
console.log(x); // 2
}
console.log(x); // 1
}
```
**const**: Block-scoped, must be initialized, reference cannot be reassigned
```javascript
const PI = 3.14159;
// PI = 3; // Error: Assignment to constant variable
const user = { name: 'John' };
user.name = 'Jane'; // OK - modifying object properties
// user = {}; // Error - reassigning reference
```
**Best Practice**: Use `const` by default, `let` when reassignment is needed, avoid `var`.
### Data Types
JavaScript has 7 primitive types and objects:
**Primitives**:
- `String`: Text data
- `Number`: Integers and floating-point numbers
- `BigInt`: Arbitrary precision integers
- `Boolean`: true/false
- `undefined`: Uninitialized variable
- `null`: Intentional absence of value
- `Symbol`: Unique identifiers
**Objects**: Collections of key-value pairs, including arrays, functions, dates, etc.
```javascript
// Type checking
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (historical bug!)
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"
// Better array checking
Array.isArray([]) // true
Array.isArray({}) // false
// Null checking
value === null // true only for null
value == null // true for null AND undefined
```
### Functions
Functions are first-class citizens in JavaScript - they can be assigned to variables, passed as arguments, and returned from other functions.
**Function Declaration**:
```javascript
function greet(name) {
return `Hello, ${name}!`;
}
```
**Function Expression**:
```javascript
const greet = function(name) {
return `Hello, ${name}!`;
};
```
**Arrow Function** (ES6+):
```javascript
const greet = (name) => `Hello, ${name}!`;
// Multiple parameters
const add = (a, b) => a + b;
// Single parameter (parentheses optional)
const double = x => x * 2;
// Multiple statements (need braces and explicit return)
const complexFunction = (x, y) => {
const result = x + y;
return result * 2;
};
```
**Key Differences**:
- Arrow functions don't have their own `this` binding
- Arrow functions cannot be used as constructors
- Arrow functions don't have `arguments` object
- Function declarations are hoisted, expressions are not
### Objects and Arrays
**Object Creation**:
```javascript
// Object literal
const person = {
name: 'John',
age: 30,
greet() {
return `Hello, I'm ${this.name}`;
}
};
// Accessing properties
person.name // Dot notation
person['name'] // Bracket notation (dynamic keys)
// Adding/modifying properties
person.email = '[email protected]';
person.age = 31;
// Deleting properties
delete person.email;
```
**Array Methods**:
```javascript
const numbers = [1, 2, 3, 4, 5];
// Transformation
numbers.map(n => n * 2) // [2, 4, 6, 8, 10]
numbers.filter(n => n > 2) // [3, 4, 5]
numbers.reduce((sum, n) => sum + n, 0) // 15
// Iteration
numbers.forEach(n => console.log(n));
// Search
numbers.find(n => n > 3) // 4
numbers.findIndex(n => n > 3) // 3
numbers.includes(3) // true
// Mutation (modify original)
numbers.push(6) // Add to end
numbers.pop() // Remove from end
numbers.unshift(0) // Add to start
numbers.shift() // Remove from start
numbers.splice(2, 1) // Remove 1 item at index 2
// Non-mutating
numbers.slice(1, 3) // [2, 3]
numbers.concat([6, 7]) // [1, 2, 3, 4, 5, 6, 7]
[...numbers, 6, 7] // Spread operator
```
### Closures
A closure is a function that has access to variables in its outer (enclosing) lexical scope, even after the outer function has returned.
```javascript
function createCounter() {
let count = 0; // Private variable
return {
increment() {
return ++count;
},
decrement() {
return --count;
},
getCount() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount()); // 2
// count is not directly accessible
```
**Use Cases**:
- Data privacy/encapsulation
- Factory functions
- Event handlers
- Callbacks maintaining state
- Module pattern implementation
### Prototypes and Inheritance
JavaScript uses prototypal inheritance. Every object has an internal `[[Prototype]]` link to another object.
```javascript
// Constructor function
function Animal(name) {
this.name = name;
}
// Add method to prototype
Animal.prototype.speak = function() {
return `${this.name} makes a sound`;
};
const dog = new Animal('Dog');
console.log(dog.speak()); // "Dog makes a sound"
// Inheritance
function Dog(name, breed) {
Animal.call(this, name); // Call parent constructor
this.breed = breed;
}
// Set up prototype chain
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
return `${this.name} barks!`;
};
const myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog.speak()); // "Buddy makes a sound" (inherited)
console.log(myDog.bark()); // "Buddy barks!" (own method)
```
### Classes (ES6+)
Classes provide syntactic sugar over prototypal inheritance:
```javascript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
// Static method
static create(name) {
return new Animal(name);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // Call parent constructor
this.breed = breed;
}
speak() {
return `${super.speak()} - Woof!`;
}
// Getter
get info() {
return `${this.name} is a ${this.breed}`;
}
// Setter
set nickname(value) {
this._nickname = value;
}
}
const myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog.speak()); // "Buddy makes a sound - Woof!"
console.log(myDog.info); // "Buddy is a Golden Retriever"
myDog.nickname = 'Bud';
```
## Modern JavaScript (ES6+)
### Destructuring
Extract values from arrays or properties from objects:
```javascript
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
// Object destructuring
const user = { name: 'John', age: 3Related in frontend
angular-development
IncludedComprehensive Angular framework development covering components, directives, services, dependency injection, routing, and reactive programming based on official Angular documentation
nextjs-development
IncludedComprehensive Next.js development skill covering App Router, Server Components, data fetching, routing patterns, API routes, middleware, and full-stack Next.js applications
react-development
IncludedComprehensive React development with hooks, components, state management, context, effects, and performance optimization based on official React documentation
vuejs-development
IncludedComprehensive Vue.js development skill covering Composition API, reactivity system, components, directives, and modern Vue 3 patterns based on official Vue.js documentation
frontend-architecture
IncludedComponent architecture, design patterns, state management strategies, module systems, build tools, and scalable application structure
responsive-design
IncludedMobile-first responsive design covering fluid layouts, media queries, flexbox, grid, viewport units, and responsive images