This content originally appeared on DEV Community and was authored by Fonyuy Gita
JavaScript Foundations for React-Native: From Zero to Confident Builder (Part 1)
Module 3, Part 1 of the Ultimate Road to React Native Mastery
Welcome to the heart of your React Native journey! If you've been wondering why your React Native apps feel confusing or why certain concepts seem to slip through your fingers, here's the truth: mastering modern JavaScript is the key that unlocks everything. Think of JavaScript as the engine of your car – without understanding how it works, you'll struggle to drive smoothly, diagnose problems, or build anything meaningful. In this comprehensive guide, we'll build rock-solid JavaScript foundations that will make your React Native development feel natural and intuitive, transforming you from a confused beginner into a confident builder.
Table of Contents
- Setting Up Your Learning Environment
- Variables: Your First Building Blocks
- Data Types: Understanding What You're Working With
- Operators: The Tools That Make Things Happen
- Control Flow: Making Decisions in Your Code
- Loops: Repeating Actions Efficiently
- Arrays: Organizing Your Data
- Practice Exercises
- Next Steps
Setting Up Your Learning Environment
Before we dive into JavaScript concepts, let's set up your workspace properly. Since this is part of our React Native series, we'll be working in a React Native environment, but I'll also show you how to test things in the browser first.
Prerequisites Check
If you haven't completed Part 1 of this series (Installation and Setup), please go back and ensure you have:
- Node.js installed
- React Native CLI or Expo CLI
- A code editor (VS Code recommended)
- Android Studio or Xcode (for device testing)
Creating Your Project Structure
Let's create a dedicated learning project. Open your terminal and run:
# Create a new React Native project for learning
npx react-native init JSFoundationsLearning
# Navigate to the project
cd JSFoundationsLearning
# Create our learning folders
mkdir src
mkdir src/01-variables
mkdir src/02-datatypes
mkdir src/03-operators
mkdir src/04-controlflow
mkdir src/05-loops
mkdir src/06-arrays
Think of this folder structure like organizing a toolbox – each drawer contains specific tools you'll need for different jobs.
Testing Your Setup
Let's make sure everything works. In your project root, create a simple test file:
// src/test.js
console.log("Hello, JavaScript learner!");
console.log("Your React Native environment is ready!");
To run this in React Native, we'll modify the main App.js file:
// App.js
import React from 'react';
import {View, Text} from 'react-native';
// Import your test file (this will run the console.log statements)
import './src/test.js';
const App = () => {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Check your terminal for JavaScript output!</Text>
</View>
);
};
export default App;
Run your app:
# For Android
npx react-native run-android
# For iOS
npx react-native run-ios
You should see the console messages in your terminal. This is where all your JavaScript learning will be visible!
Browser Testing Alternative
For quick testing, you can also use your browser's developer console:
- Open Chrome/Firefox
- Press F12 (or right-click → Inspect)
- Go to the Console tab
- Type JavaScript directly and press Enter
Both methods are valuable – browser for quick tests, React Native for real-world context.
Variables: Your First Building Blocks
Variables are like labeled boxes in your code – they store information you want to use later. Imagine you're organizing a library: instead of memorizing where every book is, you create a catalog with labels pointing to specific locations.
Understanding Variable Declaration
Create your first learning file:
// src/01-variables/variables.js
console.log("=== VARIABLES LESSON ===");
// Three ways to declare variables in modern JavaScript
let userName = "Alex";
const appName = "MyAwesomeApp";
var oldStyleVariable = "Don't use this much";
console.log("User name:", userName);
console.log("App name:", appName);
console.log("Old style:", oldStyleVariable);
Import this in your App.js:
// App.js
import React from 'react';
import {View, Text} from 'react-native';
// Import your variables lesson
import './src/01-variables/variables.js';
const App = () => {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Variables Lesson - Check Terminal!</Text>
</View>
);
};
export default App;
The Three Keywords: let, const, and var
Think of variable keywords like different types of storage containers:
const: Like a safety deposit box – once you put something in, it can't be changed.
let: Like a regular box – you can change what's inside, but the box stays in one place.
var: Like an old, unpredictable box – it can move around and cause confusion (avoid it).
// src/01-variables/keywords.js
console.log("=== VARIABLE KEYWORDS ===");
// const - Cannot be reassigned
const pi = 3.14159;
console.log("Pi value:", pi);
// This would cause an error:
// pi = 3.14; // TypeError: Assignment to constant variable
// let - Can be reassigned
let score = 100;
console.log("Initial score:", score);
score = 150; // This is fine
console.log("Updated score:", score);
// var - Old way, has weird behavior
var message = "Hello";
console.log("Message:", message);
var message = "Hi"; // This doesn't cause an error, but it's confusing
console.log("Changed message:", message);
Variable Naming Rules and Best Practices
Variable names are like street addresses – they need to be clear and follow certain rules:
// src/01-variables/naming.js
console.log("=== VARIABLE NAMING ===");
// Good naming practices
const firstName = "John"; // camelCase - recommended
const userAge = 25; // descriptive
const isLoggedIn = true; // boolean starts with 'is'
const MAX_RETRIES = 3; // constants in UPPER_CASE
// What NOT to do
// let 123abc = "bad"; // Can't start with number
// let user-name = "bad"; // Can't use hyphens
// let let = "bad"; // Can't use reserved words
console.log("First name:", firstName);
console.log("User age:", userAge);
console.log("Is logged in:", isLoggedIn);
console.log("Max retries:", MAX_RETRIES);
Exercise 1: Personal Information Storage
Create a file to practice variables:
// src/01-variables/exercise1.js
console.log("=== EXERCISE 1: Personal Information ===");
// Store your information in variables
const myName = "Your Name Here";
let myAge = 25;
let favoriteColor = "blue";
const birthYear = 1998;
// Display the information
console.log("Name:", myName);
console.log("Age:", myAge);
console.log("Favorite color:", favoriteColor);
console.log("Birth year:", birthYear);
// Try changing some values
myAge = 26; // This should work
favoriteColor = "green"; // This should work
console.log("Updated age:", myAge);
console.log("Updated favorite color:", favoriteColor);
// Challenge: Try to change myName or birthYear
// (This should cause an error because they're const)
📚 Reference: MDN Variables Guide
Data Types: Understanding What You're Working With
Data types are like different categories of information in your life – numbers, text, true/false decisions, and collections. Just as you handle money differently than you handle names, JavaScript treats different types of data in specific ways.
Primitive Data Types
// src/02-datatypes/primitives.js
console.log("=== PRIMITIVE DATA TYPES ===");
// String - Text information
const userName = "Jessica";
const message = 'Hello, world!';
const templateString = `Welcome, ${userName}!`;
console.log("String examples:");
console.log(userName);
console.log(message);
console.log(templateString);
// Number - Both integers and decimals
const age = 28;
const price = 19.99;
const negative = -5;
console.log("Number examples:");
console.log("Age:", age);
console.log("Price:", price);
console.log("Negative:", negative);
// Boolean - True or false
const isActive = true;
const isComplete = false;
console.log("Boolean examples:");
console.log("Is active:", isActive);
console.log("Is complete:", isComplete);
// Undefined - Variable declared but not assigned
let notAssigned;
console.log("Undefined example:", notAssigned);
// Null - Intentionally empty
const emptyValue = null;
console.log("Null example:", emptyValue);
Working with Strings
Strings are like sentences – they're made up of characters and have special behaviors:
// src/02-datatypes/strings.js
console.log("=== STRING OPERATIONS ===");
const firstName = "John";
const lastName = "Doe";
// String concatenation (joining strings)
const fullName = firstName + " " + lastName;
console.log("Full name:", fullName);
// Template literals (modern way)
const greeting = `Hello, ${firstName}! How are you?`;
console.log("Greeting:", greeting);
// String properties and methods
console.log("Name length:", fullName.length);
console.log("Uppercase:", fullName.toUpperCase());
console.log("Lowercase:", fullName.toLowerCase());
// String methods you'll use often
const email = " user@example.com ";
console.log("Original email:", email);
console.log("Trimmed email:", email.trim());
console.log("Includes @:", email.includes("@"));
Working with Numbers
Numbers in JavaScript are like a universal calculator – they can handle math operations:
// src/02-datatypes/numbers.js
console.log("=== NUMBER OPERATIONS ===");
const a = 10;
const b = 3;
// Basic math operations
console.log("Addition:", a + b);
console.log("Subtraction:", a - b);
console.log("Multiplication:", a * b);
console.log("Division:", a / b);
console.log("Remainder:", a % b);
// Special number methods
const decimal = 3.14159;
console.log("Rounded:", Math.round(decimal));
console.log("Rounded up:", Math.ceil(decimal));
console.log("Rounded down:", Math.floor(decimal));
// Converting strings to numbers
const userInput = "25";
const convertedNumber = Number(userInput);
console.log("Original:", userInput, "Type:", typeof userInput);
console.log("Converted:", convertedNumber, "Type:", typeof convertedNumber);
Type Checking
Sometimes you need to know what type of data you're working with:
// src/02-datatypes/typeof.js
console.log("=== TYPE CHECKING ===");
const examples = [
"Hello",
42,
true,
null,
undefined,
{ name: "John" },
[1, 2, 3]
];
// Check the type of each example
examples.forEach((example, index) => {
console.log(`Example ${index + 1}:`, example, "Type:", typeof example);
});
// Practical type checking
function checkUserInput(input) {
if (typeof input === 'string') {
console.log("Processing text:", input);
} else if (typeof input === 'number') {
console.log("Processing number:", input);
} else if (typeof input === 'boolean') {
console.log("Processing boolean:", input);
} else {
console.log("Unknown type:", typeof input);
}
}
checkUserInput("Hello");
checkUserInput(42);
checkUserInput(true);
Exercise 2: Data Type Practice
// src/02-datatypes/exercise2.js
console.log("=== EXERCISE 2: Data Types Practice ===");
// Create variables of different types
const movieTitle = "The Matrix";
const releaseYear = 1999;
const rating = 8.7;
const isClassic = true;
const director = null; // We'll assign this later
// Display information about the movie
console.log("Movie Information:");
console.log("Title:", movieTitle, "(Type:", typeof movieTitle + ")");
console.log("Release Year:", releaseYear, "(Type:", typeof releaseYear + ")");
console.log("Rating:", rating, "(Type:", typeof rating + ")");
console.log("Is Classic:", isClassic, "(Type:", typeof isClassic + ")");
console.log("Director:", director, "(Type:", typeof director + ")");
// String manipulation
const description = `${movieTitle} is a ${isClassic ? 'classic' : 'modern'} movie from ${releaseYear}`;
console.log("Description:", description);
// Number operations
const ageOfMovie = 2024 - releaseYear;
console.log("Age of movie:", ageOfMovie, "years");
// Challenge: Create a movie review summary
const reviewSummary = `"${movieTitle}" (${releaseYear}) - Rating: ${rating}/10`;
console.log("Review Summary:", reviewSummary);
📚 Reference: MDN Data Types
Operators: The Tools That Make Things Happen
Operators are like the verbs in your code – they make things happen. Just as you use different tools for different jobs (hammer for nails, screwdriver for screws), JavaScript has different operators for different operations.
Arithmetic Operators
// src/03-operators/arithmetic.js
console.log("=== ARITHMETIC OPERATORS ===");
const a = 15;
const b = 4;
// Basic arithmetic
console.log("Addition (a + b):", a + b); // 19
console.log("Subtraction (a - b):", a - b); // 11
console.log("Multiplication (a * b):", a * b); // 60
console.log("Division (a / b):", a / b); // 3.75
console.log("Remainder (a % b):", a % b); // 3
// Increment and decrement
let counter = 10;
console.log("Original counter:", counter);
counter++; // Same as counter = counter + 1
console.log("After increment:", counter);
counter--; // Same as counter = counter - 1
console.log("After decrement:", counter);
// Exponentiation (power)
console.log("2 to the power of 3:", 2 ** 3); // 8
Assignment Operators
Assignment operators are like shortcuts for common operations:
// src/03-operators/assignment.js
console.log("=== ASSIGNMENT OPERATORS ===");
let score = 100;
console.log("Initial score:", score);
// Basic assignment
score = 150;
console.log("New score:", score);
// Compound assignment operators
score += 50; // Same as: score = score + 50
console.log("After += 50:", score);
score -= 25; // Same as: score = score - 25
console.log("After -= 25:", score);
score *= 2; // Same as: score = score * 2
console.log("After *= 2:", score);
score /= 5; // Same as: score = score / 5
console.log("After /= 5:", score);
// String concatenation assignment
let message = "Hello";
message += " World"; // Same as: message = message + " World"
console.log("Message:", message);
Comparison Operators
Comparison operators help you make decisions by comparing values:
// src/03-operators/comparison.js
console.log("=== COMPARISON OPERATORS ===");
const age = 25;
const requiredAge = 18;
const userInput = "25";
// Equality comparisons
console.log("age == requiredAge:", age == requiredAge); // false
console.log("age === 25:", age === 25); // true
console.log("age == userInput:", age == userInput); // true (type coercion)
console.log("age === userInput:", age === userInput); // false (strict comparison)
// Inequality comparisons
console.log("age != requiredAge:", age != requiredAge); // true
console.log("age !== userInput:", age !== userInput); // true
// Relational comparisons
console.log("age > requiredAge:", age > requiredAge); // true
console.log("age < requiredAge:", age < requiredAge); // false
console.log("age >= 25:", age >= 25); // true
console.log("age <= 30:", age <= 30); // true
// Important difference between == and ===
console.log("'5' == 5:", '5' == 5); // true (converts string to number)
console.log("'5' === 5:", '5' === 5); // false (different types)
Logical Operators
Logical operators help you combine multiple conditions:
// src/03-operators/logical.js
console.log("=== LOGICAL OPERATORS ===");
const isLoggedIn = true;
const hasPermission = false;
const isAdmin = true;
const age = 25;
// AND operator (&&) - both conditions must be true
console.log("Logged in AND has permission:", isLoggedIn && hasPermission);
console.log("Logged in AND is admin:", isLoggedIn && isAdmin);
// OR operator (||) - at least one condition must be true
console.log("Has permission OR is admin:", hasPermission || isAdmin);
console.log("Age > 18 OR is admin:", age > 18 || isAdmin);
// NOT operator (!) - reverses the boolean value
console.log("NOT logged in:", !isLoggedIn);
console.log("NOT has permission:", !hasPermission);
// Practical examples
const canAccessAdminPanel = isLoggedIn && isAdmin;
const canViewContent = isLoggedIn || age > 18;
const needsLogin = !isLoggedIn;
console.log("Can access admin panel:", canAccessAdminPanel);
console.log("Can view content:", canViewContent);
console.log("Needs login:", needsLogin);
Exercise 3: Calculator Practice
// src/03-operators/exercise3.js
console.log("=== EXERCISE 3: Calculator Practice ===");
// Create a simple calculator
const num1 = 20;
const num2 = 8;
console.log("Calculator Input:");
console.log("First number:", num1);
console.log("Second number:", num2);
console.log("---");
// Perform all operations
console.log("Addition:", num1 + num2);
console.log("Subtraction:", num1 - num2);
console.log("Multiplication:", num1 * num2);
console.log("Division:", num1 / num2);
console.log("Remainder:", num1 % num2);
console.log("Power:", num1 ** num2);
// Comparison practice
console.log("---");
console.log("Comparison Results:");
console.log("num1 > num2:", num1 > num2);
console.log("num1 === num2:", num1 === num2);
console.log("num1 >= 20:", num1 >= 20);
// Logical operations
const isPositive1 = num1 > 0;
const isPositive2 = num2 > 0;
const isEven1 = num1 % 2 === 0;
const isEven2 = num2 % 2 === 0;
console.log("---");
console.log("Logical Results:");
console.log("Both numbers positive:", isPositive1 && isPositive2);
console.log("At least one even:", isEven1 || isEven2);
console.log("First number not even:", !isEven1);
📚 Reference: MDN Expressions and Operators
Control Flow: Making Decisions in Your Code
Control flow is like giving directions to your code – it determines which path your program takes based on different conditions. Think of it as traffic lights that guide cars through intersections.
If Statements
The if statement is like asking a question and doing something based on the answer:
// src/04-controlflow/if-statements.js
console.log("=== IF STATEMENTS ===");
const age = 20;
const hasLicense = true;
// Simple if statement
if (age >= 18) {
console.log("You are an adult!");
}
// If-else statement
if (hasLicense) {
console.log("You can drive!");
} else {
console.log("You need a license to drive.");
}
// If-else if-else chain
const score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else if (score >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
// Complex conditions
const isWeekend = true;
const weather = "sunny";
if (isWeekend && weather === "sunny") {
console.log("Perfect day for a picnic!");
} else if (isWeekend && weather === "rainy") {
console.log("Good day to stay inside and read.");
} else {
console.log("It's a regular day.");
}
Switch Statements
Switch statements are like a menu with multiple options – they're great when you have many possible values to check:
// src/04-controlflow/switch-statements.js
console.log("=== SWITCH STATEMENTS ===");
const dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
console.log("Monday - Start of the work week");
break;
case 2:
console.log("Tuesday - Getting into the groove");
break;
case 3:
console.log("Wednesday - Hump day!");
break;
case 4:
console.log("Thursday - Almost there");
break;
case 5:
console.log("Friday - TGIF!");
break;
case 6:
case 7:
console.log("Weekend - Time to relax!");
break;
default:
console.log("Invalid day");
}
// Switch with strings
const userRole = "admin";
switch (userRole) {
case "admin":
console.log("Full access granted");
break;
case "moderator":
console.log("Limited administrative access");
break;
case "user":
console.log("Standard user access");
break;
default:
console.log("Unknown role");
}
Ternary Operator
The ternary operator is like a shortcut for simple if-else statements:
// src/04-controlflow/ternary.js
console.log("=== TERNARY OPERATOR ===");
const temperature = 25;
// Instead of:
// if (temperature > 20) {
// console.log("It's warm");
// } else {
// console.log("It's cool");
// }
// You can write:
const weatherDescription = temperature > 20 ? "It's warm" : "It's cool";
console.log(weatherDescription);
// Multiple ternary operators
const age = 17;
const status = age >= 18 ? "adult" : age >= 13 ? "teenager" : "child";
console.log("Status:", status);
// Practical example
const isLoggedIn = true;
const username = "john_doe";
const greeting = isLoggedIn ? `Welcome back, ${username}!` : "Please log in";
console.log(greeting);
Exercise 4: User Authentication System
// src/04-controlflow/exercise4.js
console.log("=== EXERCISE 4: User Authentication System ===");
// Simulate user data
const username = "john_doe";
const password = "secret123";
const userRole = "admin";
const isAccountActive = true;
// Authentication check
console.log("Authentication System");
console.log("---");
if (username === "john_doe" && password === "secret123") {
console.log("✅ Username and password correct");
if (isAccountActive) {
console.log("✅ Account is active");
// Check user role and grant appropriate access
switch (userRole) {
case "admin":
console.log("🔑 Admin access granted - Full control");
break;
case "moderator":
console.log("🔑 Moderator access granted - Limited control");
break;
case "user":
console.log("🔑 User access granted - Standard features");
break;
default:
console.log("❌ Unknown role - Access denied");
}
} else {
console.log("❌ Account is inactive - Contact administrator");
}
} else {
console.log("❌ Invalid username or password");
}
// Bonus: Age verification system
const userAge = 20;
const hasParentalConsent = false;
const accessLevel = userAge >= 18 ? "full" : hasParentalConsent ? "limited" : "restricted";
console.log("---");
console.log("Age verification result:", accessLevel);
📚 Reference: MDN Control Flow
Loops: Repeating Actions Efficiently
Loops are like giving your code the ability to repeat tasks without writing the same code multiple times. Think of them as assembly lines that process items one by one, or like a recipe that says "stir until smooth" – they keep going until a condition is met.
For Loops
For loops are like counting systems – they're perfect when you know how many times you want to repeat something:
// src/05-loops/for-loops.js
console.log("=== FOR LOOPS ===");
// Basic for loop structure
console.log("Counting from 1 to 5:");
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
// Counting backwards
console.log("Countdown:");
for (let i = 5; i >= 1; i--) {
console.log("T-minus", i);
}
console.log("Blast off! 🚀");
// Skip counting
console.log("Even numbers from 2 to 10:");
for (let i = 2; i <= 10; i += 2) {
console.log("Even number:", i);
}
// Practical example: Processing a list
const fruits = ["apple", "banana", "orange", "grape"];
console.log("Fruits in my basket:");
for (let i = 0; i < fruits.length; i++) {
console.log(`${i + 1}. ${fruits[i]}`);
}
While Loops
While loops are like asking "Are we there yet?" – they keep going as long as a condition is true:
// src/05-loops/while-loops.js
console.log("=== WHILE LOOPS ===");
// Basic while loop
let count = 1;
console.log("Counting with while loop:");
while (count <= 5) {
console.log("Count:", count);
count++; // Don't forget to increment!
}
// Practical example: Finding a number
let number = 1;
console.log("Finding first number divisible by 7:");
while (number % 7 !== 0) {
number++;
}
console.log("Found:", number);
// Do-while loop (executes at least once)
let userInput;
let attempts = 0;
console.log("Password validation simulation:");
do {
attempts++;
userInput = attempts === 1 ? "wrong" : attempts === 2 ? "also wrong" : "correct";
console.log(`Attempt ${attempts}: ${userInput}`);
} while (userInput !== "correct" && attempts < 3);
if (userInput === "correct") {
console.log("Access granted!");
} else {
console.log("Too many attempts. Account locked.");
}
For...of Loops
For...of loops are like having a personal assistant that hands you items one by one:
// src/05-loops/for-of-loops.js
console.log("=== FOR...OF LOOPS ===");
// Iterating over arrays
const colors = ["red", "green", "blue", "yellow"];
console.log("Colors in my palette:");
for (const color of colors) {
console.log("Color:", color);
}
// Iterating over strings
const word = "JavaScript";
console.log("Letters in 'JavaScript':");
for (const letter of word) {
console.log("Letter:", letter);
}
// Practical example: Shopping cart
const shoppingCart = ["laptop", "mouse", "keyboard", "monitor"];
let totalItems = 0;
console.log("Processing shopping cart:");
for (const item of shoppingCart) {
totalItems++;
console.log(`Processing item ${totalItems}: ${item}`);
}
console.log(`Total items processed: ${totalItems}`);
Loop Control: Break and Continue
Sometimes you need to skip items or stop early:
// src/05-loops/loop-control.js
console.log("=== LOOP CONTROL: BREAK AND CONTINUE ===");
// Using continue to skip
console.log("Odd numbers from 1 to 10:");
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log("Odd number:", i);
}
// Using break to stop early
console.log("Looking for the number 7:");
for (let i = 1; i <= 10; i++) {
if (i === 7) {
console.log("Found 7! Stopping search.");
break;
}
console.log("Checking:", i);
}
// Practical example: Finding first valid user
const users = ["", "invalid", "john_doe", "jane_smith", ""];
console.log("Finding first valid user:");
for (const user of users) {
if (user === "") {
console.log("Skipping empty user");
continue;
}
if (user === "invalid") {
console.log("Skipping invalid user");
continue;
}
console.log("Found valid user:", user);
break; // Stop after finding first valid user
}
Exercise 5: Number Guessing Game
// src/05-loops/exercise5.js
console.log("=== EXERCISE 5: Number Guessing Game ===");
// Simulate a number guessing game
const secretNumber = 7;
const maxAttempts = 5;
let attempts = 0;
let hasWon = false;
// Array of simulated guesses (in real game, these would come from user input)
const guesses = [3, 9, 5, 7, 2];
console.log("Welcome to the Number Guessing Game!");
console.log("I'm thinking of a number between 1 and 10.");
console.log(`You have ${maxAttempts} attempts to guess it.`);
console.log("---");
// Main game loop
while (attempts < maxAttempts && !hasWon) {
attempts++;
const currentGuess = guesses[attempts - 1];
console.log(`Attempt ${attempts}: You guessed ${currentGuess}`);
if (currentGuess === secretNumber) {
console.log("🎉 Congratulations! You guessed the number!");
hasWon = true;
} else if (currentGuess < secretNumber) {
console.log("Too low! Try a higher number.");
} else {
console.log("Too high! Try a lower number.");
}
// Show remaining attempts
if (!hasWon && attempts < maxAttempts) {
console.log(`You have ${maxAttempts - attempts} attempts left.`);
}
console.log("---");
}
// Game over message
if (!hasWon) {
console.log(`Game Over! The number was ${secretNumber}.`);
console.log("Better luck next time!");
}
// Bonus: Calculate success rate
const successRate = hasWon ? ((maxAttempts - attempts + 1) / maxAttempts * 100).toFixed(1) : 0;
console.log(`Success rate: ${successRate}%`);
📚 Reference: MDN Loops and Iteration
Arrays: Organizing Your Data
Arrays are like organized containers that hold multiple items in a specific order. Think of them as shopping lists, photo albums, or playlists – they keep related items together and let you access them by their position.
Creating and Accessing Arrays
Arrays are fundamental for storing collections of related data:
// src/06-arrays/creating-arrays.js
console.log("=== CREATING AND ACCESSING ARRAYS ===");
// Different ways to create arrays
const fruits = ["apple", "banana", "orange"];
const numbers = [1, 2, 3, 4, 5];
const mixed = ["hello", 42, true, null];
const empty = [];
// Using Array constructor (less common)
const colors = new Array("red", "green", "blue");
console.log("Fruits array:", fruits);
console.log("Numbers array:", numbers);
console.log("Mixed array:", mixed);
console.log("Empty array:", empty);
console.log("Colors array:", colors);
// Accessing array elements (zero-based indexing)
console.log("First fruit:", fruits[0]); // "apple"
console.log("Second fruit:", fruits[1]); // "banana"
console.log("Last fruit:", fruits[2]); // "orange"
// Array length property
console.log("Number of fruits:", fruits.length);
// Accessing last element dynamically
console.log("Last fruit (dynamic):", fruits[fruits.length - 1]);
// Trying to access non-existent index
console.log("Fourth fruit:", fruits[3]); // undefined
Adding and Removing Elements
Arrays are dynamic – you can add and remove elements after creation:
// src/06-arrays/modifying-arrays.js
console.log("=== MODIFYING ARRAYS ===");
let shoppingList = ["milk", "bread"];
console.log("Initial shopping list:", shoppingList);
// Adding elements to the end
shoppingList.push("eggs");
shoppingList.push("cheese", "butter"); // Can add multiple items
console.log("After adding items:", shoppingList);
// Adding elements to the beginning
shoppingList.unshift("coffee");
console.log("After adding coffee to beginning:", shoppingList);
// Removing elements from the end
const removedItem = shoppingList.pop();
console.log("Removed item:", removedItem);
console.log("After removing last item:", shoppingList);
// Removing elements from the beginning
const firstItem = shoppingList.shift();
console.log("Removed first item:", firstItem);
console.log("After removing first item:", shoppingList);
// Removing elements from middle (splice method)
// splice(startIndex, deleteCount, ...itemsToAdd)
shoppingList.splice(1, 1, "organic bread", "almond milk");
console.log("After replacing bread with organic options:", shoppingList);
// Adding elements in the middle without removing
shoppingList.splice(2, 0, "yogurt");
console.log("After adding yogurt:", shoppingList);
Array Methods: The Power Tools
Arrays come with many built-in methods that make working with data much easier:
// src/06-arrays/array-methods.js
console.log("=== ARRAY METHODS ===");
const numbers = [1, 2, 3, 4, 5];
const fruits = ["apple", "banana", "orange", "grape"];
// Finding elements
console.log("Finding 3 in numbers:", numbers.includes(3)); // true
console.log("Index of 'banana':", fruits.indexOf("banana")); // 1
console.log("Index of 'kiwi':", fruits.indexOf("kiwi")); // -1 (not found)
// Joining arrays into strings
console.log("Fruits as string:", fruits.join(", "));
console.log("Numbers with dashes:", numbers.join("-"));
// Slicing arrays (creates new array)
const someFruits = fruits.slice(1, 3); // From index 1 to 2 (3 is excluded)
console.log("Some fruits:", someFruits);
console.log("Original fruits unchanged:", fruits);
// Concatenating arrays
const moreFruits = ["kiwi", "mango"];
const allFruits = fruits.concat(moreFruits);
console.log("All fruits:", allFruits);
// Reversing arrays (modifies original)
const reversedNumbers = [...numbers].reverse(); // Using spread to avoid modifying original
console.log("Reversed numbers:", reversedNumbers);
console.log("Original numbers:", numbers);
// Sorting arrays
const unsortedFruits = ["orange", "apple", "banana", "grape"];
const sortedFruits = [...unsortedFruits].sort();
console.log("Sorted fruits:", sortedFruits);
// Sorting numbers (requires compare function)
const unsortedNumbers = [10, 5, 40, 25, 1000, 1];
const sortedNumbers = [...unsortedNumbers].sort((a, b) => a - b);
console.log("Sorted numbers:", sortedNumbers);
Looping Through Arrays
We've already seen some ways to loop through arrays, but let's explore all the options:
// src/06-arrays/array-loops.js
console.log("=== LOOPING THROUGH ARRAYS ===");
const tasks = ["Write code", "Test application", "Debug issues", "Deploy app"];
// Method 1: Traditional for loop
console.log("Method 1: Traditional for loop");
for (let i = 0; i < tasks.length; i++) {
console.log(`${i + 1}. ${tasks[i]}`);
}
// Method 2: for...of loop (modern and clean)
console.log("\nMethod 2: for...of loop");
for (const task of tasks) {
console.log(`Task: ${task}`);
}
// Method 3: forEach method (functional approach)
console.log("\nMethod 3: forEach method");
tasks.forEach((task, index) => {
console.log(`${index + 1}. ${task}`);
});
// Method 4: for...in loop (gets indices, not recommended for arrays)
console.log("\nMethod 4: for...in loop (indices)");
for (const index in tasks) {
console.log(`Index ${index}: ${tasks[index]}`);
}
// Practical example: Processing user data
const users = [
{ name: "Alice", age: 25, active: true },
{ name: "Bob", age: 30, active: false },
{ name: "Charlie", age: 35, active: true }
];
console.log("\nProcessing user data:");
users.forEach(user => {
const status = user.active ? "Active" : "Inactive";
console.log(`${user.name} (${user.age} years old) - ${status}`);
});
Exercise 6: Student Grade Manager
// src/06-arrays/exercise6.js
console.log("=== EXERCISE 6: Student Grade Manager ===");
// Initialize student data
const students = ["Alice", "Bob", "Charlie", "Diana", "Eve"];
const grades = [85, 92, 78, 96, 88];
console.log("Student Grade Management System");
console.log("================================");
// Display all students and their grades
console.log("All Students and Grades:");
for (let i = 0; i < students.length; i++) {
console.log(`${students[i]}: ${grades[i]}%`);
}
// Calculate class statistics
let totalGrades = 0;
let highestGrade = grades[0];
let lowestGrade = grades[0];
let highestStudent = students[0];
let lowestStudent = students[0];
for (let i = 0; i < grades.length; i++) {
totalGrades += grades[i];
if (grades[i] > highestGrade) {
highestGrade = grades[i];
highestStudent = students[i];
}
if (grades[i] < lowestGrade) {
lowestGrade = grades[i];
lowestStudent = students[i];
}
}
const averageGrade = totalGrades / grades.length;
console.log("\nClass Statistics:");
console.log(`Average Grade: ${averageGrade.toFixed(1)}%`);
console.log(`Highest Grade: ${highestStudent} with ${highestGrade}%`);
console.log(`Lowest Grade: ${lowestStudent} with ${lowestGrade}%`);
// Categorize students by performance
const excellentStudents = [];
const goodStudents = [];
const needsImprovementStudents = [];
for (let i = 0; i < students.length; i++) {
if (grades[i] >= 90) {
excellentStudents.push(students[i]);
} else if (grades[i] >= 80) {
goodStudents.push(students[i]);
} else {
needsImprovementStudents.push(students[i]);
}
}
console.log("\nPerformance Categories:");
console.log(`Excellent (90%+): ${excellentStudents.join(", ")}`);
console.log(`Good (80-89%): ${goodStudents.join(", ")}`);
console.log(`Needs Improvement (<80%): ${needsImprovementStudents.join(", ")}`);
// Add new student
const newStudent = "Frank";
const newGrade = 89;
students.push(newStudent);
grades.push(newGrade);
console.log(`\nAdded new student: ${newStudent} with grade ${newGrade}%`);
console.log(`Total students: ${students.length}`);
// Find students above average
const aboveAverageStudents = [];
for (let i = 0; i < students.length; i++) {
if (grades[i] > averageGrade) {
aboveAverageStudents.push(students[i]);
}
}
console.log(`Students above average: ${aboveAverageStudents.join(", ")}`);
📚 Reference: MDN Array Methods
Practice Exercises
Now that you've learned the fundamentals, let's put everything together with comprehensive exercises that combine multiple concepts:
Exercise 7: Personal Finance Tracker
// src/practice-exercises/exercise7.js
console.log("=== EXERCISE 7: Personal Finance Tracker ===");
// Initialize financial data
const transactions = [
{ type: "income", amount: 3000, description: "Salary", date: "2024-01-01" },
{ type: "expense", amount: 1200, description: "Rent", date: "2024-01-02" },
{ type: "expense", amount: 300, description: "Groceries", date: "2024-01-03" },
{ type: "income", amount: 500, description: "Freelance", date: "2024-01-04" },
{ type: "expense", amount: 100, description: "Gas", date: "2024-01-05" },
{ type: "expense", amount: 200, description: "Utilities", date: "2024-01-06" }
];
console.log("Personal Finance Tracker");
console.log("========================");
// Display all transactions
console.log("All Transactions:");
transactions.forEach((transaction, index) => {
const sign = transaction.type === "income" ? "+" : "-";
console.log(`${index + 1}. ${transaction.date}: ${sign}$${transaction.amount} - ${transaction.description}`);
});
// Calculate totals
let totalIncome = 0;
let totalExpenses = 0;
for (const transaction of transactions) {
if (transaction.type === "income") {
totalIncome += transaction.amount;
} else {
totalExpenses += transaction.amount;
}
}
const netBalance = totalIncome - totalExpenses;
console.log("\nFinancial Summary:");
console.log(`Total Income: $${totalIncome}`);
console.log(`Total Expenses: $${totalExpenses}`);
console.log(`Net Balance: $${netBalance}`);
// Budget analysis
const budgetLimit = 2000;
const remainingBudget = budgetLimit - totalExpenses;
console.log("\nBudget Analysis:");
console.log(`Budget Limit: $${budgetLimit}`);
console.log(`Remaining Budget: $${remainingBudget}`);
if (remainingBudget > 0) {
console.log("✅ You're within budget!");
} else {
console.log("❌ You've exceeded your budget!");
}
// Find largest expense
let largestExpense = 0;
let largestExpenseDescription = "";
for (const transaction of transactions) {
if (transaction.type === "expense" && transaction.amount > largestExpense) {
largestExpense = transaction.amount;
largestExpenseDescription = transaction.description;
}
}
console.log(`\nLargest Expense: $${largestExpense} for ${largestExpenseDescription}`);
Exercise 8: Simple Todo List Manager
// src/practice-exercises/exercise8.js
console.log("=== EXERCISE 8: Todo List Manager ===");
// Initialize todo list
const todos = [
{ id: 1, task: "Learn JavaScript", completed: false, priority: "high" },
{ id: 2, task: "Practice coding", completed: true, priority: "medium" },
{ id: 3, task: "Build React Native app", completed: false, priority: "high" },
{ id: 4, task: "Read documentation", completed: false, priority: "low" },
{ id: 5, task: "Exercise", completed: true, priority: "medium" }
];
console.log("Todo List Manager");
console.log("================");
// Display all todos
function displayTodos() {
console.log("All Todos:");
todos.forEach(todo => {
const status = todo.completed ? "✅" : "❌";
const priority = todo.priority.toUpperCase();
console.log(`${status} [${priority}] ${todo.task}`);
});
}
displayTodos();
// Count completed and pending todos
let completedCount = 0;
let pendingCount = 0;
for (const todo of todos) {
if (todo.completed) {
completedCount++;
} else {
pendingCount++;
}
}
console.log(`\nProgress: ${completedCount} completed, ${pendingCount} pending`);
// Display pending todos by priority
const highPriorityTodos = [];
const mediumPriorityTodos = [];
const lowPriorityTodos = [];
for (const todo of todos) {
if (!todo.completed) {
switch (todo.priority) {
case "high":
highPriorityTodos.push(todo.task);
break;
case "medium":
mediumPriorityTodos.push(todo.task);
break;
case "low":
lowPriorityTodos.push(todo.task);
break;
}
}
}
console.log("\nPending Todos by Priority:");
if (highPriorityTodos.length > 0) {
console.log("🔴 High Priority:", highPriorityTodos.join(", "));
}
if (mediumPriorityTodos.length > 0) {
console.log("🟡 Medium Priority:", mediumPriorityTodos.join(", "));
}
if (lowPriorityTodos.length > 0) {
console.log("🟢 Low Priority:", lowPriorityTodos.join(", "));
}
// Calculate completion percentage
const completionPercentage = (completedCount / todos.length * 100).toFixed(1);
console.log(`\nCompletion Rate: ${completionPercentage}%`);
// Add new todo
const newTodo = {
id: todos.length + 1,
task: "Review code",
completed: false,
priority: "medium"
};
todos.push(newTodo);
console.log(`\nAdded new todo: "${newTodo.task}"`);
console.log(`Total todos: ${todos.length}`);
Next Steps
Congratulations! You've built a solid foundation in JavaScript that will serve you well in your React Native journey. Let's review what you've accomplished and map out your next steps.
What You've Mastered
Through this comprehensive guide, you've learned the essential JavaScript concepts that form the backbone of React Native development:
Core Language Features: You understand variables, data types, and operators – the basic building blocks that let you store, manipulate, and work with information in your apps.
Decision Making: You can use if statements, switch statements, and ternary operators to create apps that respond intelligently to different conditions and user inputs.
Repetition and Efficiency: You've mastered loops that let you process collections of data efficiently, whether you're displaying lists of items or performing calculations on large datasets.
Data Organization: You understand arrays and how to manipulate them, giving you the power to handle lists of information that are central to most mobile applications.
Problem-Solving Approach: Through practical exercises, you've practiced breaking down complex problems into smaller, manageable pieces – a skill that will serve you throughout your development career.
Connecting to React Native
Everything you've learned directly applies to React Native development. When you create a React Native app, you'll use these JavaScript fundamentals constantly:
State Management: The variables and data types you've mastered will help you manage your app's state – tracking user input, storing preferences, and handling dynamic content.
User Interface Logic: The conditional statements and loops you've learned will help you create dynamic interfaces that adapt to user actions and data changes.
Data Handling: The array methods and data manipulation techniques you've practiced will be essential for displaying lists, processing user input, and working with API responses.
Your Learning Path Forward
This guide is Part 1 of a comprehensive series. Here's what comes next in your React Native mastery journey:
Part 2: Advanced JavaScript Concepts will cover functions, objects, destructuring, and modern JavaScript features like arrow functions and async/await. These concepts will elevate your code from functional to elegant and efficient.
Recommended Practice
Before moving to the next part, strengthen your foundation with these practice activities:
Build a Simple Calculator: Create a calculator that performs basic operations on user input. This will reinforce your understanding of variables, operators, and functions.
Create a Data Processor: Build a small program that takes an array of student information and calculates grades, averages, and generates reports. This will solidify your array manipulation skills.
Develop a Text Analyzer: Write a program that analyzes text input – counting words, finding the longest word, or identifying patterns. This will help you practice string manipulation and loops.
Resources for Continued Learning
Official Documentation: The Mozilla Developer Network (MDN) JavaScript documentation is your best friend for diving deeper into any concept you've learned.
Practice Platforms: Websites like Codecademy, freeCodeCamp, and JavaScript.info offer interactive exercises that reinforce these concepts.
Community Support: Join JavaScript and React Native communities on Discord, Reddit, or Stack Overflow where you can ask questions and learn from experienced developers.
Final Thoughts
Remember that mastering JavaScript is a journey, not a destination. The concepts you've learned in this guide will become second nature with practice, and you'll find yourself thinking in JavaScript as you approach programming problems.
Every expert developer started exactly where you are now – with curiosity, dedication, and a willingness to practice. The fact that you've worked through this comprehensive guide shows you have the determination to succeed in React Native development.
Keep coding, keep practicing, and most importantly, keep building. Your React Native journey is just beginning, and you now have the solid JavaScript foundation that will support everything you create going forward.
Ready for the next step? Watch for Part 2 of this series, where we'll dive into advanced JavaScript concepts that will take your React Native skills to the next level.
Continue your React Native mastery journey with our complete series. Each part builds on the previous one, creating a comprehensive learning path from beginner to confident React Native developer.
📚 Complete Series References:
About This Series: This is module 3 of "The Ultimate Road to React Native Mastery" – a comprehensive series designed to take you from complete beginner to confident React Native developer. Each part builds systematically on the previous one, ensuring you develop both understanding and practical skills.
Coming Next: Part 2 of this module will cover Advanced JavaScript Concepts including functions, objects, destructuring, and modern JavaScript features that will elevate your React Native development skills.
This content originally appeared on DEV Community and was authored by Fonyuy Gita

Fonyuy Gita | Sciencx (2025-07-12T06:53:57+00:00) THE JAVASCRIPT NEEDED TO BE TOP 1% REACT NATIVE DEVELOPER. Retrieved from https://www.scien.cx/2025/07/12/the-javascript-needed-to-be-top-1-react-native-developer/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.