JavaScript for RPG/IBMi Devs
Introduction:
In this blog post, we will explore the similarities and differences between JavaScript and RPG. While the initial part of this post will cover the basics of both languages and their data types, subsequent articles in this series will delve into more detail with code snippets and learning resources.Since this blog post is primarily aimed at RPG developers and shops, I assume you have a good understanding of RPG and the IBM i OS. My goal is to teach JavaScript by highlighting the similarities between the two languages.
The main reason for considering JavaScript as an alternative language is its ease of learning and its applicability in both frontend and backend applications. With the help of Node.js, JavaScript can be seamlessly executed in the backend, making tasks like JSON handling and API calls faster and more straightforward compared to RPG. By leveraging tools like itoolkit, we can easily integrate RPG and JavaScript programs, allowing each language to excel in its respective strengths.
History of JavaScript
JavaScript was created by Brendan Eich at Netscape in 1995. It was initially developed as a scripting language for web browsers to provide interactive features and enhance user experience on websites. JavaScript quickly gained popularity with the rise of the internet and became a fundamental technology for web development.
However, with the introduction of Node.js in 2009, JavaScript gained the ability to run on the server side as well, expanding its usage beyond the browser and enabling full-stack JavaScript development.RPG and JavaScript
Here are some similarities and differences between the program lifecycles of RPG (Report Program Generator) and JavaScript:
Similarities:
Initialization: Both RPG and JavaScript programs go through an initialization phase where resources are allocated, variables are initialized, and necessary setup tasks are performed.
Execution: Once initialized, both RPG and JavaScript programs move into the execution phase, where the main logic of the program is executed. This phase involves processing statements, performing calculations, and manipulating data.
Control Structures: Both languages support control structures such as loops (for, while) and conditional statements (if-else, switch). These structures allow for branching and repetition based on certain conditions.
Data Manipulation: Both RPG and JavaScript provide capabilities for working with data, including variables, arrays, and data structures. They support operations such as data input, processing, transformations, and output.
Sequential Execution: Both RPG and JavaScript programs typically execute their instructions sequentially from start to finish, following the order defined in the program.
Error Handling: Both languages provide mechanisms for handling errors and exceptions that may occur during program execution. Error handling techniques, such as exception handling or try-catch blocks, can be used in both RPG and JavaScript to handle and recover from runtime errors.
Differences:
Execution Environment: RPG programs are primarily executed on IBM midrange systems (such as IBM i) within a specific runtime environment, whereas JavaScript programs are executed in various environments, including web browsers, server-side with Node.js, and embedded in other applications.
Language Paradigm: RPG is primarily a procedural language, focusing on sequential processing with cycle-based program flow. In contrast, JavaScript is a multi-paradigm language that supports procedural, object-oriented, and functional programming styles.
Event-Driven Nature: JavaScript is often used for developing event-driven applications, where program execution is triggered by user actions or events. JavaScript programs typically respond to user interactions, such as button clicks or form submissions, and update the user interface dynamically.
Asynchronous Operations: JavaScript excels at handling asynchronous operations, such as making HTTP requests or performing I/O operations, through techniques like callbacks, promises, and async/await. RPG, on the other hand, is primarily focused on business processing and has fewer built-in asynchronous capabilities.
Front-End vs. Back-End: JavaScript is commonly used on the front-end of web applications, interacting with the user interface and providing dynamic behavior. RPG is typically used on the back-end, handling business logic, data processing, and integration with databases and other systems.
Development Tools and Ecosystem: JavaScript benefits from a vast ecosystem of libraries, frameworks (e.g., React, Angular), and development tools, enabling rapid development and access to a wide range of resources. RPG has a more limited ecosystem, primarily tailored for IBM midrange systems, with a focus on database integration and business application development.
Overview of JavaScript Data Types
JavaScript supports the following primitive data types:
Number: Represents numeric values, including integers and floating-point numbers.
let index = 10; let value = 24.546; const fixedsum = 22;
String: Represents a sequence of characters, enclosed in single or double quotes.
let name = "John Doe";
Boolean: Represents the logical values
true
andfalse
.let isValid = true;
Null: Represents the intentional absence of any object value.
let cartValue = null;
Undefined: Represents a variable that has been declared but has not been assigned a value.
let apple = undefined;
Symbol (introduced in ECMAScript 2015): Represents a unique identifier. Symbols are often used as keys in objects to ensure uniqueness.
let greet = Symbol("Hello, Welcome!")
Non-Primitive (Reference) Data Types:
Object: Represents a collection of key-value pairs. Objects can contain properties and methods. Examples include objects created using object literals
{}
, thenew
keyword, or built-in types likeDate
,Array
, andRegExp
.let obj = new Object() let person = { firstName: "John", lastName: "Doe", age: 34}
Array: Represents an ordered list of values. Arrays can contain elements of any data type and are created using square brackets
[]
.let arr = new Array() let myCars = ['FORD, 'BMW', 'TATA', 'MAHINDRA']
Overview of RPG Data Types: Refrence
RPG provides various data types for handling data on IBM midrange systems:
Character (CHAR): Used for storing character strings.
Numeric (PACKED or ZONED): Used for storing decimal numbers. Packed decimal fields have each digit stored in a half-byte.
Binary (BINARY): Used for working with binary numbers.
Integer (INT): Used for storing whole numbers.
Date (DATE): Used for storing dates.
Time (TIME): Used for storing time values.
Timestamp (TIMESTAMP): Used for storing date and time values together.
INDICATOR (IND): Used for representing boolean values.
Comparison of Common Data Types: RPG JS
Number:
dcl-s price packed(9:2) inz(19.99);
let price = 19.99;
String:
dcl-s name char(50) inz('John Doe');
let name = 'John Doe';
Boolean:
dcl-s Ind1 ind inz(*on) ;
let isActive = true;
Date & Time:
dcl-s today date inz(*date); dcl-s currentTime time inz(*time);
let today = new Date();
Null and Undefined:
- RPG: Does not have specific null or undefined values. Instead, variables are initialized with default values or are blank.
let some = null let something = undefined
- RPG: Does not have specific null or undefined values. Instead, variables are initialized with default values or are blank.
Type Coercion:
JavaScript:
JavaScript performs automatic type coercion in certain situations. It attempts to convert the types to make comparisons.
Type coercion can lead to unexpected results. It's recommended to use strict equality operators (
===
and!==
) to avoid coercion issues.
RPG:
RPG requires explicit type conversions using built-in functions or specifications.
Functions like
%CHAR
and%DEC
is used for converting between different data types.
Defining Variables in JavaScript:
In JavaScript, there are three keywords used to define variables: let
, const
, and var
. Each keyword has its characteristics and best practices for usage. Here's an overview of let
, const
, and var
:
let:
Variables defined with
let
have block scope, meaning they are only accessible within the block (enclosed by curly braces) where they are defined.let
allows you to declare variables that can be reassigned with a new value.Variables defined with
let
are not accessible before they are declared (known as the "temporal dead zone").Example:
let age = 25; age = 30; // Reassignment is allowed
const:
Variables defined with
const
also have block scope.const
is used to declare variables that cannot be reassigned once they are assigned a value. The assigned value remains constant.It's important to note that
const
does not make the variable itself immutable, but rather prevents reassignment of the variable.const
variables must be assigned a value during declaration.Example:
const pi = 3.14; // pi = 3.14159; // This would result in an error
var:
Variables defined with
var
have function scope or global scope (if defined outside any function).var
variables are hoisted, which means they can be accessed and assigned values before they are declared (although the assigned value will beundefined
).var
allows redeclaration and reassignment within its scope.Example:
var name = 'John'; var name = 'Jane'; // Redeclaration is allowed
In modern JavaScript, it is generally recommended to use let
and const
over var
due to their more predictable scoping behavior and better block-level scope control. const
should be used for variables that do not need to be reassigned, while let
should be used for variables that require reassignment.
It's worth mentioning that variable scoping and behavior differ between let
, const
, and var
. Understanding these differences will help you write more maintainable and error-free JavaScript code.
Subscribe to my newsletter
Read articles from Gajender Tyagi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Gajender Tyagi
Gajender Tyagi
Software Development Engineer -2 of Open Source technologies @eradani-inc