JavaScript Basics
A comprehensive guide to modern JavaScript for React Native development
JavaScript Basics
Before diving into React Native, it's essential to have a solid understanding of JavaScript. This guide covers the fundamental and advanced concepts you'll use daily.
1. Modern Syntax (ES6+)
Modern JavaScript (ES6 and beyond) introduced features that make code cleaner and more readable.
Variables: let vs const
const: For values that won't be reassigned. This should be your default.let: For values that will change (e.g., a counter).
const appName = "MyCoolApp"; // Cannot be changed
let score = 0;
score = 10; // AllowedArrow Functions
Concise syntax for writing functions.
const add = (a, b) => a + b;Template Literals
Embed variables in strings using backticks.
const name = "Malik";
console.log(`Hello, ${name}!`);Destructuring
Extract values from arrays or objects.
const user = { name: "Malik", role: "Developer" };
const { name, role } = user;Spread and Rest Operators (...)
- Spread: Copy or merge objects/arrays.
const newUser = { ...oldUser, active: true }; - Rest: Gather arguments.
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
2. Array Methods
Functional programming is key in React.
map(): Transform elements (e.g., data to UI).filter(): Select elements.reduce(): Aggregate data.
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // [2, 4, 6]3. Asynchronous Programming
Promises & Async/Await
Handling API calls without blocking the UI.
const getUser = async () => {
try {
const response = await fetch('https://api.example.com/user');
if (!response.ok) throw new Error("Network response was not ok");
return await response.json();
} catch (error) {
console.error("Fetch failed:", error);
}
};4. Advanced Concepts
Error Handling
Robust apps handle errors gracefully.
try {
// Risky code
const result = riskyOperation();
} catch (error) {
// Fallback behavior
console.error("Something went wrong:", error.message);
} finally {
// Cleanup code (always runs)
console.log("Operation attempt finished.");
}JSON Handling
Communicating with APIs usually involves JSON.
JSON.stringify(obj): Converts a JS object to a JSON string.JSON.parse(string): Parses a JSON string back to a JS object.
[!WARNING]
JSON.parsewill throw an error if the string is malformed. Always wrap it in atry...catchblock.
Debugging with Console
Move beyond console.log.
console.warn("Warning message"): Yellow warning.console.error("Error message"): Red error trace.console.table(data): Displays arrays/objects in a neat table.
const users = [{ name: "A", age: 10 }, { name: "B", age: 20 }];
console.table(users);Data Storage Concepts
In web we use localStorage. In React Native, we uses AsyncStorage.
The concept is the same: Key-Value pairs stored as strings.
// Saving data
const saveUser = (user) => {
const jsonValue = JSON.stringify(user);
localStorage.setItem('user', jsonValue);
};
// Loading data
const loadUser = () => {
const jsonValue = localStorage.getItem('user');
return jsonValue != null ? JSON.parse(jsonValue) : null;
};5. Reading Code > Writing Code
With AI, you write less code, but you must read more. You need to recognize patterns.
| Pattern | Meaning |
|---|---|
const x = ... | Defining a variable (a container for data). |
if (x) { ... } | Logic. "Only do this if X is true". |
map(...) | Transforming a list. "Take these items and change them". |
function() { ... } | A recipe. "Here are the steps to do a task". |
Pro Tip: If you don't understand a block of code, highlight it in Cursor and press Cmd + K (or Cmd + L), then ask: "Explain this to me like I'm 5."
Summary Checklist
- Arrow Functions & Destructuring
- Async/Await patterns
- Error Handling (try/catch)
- JSON parsing/stringifying