Introduction to JavaScript for React Native
Course: React Native Training
Topic: Introduction to JavaScript for React Native
Course Link: React Native Training at JustAcademy
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to JavaScript
JavaScript is a programming language used to create interactive applications and implement application logic. In React Native, JavaScript is used to define components, manage data, respond to user actions, process information, communicate with APIs, and control application behavior.
React Native uses React concepts and JavaScript to build applications for platforms such as Android and iOS. Instead of creating an entire application using separate native UI code for each platform, developers can reuse much of their JavaScript and React code while rendering native user interface components.
1.1 What Is JavaScript?
JavaScript is a high-level programming language that supports variables, functions, objects, arrays, conditions, loops, and asynchronous operations. It is commonly used for web development and cross-platform application development.
Example:
const appName = "My React Native App";
const version = 1;
console.log(appName);
console.log(version);
In this example, appName stores a string, version stores a number, and console.log() displays their values in the development console.
1.2 Why JavaScript Is Important in React Native
- Defines application logic and reusable functions.
- Creates React components and works with JSX.
- Manages component data through props and state.
- Responds to button presses, text input, and other user interactions.
- Processes arrays and objects returned by APIs.
- Supports asynchronous operations such as network requests.
- Helps developers build reusable features for Android and iOS.
1.3 JavaScript and React Native
JavaScript provides the programming logic, React provides the component-based user interface model, and React Native provides native components and platform APIs.
| Technology |
Purpose |
Example |
| JavaScript |
Programming logic and data processing |
Functions, arrays, conditions |
| React |
Reusable components and UI updates |
Components, props, state |
| React Native |
Native mobile user interfaces and platform integration |
View, Text, Pressable |
| JSX |
Writing UI descriptions within JavaScript |
<Text>Hello</Text> |
2. JavaScript Development Fundamentals
2.1 Writing JavaScript Code
JavaScript code consists of statements, expressions, declarations, and function calls. Statements are commonly separated by semicolons, although JavaScript can insert semicolons automatically in many situations. Using consistent formatting improves readability.
const userName = "Aarav";
const age = 24;
console.log(`Name: ${userName}`);
console.log(`Age: ${age}`);
2.2 Comments in JavaScript
Comments explain code and are ignored during normal execution.
// This is a single-line comment
/*
This is a
multi-line comment
*/
const totalPrice = 500;
Use comments to explain important decisions, unusual logic, or complex operations rather than describing every obvious line.
3. Variables: var, let, and const
Variables store values that can be used and updated while an application runs. JavaScript provides var, let, and const for declaring variables.
| Keyword |
Scope |
Can Reassign? |
Typical Use |
var |
Function-scoped |
Yes |
Legacy code; generally avoid in new code |
let |
Block-scoped |
Yes |
Values that need reassignment |
const |
Block-scoped |
No |
Default choice for bindings that do not need reassignment |
3.1 Using let
let score = 10;
score = 20;
console.log(score); // 20
The score variable can be reassigned because it was declared with let.
3.2 Using const
const appTitle = "Student Manager";
console.log(appTitle);
A const binding cannot be reassigned. However, if it refers to an object or array, the object's properties or array contents may still be changed unless the object is otherwise protected.
const student = {
name: "Riya",
age: 21
};
student.age = 22;
console.log(student.age); // 22
3.3 Best Practices for Variables
- Prefer
const when reassignment is unnecessary.
- Use
let when a variable must be reassigned.
- Avoid using
var in most new application code.
- Choose meaningful names such as
userName or totalAmount.
- Use camelCase for ordinary JavaScript variables and functions.
4. JavaScript Data Types
JavaScript supports primitive data types and reference types. Understanding data types helps developers store, process, validate, and display information correctly.
4.1 Primitive Data Types
| Type |
Description |
Example |
| String |
Text data |
"React Native" |
| Number |
Integers and decimal numbers |
100, 19.5 |
| Boolean |
True or false value |
true |
| Undefined |
A declared variable without an assigned value |
let result; |
| Null |
An intentional absence of a value |
const selectedItem = null; |
| BigInt |
Very large integers |
12345678901234567890n |
| Symbol |
A unique primitive value |
Symbol("id") |
4.2 Reference Types: Objects and Arrays
Objects store related information as key-value pairs. Arrays store ordered collections of values.
const product = {
id: 101,
name: "Headphones",
price: 1500,
inStock: true
};
const colors = ["red", "blue", "green"];
console.log(product.name);
console.log(colors[0]);
4.3 Checking Data Types
The typeof operator identifies the type of many JavaScript values.
console.log(typeof "Hello"); // "string"
console.log(typeof 25); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof {}); // "object"
Important: typeof null returns "object" due to a historical JavaScript behavior. Use an explicit comparison such as value === null when checking for null.
5. Operators in JavaScript
Operators perform calculations, compare values, assign values, and combine conditions.
5.1 Arithmetic Operators
const price = 200;
const quantity = 3;
const total = price * quantity;
const discount = 50;
const finalPrice = total - discount;
console.log(finalPrice); // 550
| Operator |
Meaning |
Example |
+ |
Addition |
10 + 5 |
- |
Subtraction |
10 - 5 |
* |
Multiplication |
10 * 5 |
/ |
Division |
10 / 5 |
% |
Remainder |
10 % 3 |
** |
Exponentiation |
2 ** 3 |
5.2 Comparison Operators
const age = 20;
console.log(age > 18); // true
console.log(age === 20); // true
console.log(age !== 18); // true
Use strict equality (===) and strict inequality (!==) in most cases to avoid unexpected type conversion.
5.3 Logical Operators
const isLoggedIn = true;
const hasPermission = true;
const canAccess = isLoggedIn && hasPermission;
console.log(canAccess); // true
&& returns a value based on logical AND behavior.
|| returns a value based on logical OR behavior.
! negates a truthy or falsy value.
5.4 Nullish Coalescing and Optional Chaining
The nullish coalescing operator (??) provides a fallback only when a value is null or undefined. Optional chaining (?.) safely accesses nested properties when an intermediate value may be missing.
const user = {
profile: {
name: "Aman"
}
};
const displayName = user.profile?.name ?? "Guest";
console.log(displayName); // Aman
These operators are especially useful when working with incomplete API responses or optional user information.
6. Conditional Statements
Conditional statements execute different code depending on whether a condition is true or false. They are useful for validation, login flows, permission checks, and deciding which message an application should display.
6.1 if, else if, and else
const marks = 78;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 70) {
console.log("Grade B");
} else if (marks >= 50) {
console.log("Grade C");
} else {
console.log("Needs improvement");
}
6.2 Ternary Operator
The ternary operator is a compact alternative to a simple if-else expression.
const isLoggedIn = true;
const message = isLoggedIn
? "Welcome back"
: "Please log in";
console.log(message);
6.3 switch Statement
const status = "loading";
switch (status) {
case "loading":
console.log("Please wait...");
break;
case "success":
console.log("Data loaded");
break;
case "error":
console.log("Something went wrong");
break;
default:
console.log("Unknown status");
}
Use switch when several branches depend on the same expression and the structure is clearer than multiple conditions.
7. Loops and Iteration
Loops repeat operations. They are useful for processing lists of products, students, messages, or records returned by an API.
7.1 for Loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}
7.2 for...of Loop
const subjects = ["JavaScript", "React", "React Native"];
for (const subject of subjects) {
console.log(subject);
}
7.3 while Loop
let count = 1;
while (count <= 3) {
console.log(count);
count++;
}
7.4 Array Iteration Methods
JavaScript provides array methods that are often easier to read than traditional loops.
const prices = [100, 200, 300];
const discountedPrices = prices.map(price => price * 0.9);
const expensivePrices = prices.filter(price => price >= 200);
const totalPrice = prices.reduce((sum, price) => sum + price, 0);
console.log(discountedPrices);
console.log(expensivePrices);
console.log(totalPrice);
map() creates a new array by transforming each item.
filter() creates a new array containing items that pass a condition.
reduce() combines array values into a single result.
forEach() executes a callback for each item and does not create a transformed array.
8. Functions in JavaScript
A function is a reusable block of code designed to perform a task. Functions help keep application logic organized and reduce duplication.
8.1 Function Declaration
function greetUser(name) {
return `Hello, ${name}!`;
}
console.log(greetUser("Riya"));
8.2 Function Expression
const calculateTotal = function(price, quantity) {
return price * quantity;
};
console.log(calculateTotal(250, 4));
8.3 Arrow Functions
Arrow functions provide a concise way to define functions and are common in React Native event handlers, array methods, and functional components.
const add = (a, b) => {
return a + b;
};
const multiply = (a, b) => a * b;
console.log(add(5, 3));
console.log(multiply(5, 3));
8.4 Parameters and Return Values
Parameters receive input values, while a return statement sends a result back to the caller.
function calculateDiscount(price, percentage) {
const discount = price * percentage / 100;
return price - discount;
}
const finalPrice = calculateDiscount(1000, 10);
console.log(finalPrice); // 900
8.5 Default Parameters
function welcome(name = "Guest") {
return `Welcome, ${name}`;
}
console.log(welcome());
console.log(welcome("Aman"));
9. Scope and Closures
9.1 Understanding Scope
Scope determines where a variable can be accessed. JavaScript commonly uses global scope, function scope, and block scope.
const appName = "Student App";
function showAppName() {
const message = "Welcome to " + appName;
console.log(message);
}
showAppName();
The variable appName is available inside the function because it is defined in an outer scope. The variable message is local to the function.
9.2 Closures
A closure occurs when a function retains access to variables from the scope in which it was created, even after that outer function has finished executing.
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
Closures are useful for encapsulating logic and are part of the JavaScript concepts underlying many callback and hook patterns.
10. Arrays and Objects
Arrays and objects are essential for representing structured application data, including user profiles, product catalogs, shopping carts, and API responses.
10.1 Creating and Accessing Arrays
const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]);
fruits.push("Orange");
console.log(fruits.length);
10.2 Creating and Accessing Objects
const employee = {
id: 101,
name: "Neha",
department: "Development"
};
console.log(employee.name);
console.log(employee["department"]);
10.3 Destructuring Arrays and Objects
Destructuring extracts values from arrays or properties from objects into variables.
const user = {
name: "Karan",
age: 25
};
const { name, age } = user;
const coordinates = [10, 20];
const [x, y] = coordinates;
console.log(name, age);
console.log(x, y);
10.4 Spread Syntax
Spread syntax (...) can copy or combine arrays and objects. It is frequently used to create updated data without modifying the original array or object.
const oldUser = {
name: "Riya",
city: "Mumbai"
};
const updatedUser = {
...oldUser,
city: "Pune"
};
const firstList = [1, 2];
const secondList = [...firstList, 3, 4];
console.log(updatedUser);
console.log(secondList);
10.5 Rest Parameters
Rest parameters collect multiple function arguments into an array.
function sum(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
console.log(sum(10, 20, 30)); // 60
11. Template Literals and String Methods
Template literals use backticks and allow variables or expressions to be embedded inside strings using ${...}.
const firstName = "Aarav";
const lastName = "Sharma";
const fullName = `${firstName} ${lastName}`;
console.log(fullName);
Common string methods include:
| Method |
Purpose |
Example |
toUpperCase() |
Converts text to uppercase |
"hello".toUpperCase() |
toLowerCase() |
Converts text to lowercase |
"HELLO".toLowerCase() |
trim() |
Removes surrounding whitespace |
" hi ".trim() |
includes() |
Checks whether a string contains text |
"React Native".includes("React") |
slice() |
Extracts part of a string |
"JavaScript".slice(0, 4) |
12. ES6+ Features Used in React Native
Modern JavaScript includes features that make application code more concise and maintainable. React Native projects commonly use these features through their JavaScript toolchain.
12.1 let and const
Use block-scoped declarations to make variable behavior easier to understand.
12.2 Arrow Functions
const square = number => number * number;
12.3 Destructuring
const profile = { name: "Meera", city: "Delhi" };
const { name, city } = profile;
12.4 Spread and Rest
const original = [1, 2, 3];
const copy = [...original, 4];
function logItems(...items) {
console.log(items);
}
logItems("Home", "Profile", "Settings");
12.5 Modules: import and export
Modules allow code to be divided into separate files and reused across an application.
// utils.js
export const formatName = name => name.trim();
export function add(a, b) {
return a + b;
}
// App.js
import { formatName, add } from "./utils";
console.log(formatName(" Riya "));
console.log(add(2, 3));
Named exports are imported using their exported names. A default export can be imported with a chosen local name.
13. Understanding JSX
JSX is a syntax extension used with React to describe user interfaces inside JavaScript. It resembles HTML, but React Native JSX uses React Native components rather than browser DOM elements.
import { View, Text } from "react-native";
const WelcomeMessage = () => {
const name = "Aarav";
return (
<View>
<Text>Welcome, {name}!</Text>
</View>
);
};
export default WelcomeMessage;
13.1 JavaScript Expressions in JSX
Use curly braces to include JavaScript expressions in JSX. Expressions can contain variables, calculations, function calls, and conditional expressions.
const quantity = 3;
const price = 150;
return (
<Text>
Total: {quantity * price}
</Text>
);
13.2 JSX Rules
- Return a single parent element, or use a React fragment where appropriate.
- Close JSX elements correctly.
- Use curly braces to insert JavaScript expressions.
- Use React Native components such as
View and Text instead of browser elements such as div and p.
- Use
className only in environments or libraries that specifically support it; standard React Native styling uses the style prop.
14. React Native Components and JavaScript
React Native components are reusable building blocks for a mobile user interface. JavaScript determines their structure, values, event handlers, and behavior.
| Component |
Purpose |
View |
Container for grouping and arranging elements |
Text |
Displays text |
TextInput |
Accepts text from users |
Pressable |
Responds to press interactions |
Image |
Displays images |
ScrollView |
Provides a scrollable container for content |
FlatList |
Efficiently renders lists of data |
14.1 Using Variables in a Component
import { View, Text } from "react-native";
const ProductInfo = () => {
const productName = "Wireless Mouse";
const price = 799;
return (
<View>
<Text>Product: {productName}</Text>
<Text>Price: ₹{price}</Text>
</View>
);
};
export default ProductInfo;
15. Props and Data Passing
Props, short for properties, allow a parent component to pass data to a child component. Props make components reusable because their displayed information can change without rewriting their implementation.
import { View, Text } from "react-native";
const Greeting = ({ name }) => {
return (
<Text>Hello, {name}!</Text>
);
};
const App = () => {
return (
<View>
<Greeting name="Riya" />
<Greeting name="Aman" />
</View>
);
};
export default App;
In this example, name is passed from the parent to each instance of Greeting. A component should treat its props as read-only rather than modifying them directly.
16. State and useState
State stores information that can change while a component is in use. When state is updated through its setter, React can render the component again to reflect the new value.
import { useState } from "react";
import { View, Text, Pressable } from "react-native";
const Counter = () => {
const [count, setCount] = useState(0);
return (
<View>
<Text>Count: {count}</Text>
<Pressable onPress={() => setCount(current => current + 1)}>
<Text>Increase</Text>
</Pressable>
</View>
);
};
export default Counter;
16.1 Understanding the Code
useState(0) creates state with an initial value of zero.
count contains the current state value.
setCount requests an update to that state.
onPress runs the callback when the user presses the component.
- The functional updater receives the previous state value and returns the next value.
16.2 Updating Objects in State
When updating an object held in state, create a new object instead of directly mutating the existing one.
const [user, setUser] = useState({
name: "Riya",
city: "Mumbai"
});
const updateCity = () => {
setUser(current => ({
...current,
city: "Pune"
}));
};
17. Event Handling in React Native
Event handlers connect user actions to JavaScript functions. They can respond to button presses, text changes, selections, and other interactions.
import { View, Text, Pressable } from "react-native";
const ActionExample = () => {
const handlePress = () => {
console.log("Button pressed");
};
return (
<View>
<Pressable onPress={handlePress}>
<Text>Tap Here</Text>
</Pressable>
</View>
);
};
export default ActionExample;
Passing onPress={handlePress} supplies the function for React Native to call later. Writing onPress={handlePress()} calls the function immediately during rendering, which is usually not the intended behavior.
18. Working with Text Input
TextInput accepts text from a user. Its onChangeText callback can update component state so the current input can be displayed, validated, or submitted.
import { useState } from "react";
import { View, Text, TextInput } from "react-native";
const NameForm = () => {
const [name, setName] = useState("");
return (
<View>
<TextInput
placeholder="Enter your name"
value={name}
onChangeText={setName}
/>
<Text>Hello, {name || "Guest"}!</Text>
</View>
);
};
export default NameForm;
This example demonstrates controlled input: the displayed input value comes from state, and changes update state through setName.
19. Asynchronous JavaScript
Mobile applications frequently perform asynchronous operations, including API requests, file operations, and other tasks that may take time. Promises and async/await help manage these operations without blocking the flow of code while waiting for results.
19.1 Promises
A Promise represents the eventual completion or failure of an asynchronous operation.
const task = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Task completed");
} else {
reject(new Error("Task failed"));
}
});
task
.then(result => console.log(result))
.catch(error => console.error(error.message));
19.2 async and await
The async keyword defines an asynchronous function, and await pauses that function until a Promise settles.
const getMessage = async () => {
return "Data loaded successfully";
};
getMessage()
.then(message => console.log(message));
19.3 Error Handling with try...catch
const loadData = async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Unable to load data:", error.message);
}
};
loadData();
Always handle possible failures in network operations. In a real application, display a suitable error message to the user and consider loading indicators, retries, and offline behavior where appropriate.
20. Fetch API and JSON Data
The Fetch API allows JavaScript to make HTTP requests. APIs commonly send data in JSON format, which JavaScript can parse into objects and arrays.
20.1 Making a GET Request
const fetchPost = async () => {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/1"
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const post = await response.json();
console.log(post.title);
} catch (error) {
console.error("Request failed:", error.message);
}
};
fetchPost();
20.2 Converting JSON Strings
const jsonString = '{"name":"Riya","age":22}';
const user = JSON.parse(jsonString);
console.log(user.name);
const convertedBack = JSON.stringify(user);
console.log(convertedBack);
JSON.parse() converts valid JSON text into a JavaScript value.
JSON.stringify() converts a compatible JavaScript value into JSON text.
- Validate API responses and handle malformed data or failed requests appropriately.
21. Array Methods for React Native Lists
Arrays are commonly used to display lists of products, contacts, tasks, and notifications. Methods such as map(), filter(), and find() help process these collections.
21.1 Using map()
const students = [
{ id: 1, name: "Riya" },
{ id: 2, name: "Aman" },
{ id: 3, name: "Neha" }
];
const names = students.map(student => student.name);
console.log(names);
21.2 Using filter()
const products = [
{ id: 1, name: "Keyboard", price: 900 },
{ id: 2, name: "Mouse", price: 500 },
{ id: 3, name: "Monitor", price: 8000 }
];
const affordableProducts = products.filter(
product => product.price < 1000
);
console.log(affordableProducts);
21.3 Rendering Data in React Native
import { View, Text } from "react-native";
const students = [
{ id: "1", name: "Riya" },
{ id: "2", name: "Aman" },
{ id: "3", name: "Neha" }
];
const StudentList = () => {
return (
<View>
{students.map(student => (
<Text key={student.id}>
{student.name}
</Text>
))}
</View>
);
};
export default StudentList;
Each rendered item should have a stable, unique key. For longer or frequently changing lists, React Native's FlatList is generally preferable to manually rendering every item with map().
22. Error Handling and Debugging
Debugging helps identify and correct problems in JavaScript logic, application data, API calls, and component behavior.
22.1 Common Error Types
| Error Type |
Meaning |
Example |
| SyntaxError |
Code does not follow valid JavaScript syntax |
Missing closing bracket |
| ReferenceError |
Accessing an undeclared identifier |
Using a variable that does not exist |
| TypeError |
Performing an invalid operation on a value |
Calling a non-function as a function |
| Network Error |
A request cannot complete successfully |
Connection failure |
22.2 Using console.log()
const total = 250;
const quantity = 3;
console.log("Total:", total);
console.log("Quantity:", quantity);
console.log("Final amount:", total * quantity);
22.3 Using try...catch
try {
const data = JSON.parse('{"name":"Riya"}');
console.log(data.name);
} catch (error) {
console.error("Unable to parse data:", error.message);
}
22.4 Debugging Best Practices
- Read the complete error message and identify the relevant file and line.
- Check variable names, types, and expected values.
- Use logs or available debugging tools to inspect the flow of execution.
- Handle network failures and invalid responses explicitly.
- Remove unnecessary debugging logs before production releases.
- Avoid exposing passwords, tokens, or other sensitive data in logs.
23. JavaScript Best Practices for React Native
- Use descriptive variable and function names.
- Prefer
const and use let only when reassignment is needed.
- Use strict equality operators when comparing values.
- Break complex logic into small, reusable functions.
- Keep components focused on a clear responsibility.
- Use array methods when they make data transformations easier to understand.
- Update React state through the appropriate setter rather than mutating it directly.
- Handle asynchronous errors and unexpected API responses.
- Use stable keys when rendering lists.
- Keep secrets and private credentials out of client-side application code.
- Use consistent formatting and meaningful comments.
- Test application behavior on the target platforms.
24. Practical Example: Simple React Native Profile Screen
This example combines variables, objects, functions, destructuring, JSX, props, state, and event handling to create a simple interactive profile screen.
import { useState } from "react";
import {
View,
Text,
Pressable,
StyleSheet
} from "react-native";
const ProfileScreen = () => {
const [isFollowing, setIsFollowing] = useState(false);
const user = {
name: "Riya Sharma",
role: "React Native Learner",
city: "Mumbai"
};
const { name, role, city } = user;
const toggleFollow = () => {
setIsFollowing(current => !current);
};
return (
<View style={styles.container}>
<Text style={styles.title}>{name}</Text>
<Text>Role: {role}</Text>
<Text>City: {city}</Text>
<Pressable
style={styles.button}
onPress={toggleFollow}
>
<Text style={styles.buttonText}>
{isFollowing ? "Following" : "Follow"}
</Text>
</Pressable>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
padding: 20
},
title: {
fontSize: 24,
fontWeight: "bold",
marginBottom: 10
},
button: {
marginTop: 20,
paddingVertical: 12,
paddingHorizontal: 24,
backgroundColor: "#2563eb",
borderRadius: 8
},
buttonText: {
color: "#ffffff",
fontWeight: "bold"
}
});
export default ProfileScreen;
24.1 Concepts Used in the Example
| Concept |
Where It Is Used |
| Object |
The user object stores profile information. |
| Destructuring |
name, role, and city are extracted from the object. |
| Function |
toggleFollow() handles the follow action. |
| State |
isFollowing stores whether the user is followed. |
| Conditional expression |
The button text changes based on the state value. |
| JSX |
The UI is described using React Native components. |
| StyleSheet |
JavaScript objects define the component's styles. |
25. Common Mistakes and Troubleshooting
| Problem |
Possible Cause |
Solution |
| Variable cannot be accessed |
Variable is out of scope or misspelled |
Check declaration, spelling, and scope. |
| State does not update as expected |
State was mutated directly or the wrong setter was used |
Use the state setter and create new objects or arrays when updating collections. |
| Button handler runs immediately |
The function was called during rendering |
Pass a callback, such as onPress={handlePress}. |
| Unexpected comparison result |
Loose equality or implicit type conversion |
Prefer === and validate data types. |
| API data does not appear |
Request failed or response was not parsed |
Check network access, response status, and JSON parsing. |
| List warning about keys |
Rendered list items lack stable keys |
Provide unique, stable keys based on item identifiers. |
| JSX compilation error |
Incorrect tags, brackets, or expressions |
Review JSX syntax and ensure tags are correctly closed. |
| Input does not reflect typed text |
Input value is not connected to state correctly |
Use a controlled value and update it through onChangeText. |
26. Hands-On Exercises
Exercise 1: Variables and Data Types
- Create variables for a user's name, age, and city.
- Display the values using
console.log().
- Use
typeof to inspect their data types.
Exercise 2: Functions and Operators
- Create a function that accepts a price and quantity.
- Calculate the total cost.
- Apply a discount when the total exceeds a chosen amount.
- Return and display the final result.
Exercise 3: Array Processing
- Create an array of at least five products.
- Use
map() to extract their names.
- Use
filter() to find products below a selected price.
- Use
reduce() to calculate the combined price.
Exercise 4: React Native Counter
- Create a component with a counter initialized to zero.
- Add an Increase button.
- Add a Decrease button.
- Display the current counter value.
- Use the state setter to update the counter correctly.
Exercise 5: Profile Screen
- Create a profile object with a name, city, and role.
- Display the information using React Native components.
- Add a button that changes its label when pressed.
- Use state, functions, and JSX expressions to implement the interaction.
27. Mini Project: Student Information App
Project Objective: Build a basic React Native screen that displays student information and calculates a student's average marks.
Project Requirements
- Create a student object containing a name, course, and marks array.
- Use destructuring to extract the required values.
- Use
reduce() to calculate the total marks.
- Calculate the average marks.
- Display the student details using
View and Text.
- Use conditional logic to display a suitable result message.
- Add a button that toggles a simple status using
useState.
Sample JavaScript Logic
const student = {
name: "Aarav",
course: "React Native",
marks: [80, 75, 90]
};
const { name, course, marks } = student;
const totalMarks = marks.reduce(
(total, mark) => total + mark,
0
);
const averageMarks = totalMarks / marks.length;
const result = averageMarks >= 50
? "Pass"
: "Needs Improvement";
console.log(name);
console.log(course);
console.log(totalMarks);
console.log(averageMarks);
console.log(result);
Expected Learning: This project combines JavaScript objects, destructuring, arrays, arithmetic operators, array methods, variables, and conditional expressions. The React Native interface can then present the calculated information to the user.
28. Interview Questions and Answers
Q1. What is JavaScript?
Answer: JavaScript is a programming language used to implement application logic, process data, handle events, and build interactive applications. React Native uses JavaScript with React to create mobile applications.
Q2. What is the difference between let and const?
Answer: Both are block-scoped. A variable declared with let can be reassigned, while a const binding cannot be reassigned after initialization.
Q3. What are JavaScript data types?
Answer: JavaScript primitive types are string, number, bigint, boolean, undefined, symbol, and null. Objects, including arrays and functions, are reference types.
Q4. What is an arrow function?
Answer: An arrow function is a concise way to define a function using the => syntax. It is commonly used for callbacks, event handlers, and array methods.
Q5. What is the difference between == and ===?
Answer: The loose equality operator == may convert types before comparison. The strict equality operator === compares values without performing that implicit type conversion.
Q6. What is JSX?
Answer: JSX is a syntax extension that lets developers describe React user interfaces within JavaScript. React Native uses JSX with native components such as View and Text.
Q7. What is the difference between props and state?
Answer: Props are values passed from a parent component to a child component. State is data managed by a component that can change over time and trigger a re-render.
Q8. What is useState?
Answer: useState is a React Hook that lets a function component store and update state.
Q9. What is the purpose of map()?
Answer: map() transforms each element of an array and returns a new array containing the results.
Q10. What is the difference between map() and filter()?
Answer: map() transforms every item, while filter() returns the items that satisfy a condition.
Q11. What is destructuring?
Answer: Destructuring extracts values from arrays or properties from objects into variables using concise syntax.
Q12. What is the spread operator?
Answer: Spread syntax (...) expands iterable values or object properties. It is frequently used to copy and combine arrays and objects.
Q13. What are Promises?
Answer: Promises represent the eventual success or failure of asynchronous operations and can be handled using methods such as then() and catch().
Q14. What is async/await?
Answer: async and await provide a readable syntax for working with Promises. They are often used for network requests and other asynchronous operations.
Q15. Why should state not be mutated directly?
Answer: Direct mutation can prevent React from recognizing changes reliably and can lead to unpredictable behavior. State should be updated using its setter, usually by creating a new object or array when changing structured data.
29. Quick Revision Checklist
- Understand JavaScript syntax, comments, variables, and data types.
- Know the difference between
var, let, and const.
- Practice arithmetic, comparison, logical, and nullish operators.
- Use conditional statements and loops correctly.
- Create functions, arrow functions, and reusable callbacks.
- Understand scope, closures, arrays, objects, and destructuring.
- Practice spread syntax, template literals, and modules.
- Understand JSX and React Native components.
- Know how props, state, and event handlers work.
- Practice
map(), filter(), and reduce().
- Use Promises, async/await, and try...catch for asynchronous tasks.
- Fetch JSON data and handle unsuccessful requests.
- Debug common syntax, type, state, and rendering problems.
30. Recommended Learning Resources
31. Conclusion
JavaScript is a fundamental skill for React Native development. A strong understanding of variables, data types, operators, functions, arrays, objects, JSX, props, state, event handling, and asynchronous programming makes it easier to build interactive mobile applications.
Practice each concept with small examples before combining them into complete screens and projects. Focus on writing readable code, handling errors, updating state correctly, and processing data safely. These fundamentals provide a strong foundation for learning React Native navigation, API integration, forms, reusable components, and complete Android and iOS applications.
Continue Learning: Explore React Native Training | Register for a Demo