JavaScript for RPG/IBMi Devs

Photo by Growtika on Unsplash

JavaScript for RPG/IBMi Devs

Part - 1: Basics and Data Types

  1. 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.

  2. 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.

  3. RPG and JavaScript

    Here are some similarities and differences between the program lifecycles of RPG (Report Program Generator) and JavaScript:

    Similarities:

    1. Initialization: Both RPG and JavaScript programs go through an initialization phase where resources are allocated, variables are initialized, and necessary setup tasks are performed.

    2. 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.

    3. 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.

    4. 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.

    5. Sequential Execution: Both RPG and JavaScript programs typically execute their instructions sequentially from start to finish, following the order defined in the program.

    6. 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:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  1. Overview of JavaScript Data Types

    JavaScript supports the following primitive data types:

    1. Number: Represents numeric values, including integers and floating-point numbers.

      let index = 10; 
      let value = 24.546;
      const fixedsum = 22;
      
    2. String: Represents a sequence of characters, enclosed in single or double quotes.

      let name = "John Doe";
      
    3. Boolean: Represents the logical values true and false.

      let isValid = true;
      
    4. Null: Represents the intentional absence of any object value.

      let cartValue = null;
      
    5. Undefined: Represents a variable that has been declared but has not been assigned a value.

      let apple = undefined;
      
    6. 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:

  1. Object: Represents a collection of key-value pairs. Objects can contain properties and methods. Examples include objects created using object literals {}, the new keyword, or built-in types like Date, Array, and RegExp.

    let obj = new Object() 
    let person = { firstName: "John", lastName: "Doe", age: 34}
    
  2. 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']
    
  1. Overview of RPG Data Types: Refrence

    RPG provides various data types for handling data on IBM midrange systems:

    1. Character (CHAR): Used for storing character strings.

    2. Numeric (PACKED or ZONED): Used for storing decimal numbers. Packed decimal fields have each digit stored in a half-byte.

    3. Binary (BINARY): Used for working with binary numbers.

    4. Integer (INT): Used for storing whole numbers.

    5. Date (DATE): Used for storing dates.

    6. Time (TIME): Used for storing time values.

    7. Timestamp (TIMESTAMP): Used for storing date and time values together.

    8. INDICATOR (IND): Used for representing boolean values.

Comparison of Common Data Types: RPG JS

  1. Number:

    dcl-s price packed(9:2) inz(19.99);
    
    let price = 19.99;
    
  2. String:

    dcl-s name char(50) inz('John Doe');
    
    let name = 'John Doe';
    
  3. Boolean:

    dcl-s Ind1 ind inz(*on) ;
    
    let isActive = true;
    
  4. Date & Time:

    dcl-s today date inz(*date); 
    dcl-s currentTime time inz(*time);
    
       let today = new Date();
    

    Detailed reference for dates

  5. 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
      

Type Coercion:

  1. 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.

  2. 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:

  1. 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
      
  2. 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
      
  3. 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 be undefined).

    • 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.

Free format RPG refrence

How JS works internally

Did you find this article valuable?

Support GajenderTyagi by becoming a sponsor. Any amount is appreciated!