JavaScript is the beating heart of any React Native application. If you’re interested in creating fantastic mobile applications using React Native, you need to master JavaScript first.
A solid grasp of JavaScript fundamentals and its modern syntax is not just an advantage, it’s a necessity. This comprehensive guide will walk you through the essentials of the JavaScript language.
Introduction to JavaScript
JavaScript is a high-level, interpreted programming language. It’s a core technology of the web, along with HTML and CSS, and is primarily used to add interactivity to web pages. But with the advent of technologies like Node.js and React Native, JavaScript has found its place in server-side and mobile application development.
JavaScript conforms to the ECMAScript specification, and in this guide, we’ll focus on ES6 syntax, the sixth edition of the ECMAScript standard, which brought significant updates to the language.
Variables and Data Types
Variables
In JavaScript, variables are containers for storing data values. JavaScript provides several ways to create different types of variables, such as let
and const
.
let
is used when the variable may be reassigned, and const
is used when the variable should not be reassigned. Using const
can help make your code more predictable and easier to understand.
let name = 'John Doe'; // can be reassigned later
const pi = 3.14159; // cannot be reassigned later
Data Types
JavaScript is a dynamically typed language, which means that the same variable can hold values of any type without any type specification. It provides six primitive data types and one special data type for storing collections of values.
Number
The Number
data type represents both integer and floating point numbers. There are many operations for numbers, e.g. multiplication *
, division /
, addition +
, subtraction -
, and so on.
let num1 = 10; // An integer
let num2 = 10.5; // A floating point number
String
A String
is a sequence of characters used to represent text. There are 3 ways to define a String
value.
let str1 = 'Hello, world!'; // <-- using single quotes
let str2 = "Hello, world!"; // <-- using double quotes
let str3 = `Hello, world!`; // <-- using backticks
Boolean
The Boolean
type has only two values: true
and false
. This data type is commonly used for storing yes/no values.
let isTrue = true;
let isFalse = false;
Null
Null
in JavaScript is a special value that represents “nothing”, “empty” or “value unknown”.
let emptyValue = null;
Undefined
A variable that has not been assigned a value is of type undefined
.
let undefinedValue;
console.log(undefinedValue); // undefined
Objects and Arrays
The Object
data type is special. All other data types are considered primitive data types because their values can contain only a single thing—be it a string or a number.
In contrast, objects are used to store more complex entities. Objects can be created using the {}
syntax.
When defining an object, we use an identifier (also called a key) and a value.
In the following example, name
and age
are keys, and 'John Doe'
and ’25’ are values.
let person = {
name: 'John Doe',
age: 25
};
Arrays in JavaScript are a type of object which can store multiple values of the same type in a single variable.
Arrays can be created using the []
syntax.
let emptyArray = []; // <-- This array is empty
let fruits = ['apple', 'banana', 'cherry']; // <-- This array contains 3 String values
Exploring JavaScript Operators
Operators in JavaScript are symbols that tell the compiler to perform specific mathematical or logical manipulations. They are used to perform operations on variables and values.
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations.
let a = 10;
let b = 5;
console.log(a + b); // 15, addition
console.log(a - b); // 5, subtraction
console.log(a * b); // 50, multiplication
console.log(a / b); // 2, division
console.log(a % b); // 0, modulus (remainder)
console.log(a ** b); // 100000, exponentiation
Assignment Operators
Assignment operators are used to assign values to variables.
let a = 10; // assignment
a += 5; // addition assignment, equivalent to a = a + 5
a -= 5; // subtraction assignment, equivalent to a = a - 5
a *= 5; // multiplication assignment, equivalent to a = a * 5
a /= 5; // division assignment, equivalent to a = a / 5
a %= 5; // remainder assignment, equivalent to a = a % 5
a **= 5; // exponentiation assignment, equivalent to a = a ** 5
Comparison Operators
Comparison operators are used to compare values.
let a = 10;
let b = 5;
console.log(a == b); // false, equality
console.log(a != b); // true, inequality
console.log(a === b); // false, strict equality
console.log(a !== b); // true, strict inequality
console.log(a < b); // false, less than
console.log(a > b); // true, greater than
console.log(a <= b); // false, less than or equal to
console.log(a >= b); // true, greater than or equal to
Logical Operators
Logical operators are used to determine the logic between variables or values.
let a = true;
let b = false;
console.log(a && b); // false, logical AND
console.log(a || b); // true, logical OR
console.log(!a); // false, logical NOT
Conditional Statements and Error Handling
In programming, often we need to perform different actions based on different conditions. To do this, we use conditional statements.
In JavaScript, we have several types of conditional statements:
If Statement
The if
statement is used to specify a block of code to be executed if a specified condition is true.
let a = 10;
if (a > 5) {
console.log('a is greater than 5');
}
Else Statement
The else
statement is used to specify a block of code to be executed if the same condition is false.
let a = 4;
if (a > 5) {
console.log('a is greater than 5');
} else {
console.log('a is not greater than 5');
}
Else If Statement
The else if
statement is used to specify a new condition if the first condition is false.
let a = 5;
if (a > 5) {
console.log('a is greater than 5');
} else if (a === 5) {
console.log('a is equal to 5');
} else {
console.log('a is less than 5');
}
Sometimes, an error may occur in your code. To handle these errors, JavaScript provides a special syntax: try...catch
.
Try/Catch Statement
The try
statement lets you test a block of code for errors, and the catch
statement lets you handle the error.
try {
let a = 2;
if (a < 5) {
throw new Error('The value is too small');
}
} catch (error) {
console.log('An error occurred:', error.message); // logs 'An error occurred: The value is too small'
}
Working with JavaScript Functions
Functions are fundamental to JavaScript. They allow you to encapsulate a piece of code and reuse it in other parts of your code by calling it.
A function can have name like a variable or can be anonymous.
A function can accept parameters that will be used in the encapsulated piece of code.
A function is also a value in JavaScript, we can store it in a variable, in an object or in an array.
Let’s see how to define and call a function:
// Function declaration
/* This function is named `greet` and expects 1 parameter `name`. */
function greet(name) {
return `Hello, ${name}!`;
}
// Function call
/* We call the function and we pass a value 'John' to the parameter `name`. */
console.log(greet('John')); // logs "Hello, John!"
Manipulating Arrays
The JavaScript language provide several helpful methods for working with arrays like map()
, filter()
, and reduce()
.
Let’s see how to use these methods:
// map() takes a function as parameter, and creates a new array with the results of calling that function for every array element
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(num => num * num); // [1, 4, 9, 16, 25]
// filter() takes a function as parameter, and creates a new array with all elements that pass the test implemented by the provided function
let evenNumbers = numbers.filter(num => num % 2 === 0); // [2, 4]
// reduce() takes a function as parameter, and applies the function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
let sum = numbers.reduce((total, num) => total + num, 0); // 15
ES6 Syntax: The Modern JavaScript
ES6, or ECMAScript 2015, introduced a new syntax and powerful features to make your JavaScript code more modern and readable.
Arrow Functions
Arrow functions provide a new way to write functions with a more concise syntax.
// Arrow function
/* This function is anonymous and stored in a `const` variable `greet` */
const greet = (name) => `Hello, ${name}!`;
console.log(greet('Jane')); // logs "Hello, Jane!"
Template Literals
Template literals allow you to embed expressions within string literals.
let name = 'John';
console.log(`Hello, ${name}!`); // Hello, John!
Destructuring Assignment
Destructuring assignment allows you to unpack values from arrays or properties from objects into distinct variables.
let person = { name: 'John Doe', age: 25 };
let { name, age } = person;
console.log(name); // John Doe
console.log(age); // 25
Asynchronous Programming and Promises
JavaScript is a single-threaded language, which means it can only process one task at a time. However, JavaScript is also an asynchronous language, which means it can start multiple tasks without waiting for the previous task to complete.
This asynchronicity is especially useful when dealing with operations that are time-consuming, such as network requests, file I/O, or timers.
Understanding asynchronous programming and how to handle it effectively is crucial for writing modern JavaScript and React Native applications, as many operations when building UI apps are asynchronous by nature.
To handle tasks asynchronously, we use callbacks
, promises
, and async/await
.
Callbacks
The oldest and simplest way to handle asynchronous operations in JavaScript is using callbacks.
A callback function is a function passed into another function as an argument to be executed later.
function downloadData(url, callback) {
// Simulating data download with a timer
// After 2 seconds, the callback is executed
setTimeout(() => {
const data = `Data from ${url}`;
callback(null, data);
}, 2000);
}
downloadData('http://example.com', (err, data) => {
if (err) {
console.error('Error:', err);
return;
}
console.log(data); // Data from http://example.com
});
Promises
Promises are a more modern way to handle asynchronous operations in JavaScript. A Promise is an object that holds the eventual completion (or failure) of an asynchronous operation and its resulting value.
const promise = new Promise((resolve, reject) => {
// some asynchronous operation here
// When the operation is done successfully, we call resolve(result)
// If an error happens, call reject(error)
});
promise.then(
result => { /* handle a successful result */ },
error => { /* handle an error */ }
);
Let’s have a look at a real world example:
const promise_success = new Promise((resolve, reject) => {
// Simulating an operation with a timer
setTimeout(() => {
resolve('Operation successful!');
}, 2000);
});
const promise_error = new Promise((resolve, reject) => {
// Simulating an operation with a timer
setTimeout(() => {
reject('Operation failed!');
}, 2000);
});
promise_success
.then((message) => console.log(message)) // logs 'Operation successful!'
.catch((error) => console.error(error));
promise_error
.then((message) => console.log(message))
.catch((error) => console.error(error)); // logs 'Operation failed!'
Async/Await
Async/Await is a syntactic sugar on top of Promises that makes asynchronous code look and behave a bit more like synchronous code. This can make your code cleaner and easier to understand, especially when you have to deal with chaining multiples promises.
To use the await
keyword inside a function, we need to tag the function as async
.
With async/await
, to handle a potential error, we can use try/catch
and handle the error in the catch block.
async function fetchData(url) {
try {
let response = await fetch(url); // <-- await for the response from the network request
let data = await response.json(); // <-- await for the parsed result of the response
console.log(data); // <-- Now we can use the JSON data
} catch (error) {
console.error('Error:', error); // <-- If any of the awaited operations fail, we handle the error here
}
}
fetchData('http://example.com');
Wrapping up
Mastering JavaScript is your first step towards becoming proficient in React Native.
With a solid understanding of JavaScript, you’ll find learning and working with React Native much more comfortable and enjoyable. We hope this guide has been helpful in your journey!
If you want to learn about the ins and outs of JavaScript, I gladly recommand you to read the book “You Don’t Know JS Yet” by Kyle Simpson. It is available on Amazon and Github.
For more on JavaScript and React Native, you might find these articles helpful: