Variables, Data Types, and Operators in React Native
Course: React Native Training
Topic: Variables, Data Types, and Operators in JavaScript
Course Link: React Native Training Course – JustAcademy
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to Variables, Data Types, and Operators
React Native is a framework used to build mobile applications for Android and iOS using JavaScript or TypeScript and React. Variables, data types, and operators are fundamental programming concepts used to store information, perform calculations, compare values, and control application behavior.
For example, an e-commerce application may store a product name, price, quantity, and availability status. Operators can calculate the total price, and conditional expressions can determine whether the product should be displayed as available.
1.1 What Is a Variable?
A variable is a named binding that stores or references a value in a program.
const productName = "Wireless Headphones";
const price = 2499;
const isAvailable = true;
console.log(productName);
console.log(price);
console.log(isAvailable);
Here, productName stores text, price stores a number, and isAvailable stores a Boolean value.
1.2 What Is a Data Type?
A data type identifies the kind of value being represented. JavaScript includes primitive types such as String, Number, Boolean, Undefined, Null, BigInt, and Symbol. It also supports objects, arrays, and functions.
1.3 What Is an Operator?
An operator performs an operation on one or more values.
const price = 500;
const quantity = 3;
const total = price * quantity;
console.log(total); // 1500
1.4 Importance in React Native
- Store information entered by users.
- Calculate product prices, discounts, quantities, and totals.
- Validate forms and compare user input.
- Manage login, loading, and availability conditions.
- Process data received from APIs.
- Display different content based on application state.
2. Learning Objectives
After completing this topic, learners will be able to:
- Understand JavaScript variables and declaration keywords.
- Differentiate between
var, let, and const.
- Identify primitive and non-primitive data types.
- Use arithmetic, assignment, comparison, and logical operators.
- Understand type conversion, coercion, and truthy or falsy values.
- Apply variables and operators in React Native components.
- Validate numeric input and troubleshoot common JavaScript errors.
3. Declaring Variables in JavaScript
JavaScript provides three common variable declaration keywords: var, let, and const. They differ in their scope, reassignment, and redeclaration behavior.
3.1 The var Keyword
var is the older declaration keyword. It is function-scoped and allows reassignment and redeclaration within the same scope. Modern JavaScript code generally prefers let and const because their block-scoping behavior is easier to reason about.
var userName = "Aarav";
userName = "Riya";
console.log(userName); // Riya
3.2 The let Keyword
let declares a block-scoped variable whose value can be reassigned.
let quantity = 1;
quantity = 5;
console.log(quantity); // 5
A variable declared with let cannot be redeclared in the same scope.
let score = 10;
// let score = 20; // SyntaxError in the same scope
3.3 The const Keyword
const declares a block-scoped binding that must be initialized when declared and cannot be reassigned. It is a good default when reassignment is unnecessary.
const appName = "MyReactNativeApp";
const taxRate = 0.18;
console.log(appName);
console.log(taxRate);
A const binding does not make an object or array immutable. Its properties or elements can still be changed unless separately protected.
const user = {
name: "Riya",
city: "Mumbai"
};
user.city = "Pune";
console.log(user.city); // Pune
// user = {}; // TypeError: reassignment is not allowed
3.4 Difference Between var, let, and const
| Feature |
var |
let |
const |
| Scope |
Function scope |
Block scope |
Block scope |
| Reassignment |
Allowed |
Allowed |
Not allowed |
| Redeclaration in same scope |
Allowed |
Not allowed |
Not allowed |
| Initialization required |
No |
No |
Yes |
| Recommended modern usage |
Usually avoid in new code |
When reassignment is needed |
Default when reassignment is unnecessary |
3.5 Practical Example
const appTitle = "Expense Tracker";
let monthlyExpense = 12000;
monthlyExpense = monthlyExpense + 1500;
console.log(appTitle);
console.log(monthlyExpense); // 13500
4. Variable Naming Rules and Best Practices
Good variable names make code easier to read, maintain, and debug.
4.1 Naming Rules
- Names may contain letters, digits, underscores, and dollar signs.
- A name cannot begin with a digit.
- Reserved keywords cannot be used as ordinary variable names.
- Names are case-sensitive.
- Spaces are not allowed in variable names.
- Use meaningful names that explain the purpose of the value.
4.2 Valid and Invalid Names
| Name |
Status |
Explanation |
userName |
Valid |
Uses a descriptive camelCase name. |
totalPrice |
Valid |
Clearly describes the value. |
_count |
Valid |
Starts with an underscore. |
$amount |
Valid |
Starts with a dollar sign. |
2items |
Invalid |
Cannot begin with a digit. |
user name |
Invalid |
Contains a space. |
const |
Invalid |
Reserved keyword. |
4.3 CamelCase Convention
JavaScript commonly uses camelCase for variables and functions.
const firstName = "Aarav";
const totalCartPrice = 3500;
const isUserLoggedIn = true;
let selectedProductCount = 2;
5. Understanding JavaScript Data Types
JavaScript data types can be grouped into primitive and non-primitive categories.
5.1 Primitive Data Types
| Type |
Description |
Example |
| String |
Textual data |
"React Native" |
| Number |
Integers and decimal numbers |
42, 19.99 |
| BigInt |
Large integers beyond the safe integer range of Number |
9007199254740993n |
| Boolean |
Logical true or false |
true |
| Undefined |
A variable has not been assigned a value |
let result; |
| Null |
An intentional absence of a value |
const selectedItem = null; |
| Symbol |
A unique identifier value |
Symbol("id") |
5.2 Non-Primitive Data Types
Objects represent collections of properties and more complex information. Arrays and functions are also objects in JavaScript.
- Object: Stores related information as key-value pairs.
- Array: Stores an ordered collection of values.
- Function: Represents reusable executable code.
const user = {
name: "Aarav",
age: 25,
isActive: true
};
const skills = ["JavaScript", "React Native", "Git"];
function greetUser(name) {
return "Hello, " + name;
}
console.log(user.name);
console.log(skills[0]);
console.log(greetUser("Aarav"));
6. String Data Type
A string represents text. Strings can be created with single quotes, double quotes, or backticks.
6.1 Creating Strings
const firstName = "Riya";
const city = 'Mumbai';
const framework = `React Native`;
console.log(firstName);
console.log(city);
console.log(framework);
6.2 String Concatenation
The plus operator combines strings.
const firstName = "Riya";
const lastName = "Sharma";
const fullName = firstName + " " + lastName;
console.log(fullName); // Riya Sharma
6.3 Template Literals
Template literals use backticks and allow variables or expressions to be embedded using ${...}.
const productName = "Smart Watch";
const price = 1999;
const message = `The ${productName} costs ₹${price}.`;
console.log(message);
6.4 Common String Properties and Methods
const message = "React Native";
console.log(message.length); // 12
console.log(message.toUpperCase()); // REACT NATIVE
console.log(message.toLowerCase()); // react native
console.log(message.includes("React")); // true
console.log(message.slice(0, 5)); // React
Other useful methods include trim(), startsWith(), and replace(). Strings are immutable, so these methods return new strings rather than changing the original string.
7. Number Data Type
The Number type represents integers and decimal numbers. It is used for prices, quantities, scores, dimensions, and calculations.
const price = 1499.50;
const discount = 0.10;
const discountedPrice = price - price * discount;
console.log(discountedPrice); // 1349.55
7.1 Special Number Values
NaN represents an invalid numeric result.
Infinity represents positive infinity.
-Infinity represents negative infinity.
Number.MAX_SAFE_INTEGER identifies the largest safe integer for Number calculations.
console.log(Number("123")); // 123
console.log(Number("hello")); // NaN
console.log(Number.isNaN(NaN)); // true
console.log(10 / 0); // Infinity
console.log(Number.isFinite(10)); // true
7.2 Floating-Point Precision
Some decimal calculations may produce results that look unexpected because JavaScript uses binary floating-point numbers.
console.log(0.1 + 0.2); // 0.30000000000000004
For financial applications, use appropriate rounding rules. A common approach is to represent money in the smallest currency unit, such as paise, where suitable.
const priceInPaise = 1999;
const quantity = 3;
const totalInPaise = priceInPaise * quantity;
console.log(totalInPaise); // 5997
8. Boolean Data Type
A Boolean value is either true or false. It is useful for representing login status, product availability, loading status, and validation results.
const isLoggedIn = true;
const isLoading = false;
const hasPermission = true;
if (isLoggedIn && hasPermission) {
console.log("Access granted");
}
8.1 Boolean Values in React Native
import React from "react";
import { View, Text } from "react-native";
export default function StatusScreen() {
const isLoading = false;
return (
<View>
{isLoading ? (
<Text>Loading...</Text>
) : (
<Text>Content is ready.</Text>
)}
</View>
);
}
This example uses a ternary expression to display different text depending on the Boolean value.
9. Undefined and Null
9.1 Undefined
A variable declared with let or var but not assigned a value evaluates to undefined. A function without an explicit return value also returns undefined.
let selectedProduct;
console.log(selectedProduct); // undefined
function printMessage() {
console.log("Hello");
}
console.log(printMessage()); // undefined
9.2 Null
null is used to represent an intentional absence of a value.
const selectedUser = null;
if (selectedUser === null) {
console.log("No user is selected.");
}
9.3 Difference Between Null and Undefined
| Feature |
undefined |
null |
| Meaning |
Missing or unassigned value |
Intentional absence of value |
| Example |
let result; |
const result = null; |
| typeof result |
"undefined" |
"object" due to a historical quirk |
| Strict check |
value === undefined |
value === null |
10. Objects and Arrays
10.1 Objects
An object groups related information into properties. React Native applications often use objects to represent users, products, settings, and API responses.
const product = {
id: 101,
name: "Bluetooth Speaker",
price: 2500,
inStock: true
};
console.log(product.name);
console.log(product.price);
console.log(product.inStock);
Properties can be accessed with dot notation or bracket notation.
console.log(product.name);
console.log(product["price"]);
10.2 Arrays
An array stores an ordered collection of values. Array indexes begin at zero.
const colors = ["red", "green", "blue"];
console.log(colors[0]); // red
console.log(colors[1]); // green
console.log(colors.length); // 3
10.3 Arrays of Objects
Arrays of objects are frequently used to display lists in React Native.
const products = [
{ id: "p1", name: "Keyboard", price: 1200 },
{ id: "p2", name: "Mouse", price: 600 },
{ id: "p3", name: "Monitor", price: 8500 }
];
products.forEach((product) => {
console.log(product.name, product.price);
});
When displaying such data using FlatList, provide a stable unique key for each item.
11. The typeof Operator
The typeof operator returns a string identifying the type category of a value.
console.log(typeof "Hello"); // string
console.log(typeof 25); // number
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof 10n); // bigint
console.log(typeof Symbol("id")); // symbol
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof null); // object
console.log(typeof function () {}); // function
Use Array.isArray() to identify arrays because typeof [] returns "object".
console.log(Array.isArray(["pen", "book"])); // true
console.log(Array.isArray({})); // false
12. Arithmetic Operators
Arithmetic operators perform mathematical calculations. They are useful for counters, totals, budgets, scores, and discounts.
| Operator |
Name |
Example |
Result |
+ |
Addition |
10 + 5 |
15 |
- |
Subtraction |
10 - 5 |
5 |
* |
Multiplication |
10 * 5 |
50 |
/ |
Division |
10 / 5 |
2 |
% |
Remainder |
10 % 3 |
1 |
** |
Exponentiation |
2 ** 3 |
8 |
++ |
Increment |
count++ |
Increases count by one |
-- |
Decrement |
count-- |
Decreases count by one |
12.1 Arithmetic Example
const price = 800;
const quantity = 4;
const subtotal = price * quantity;
const deliveryFee = 50;
const total = subtotal + deliveryFee;
console.log(subtotal); // 3200
console.log(total); // 3250
12.2 Increment and Decrement
Prefix and postfix forms differ in the value returned by the expression.
let count = 5;
console.log(count++); // 5, then count becomes 6
console.log(count); // 6
console.log(++count); // 7
For React state, use the state setter rather than directly changing a state variable.
13. Assignment Operators
Assignment operators assign values to variables. Compound assignment operators combine an operation with assignment.
| Operator |
Meaning |
Example |
Equivalent |
= |
Assignment |
x = 10 |
Assign 10 to x |
+= |
Add and assign |
x += 5 |
x = x + 5 |
-= |
Subtract and assign |
x -= 5 |
x = x - 5 |
*= |
Multiply and assign |
x *= 2 |
x = x * 2 |
/= |
Divide and assign |
x /= 2 |
x = x / 2 |
%= |
Remainder and assign |
x %= 3 |
x = x % 3 |
let balance = 1000;
balance += 500;
console.log(balance); // 1500
balance -= 200;
console.log(balance); // 1300
14. Comparison Operators
Comparison operators compare values and return Boolean results. They are commonly used in validation and conditional rendering.
| Operator |
Meaning |
Example |
Result |
== |
Loose equality |
5 == "5" |
true |
=== |
Strict equality |
5 === "5" |
false |
!= |
Loose inequality |
5 != "6" |
true |
!== |
Strict inequality |
5 !== "5" |
true |
> |
Greater than |
10 > 5 |
true |
< |
Less than |
3 < 8 |
true |
>= |
Greater than or equal to |
5 >= 5 |
true |
<= |
Less than or equal to |
4 <= 3 |
false |
14.1 Strict Equality
Strict equality checks both type and value without automatic type coercion. It is generally preferred in application code.
console.log(10 == "10"); // true
console.log(10 === "10"); // false
const userAge = 18;
if (userAge >= 18) {
console.log("Eligible");
} else {
console.log("Not eligible");
}
15. Logical Operators
Logical operators combine conditions or invert a Boolean result.
| Operator |
Name |
Description |
&& |
Logical AND |
Returns a truthy result only when both operands are truthy. |
|| |
Logical OR |
Returns the first truthy operand, or the final operand if none is truthy. |
! |
Logical NOT |
Inverts the truthiness of a value. |
15.1 Logical AND
const isLoggedIn = true;
const hasPermission = true;
if (isLoggedIn && hasPermission) {
console.log("Access granted");
}
15.2 Logical OR
const preferredName = "";
const displayName = preferredName || "Guest";
console.log(displayName); // Guest
Logical OR uses truthiness. If zero or an empty string is a valid value that must be preserved, consider using ?? instead.
15.3 Logical NOT
const isLoading = false;
console.log(!isLoading); // true
16. Conditional (Ternary) Operator
The ternary operator selects one of two expressions based on a condition. Its syntax is condition ? valueIfTrue : valueIfFalse.
const age = 20;
const message = age >= 18 ? "Adult" : "Minor";
console.log(message); // Adult
16.1 Ternary Operator in React Native
import React from "react";
import { View, Text } from "react-native";
export default function StatusScreen() {
const isLoggedIn = true;
return (
<View>
<Text>
{isLoggedIn ? "Welcome back!" : "Please log in."}
</Text>
</View>
);
}
Use ternary expressions for simple alternatives. For complex logic, use named variables or separate functions.
17. Nullish Coalescing and Optional Chaining
17.1 Nullish Coalescing Operator
The ?? operator provides a fallback only when the left operand is null or undefined.
const quantity = 0;
console.log(quantity ?? 1); // 0
const userName = null;
console.log(userName ?? "Guest"); // Guest
Unlike ||, the nullish coalescing operator preserves valid falsy values such as zero and an empty string.
console.log(0 || 1); // 1
console.log(0 ?? 1); // 0
console.log("" || "Default"); // Default
console.log("" ?? "Default"); // ""
17.2 Optional Chaining Operator
Optional chaining safely accesses a property when an intermediate value may be null or undefined.
const user = {
profile: {
name: "Riya"
}
};
console.log(user.profile?.name); // Riya
const missingUser = null;
console.log(missingUser?.profile?.name); // undefined
18. Type Conversion and Type Coercion
Type conversion changes a value from one type to another. Explicit conversion is performed by the developer, while coercion is performed automatically by JavaScript in certain operations.
18.1 Explicit Conversion
const ageText = "25";
const age = Number(ageText);
console.log(age); // 25
console.log(typeof age); // number
console.log(String(1500)); // "1500"
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
18.2 Converting Text Input to a Number
React Native's TextInput provides entered text as a string. Convert and validate numeric input before calculations.
const quantityText = "4";
const priceText = "250";
const quantity = Number(quantityText);
const price = Number(priceText);
const total = quantity * price;
console.log(total); // 1000
Remember that Number("") returns zero and invalid numeric text returns NaN. Validate empty input separately when an empty field should not be treated as zero.
18.3 Automatic Type Coercion
console.log("5" + 2); // "52"
console.log("5" - 2); // 3
console.log("5" * 2); // 10
console.log(true + 1); // 2
These examples show that JavaScript may convert values differently depending on the operator. Explicit conversion makes application logic easier to understand.
19. Truthy and Falsy Values
JavaScript conditions evaluate values using truthiness. Falsy values include false, 0, -0, 0n, "", null, undefined, and NaN. Empty arrays and empty objects are truthy.
console.log(Boolean("React Native")); // true
console.log(Boolean(100)); // true
console.log(Boolean([])); // true
console.log(Boolean({})); // true
console.log(Boolean("")); // false
console.log(Boolean(0)); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
19.1 Avoiding Unexpected Zero in JSX
When a numeric value is used directly with logical AND, the number zero can be rendered instead of nothing.
const unreadCount = 0;
// May render 0:
{unreadCount && <Text>Unread messages</Text>}
// Explicit condition:
{unreadCount > 0 && <Text>Unread messages</Text>}
20. Bitwise Operators
Bitwise operators work with binary representations of numbers. They are used in specialized algorithms and bit flags but are less common in everyday React Native interface development.
| Operator |
Name |
Example |
& |
Bitwise AND |
5 & 1 |
| |
Bitwise OR |
5 | 1 |
^ |
Bitwise XOR |
5 ^ 1 |
~ |
Bitwise NOT |
~5 |
<< |
Left shift |
5 << 1 |
>> |
Sign-propagating right shift |
5 >> 1 |
>>> |
Zero-fill right shift |
5 >>> 1 |
console.log(5 & 1); // 1
console.log(5 | 1); // 5
console.log(5 ^ 1); // 4
console.log(5 << 1); // 10
21. Operator Precedence
Operator precedence determines the order in which operations are evaluated. Parentheses can clarify the intended calculation.
const resultOne = 2 + 3 * 4;
console.log(resultOne); // 14
const resultTwo = (2 + 3) * 4;
console.log(resultTwo); // 20
- Use parentheses for complex expressions.
- Break long calculations into smaller steps.
- Store intermediate results in descriptive variables.
- Test calculations with zero, negative numbers, and invalid input.
22. Variables and Operators in React Native Components
Variables can represent labels, calculations, and conditions inside React Native components. However, changing an ordinary local variable does not trigger a component re-render. Use React state when changing a value should update the interface.
22.1 Product Price Calculator
import React from "react";
import { View, Text } from "react-native";
export default function PriceCalculator() {
const price = 500;
const quantity = 3;
const discountRate = 0.10;
const subtotal = price * quantity;
const discount = subtotal * discountRate;
const finalTotal = subtotal - discount;
return (
<View>
<Text>Price: ₹{price}</Text>
<Text>Quantity: {quantity}</Text>
<Text>Subtotal: ₹{subtotal}</Text>
<Text>Discount: ₹{discount}</Text>
<Text>Final Total: ₹{finalTotal}</Text>
</View>
);
}
22.2 Counter Using React State
import React, { useState } from "react";
import { View, Text, Button } from "react-native";
export default function CounterApp() {
const [count, setCount] = useState(0);
return (
<View>
<Text>Count: {count}</Text>
<Button
title="Increase"
onPress={() => setCount((previousCount) => previousCount + 1)}
/>
<Button
title="Decrease"
onPress={() => setCount((previousCount) => previousCount - 1)}
/>
</View>
);
}
The useState hook stores the current count and provides a setter that triggers an update. The functional updater is useful when the next value depends on the previous value.
23. Working with TextInput and Numeric Values
React Native's TextInput receives text from users. A calculator must convert the text to numbers and validate it before calculating totals.
import React, { useState } from "react";
import { View, Text, TextInput } from "react-native";
export default function QuantityCalculator() {
const [quantityText, setQuantityText] = useState("1");
const [priceText, setPriceText] = useState("100");
const quantity = Number(quantityText);
const price = Number(priceText);
const hasValidInput =
quantityText.trim() !== "" &&
priceText.trim() !== "" &&
Number.isFinite(quantity) &&
Number.isFinite(price) &&
quantity >= 0 &&
price >= 0;
const total = hasValidInput ? quantity * price : null;
return (
<View>
<Text>Quantity</Text>
<TextInput
value={quantityText}
onChangeText={setQuantityText}
keyboardType="numeric"
placeholder="Enter quantity"
/>
<Text>Price</Text>
<TextInput
value={priceText}
onChangeText={setPriceText}
keyboardType="numeric"
placeholder="Enter price"
/>
<Text>
{total === null ? "Enter valid values" : `Total: ₹${total}`}
</Text>
</View>
);
}
This example demonstrates state variables, type conversion, logical operators, comparisons, and conditional output. A production form should also define rules for decimal input, maximum values, and currency rounding.
24. Common Errors and Troubleshooting
| Problem |
Cause |
Solution |
| Assignment to a constant error |
Reassigning a const binding |
Use let when reassignment is required. |
| Unexpected string concatenation |
Using + with text and numbers |
Convert and validate numeric input first. |
| Unexpected comparison result |
Comparing different types with loose equality |
Prefer === and !==. |
| NaN in calculations |
Invalid numeric input |
Check empty input and use Number.isFinite(). |
| Screen does not update |
Changing an ordinary local variable |
Use React state for values that update the UI. |
| Unexpected zero in JSX |
Using a numeric value directly with logical AND |
Use an explicit comparison such as count > 0. |
| Cannot read property of null or undefined |
Accessing unavailable nested data |
Validate data or use optional chaining where appropriate. |
| Unexpected decimal result |
Floating-point precision |
Apply appropriate rounding or use a suitable currency representation. |
24.1 Debugging Techniques
- Use
console.log() to inspect values.
- Use
typeof to inspect primitive type categories.
- Use
Array.isArray() to identify arrays.
- Use
Number.isNaN() and Number.isFinite() for numeric validation.
- Test missing data, empty strings, zero, and negative values.
- Inspect errors using React Native development tools.
25. Best Practices
- Prefer
const by default and use let when reassignment is needed.
- Avoid using
var in new modern JavaScript code.
- Use descriptive camelCase variable names.
- Use strict equality unless loose equality is specifically required.
- Convert and validate text input before calculations.
- Use
?? when a fallback should apply only to null or undefined.
- Use React state for values that must trigger interface updates.
- Avoid directly mutating state objects and arrays.
- Keep calculations and conditions readable.
- Validate data received from APIs before using it.
- Test edge cases such as zero, empty input, and invalid numeric strings.
26. Practical Exercises
Exercise 1: Personal Profile
Create variables for a user's name, age, city, and student status. Print each value and its type.
Exercise 2: Shopping Cart Calculation
Create variables for product price, quantity, and discount percentage. Calculate the subtotal, discount, and final total.
Exercise 3: Age Eligibility Checker
Store an age in a variable and use comparison operators to determine whether the person meets a specified age requirement.
Exercise 4: Form Input Validation
Convert text input to a number, check whether it is valid and non-negative, and display an appropriate message for empty or invalid input.
Exercise 5: React Native Counter
Build a counter screen with Increase and Decrease buttons. Use useState and prevent the count from going below zero.
Exercise 6: Product Availability
Create a product object with a name, price, and stock quantity. Use Boolean expressions to determine whether it is available.
27. Mini Project: Shopping Total Calculator
Objective: Build a React Native screen that calculates an item's total cost based on its unit price, quantity, and discount percentage.
27.1 Project Requirements
- Provide inputs for unit price, quantity, and discount percentage.
- Convert and validate the entered values.
- Calculate the subtotal and discount amount.
- Calculate the final total after discount.
- Display an error message when input is invalid.
- Update the results as input values change.
27.2 Sample Calculation
| Item |
Value |
| Unit price |
₹500 |
| Quantity |
3 |
| Subtotal |
₹1,500 |
| Discount rate |
10% |
| Discount amount |
₹150 |
| Final total |
₹1,350 |
27.3 Sample Calculation Logic
const unitPrice = 500;
const quantity = 3;
const discountPercentage = 10;
const subtotal = unitPrice * quantity;
const discountAmount = subtotal * (discountPercentage / 100);
const finalTotal = subtotal - discountAmount;
console.log(`Subtotal: ₹${subtotal}`);
console.log(`Discount: ₹${discountAmount}`);
console.log(`Final total: ₹${finalTotal}`);
28. Interview Questions and Answers
Q1. What is a variable in JavaScript?
A variable is a named binding used to store or reference a value.
Q2. What is the difference between let and const?
let allows reassignment, while const does not allow reassignment of its binding. Both are block-scoped.
Q3. What are the primitive data types in JavaScript?
String, Number, BigInt, Boolean, Undefined, Null, and Symbol.
Q4. What is the difference between == and ===?
== permits type coercion during comparison, while === checks type and value without that coercion.
Q5. What does typeof do?
It returns a string describing the type category of a value.
Q6. Why does typeof null return object?
It is a historical JavaScript quirk. Use value === null to check for null.
Q7. What is the difference between null and undefined?
undefined commonly represents a missing or unassigned value, while null represents an intentional absence of a value.
Q8. What is NaN?
NaN represents an invalid numeric result. Use Number.isNaN() to check for it.
Q9. What is the difference between an array and an object?
An array stores an ordered collection accessed by indexes. An object stores properties accessed by keys.
Q10. What does the remainder operator do?
The % operator returns the remainder after division. For example, 10 % 3 returns 1.
Q11. What is the difference between || and ???
|| uses truthiness to select a fallback, while ?? uses a fallback only for null or undefined.
Q12. Why might a React Native screen not update after a variable changes?
Changing an ordinary local variable does not trigger a re-render. Use React state when the UI must update.
Q13. What type of value does TextInput provide?
TextInput provides text as a string through onChangeText. Convert and validate it before numerical calculations.
Q14. Can a const object be modified?
Yes. Its binding cannot be reassigned, but its properties can still be modified unless the object is separately protected.
Q15. What are truthy and falsy values?
Truthy values behave like true in Boolean contexts. Falsy values include false, 0, "", null, undefined, and NaN.
29. Quick Revision Checklist
- Understand
var, let, and const.
- Follow variable naming conventions.
- Identify primitive types, objects, and arrays.
- Use
typeof and Array.isArray() appropriately.
- Practice arithmetic, assignment, comparison, and logical operators.
- Understand ternary expressions,
??, and optional chaining.
- Convert and validate numeric text input.
- Recognize truthy and falsy values.
- Use React state when values must update the interface.
- Test edge cases and debug errors carefully.
30. Additional Learning Resources
31. Conclusion
Variables, data types, and operators are essential building blocks of JavaScript and React Native development. Variables represent application information, data types define the values being processed, and operators perform calculations, comparisons, and logical decisions.
By practicing these concepts through a counter, form validator, and shopping calculator, learners can develop a strong foundation for more advanced React Native topics, including components, props, state management, API integration, navigation, and mobile application development.
Explore the React Native Training Course and register for a course demo at JustAcademy.