Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

JavaScript Fundamentals

Getting Started

JavaScript is a programming language that allows you to add logic and interactivity to your PDF documents. While the previous chapter touched on JavaScript's history, this chapter focuses on the core language features you'll need to write effective scripts in Revu. Think of JavaScript as a set of instructions that tell Revu what to do - whether that's calculating form field values, validating user input, or responding to button clicks.

Comments

Before diving into code, let's start with comments. Comments are notes you write for yourself or other developers that JavaScript ignores when running. They're essential for documenting what your code does.

// This is a single-line comment

/* 
   This is a multi-line comment
   that can span several lines.
   Use it for longer explanations.
*/

Variables and Data Types

Variables are containers that store values you can use throughout your script. In JavaScript, you declare variables using var:

var userName = "John Doe"
var pageCount = 10
var isComplete = false

JavaScript has several fundamental data types:

Strings

Strings represent text and are enclosed in either double quotes or single quotes:

var firstName = "Jane"
var lastName = 'Smith'
var fullName = firstName + " " + lastName  // Results in "Jane Smith"

Common string operations:

var text = "Hello World"
var length = text.length           // 11
var upper = text.toUpperCase()     // "HELLO WORLD"
var lower = text.toLowerCase()     // "hello world"
var partial = text.substring(0, 5) // "Hello"

Numbers

Numbers in JavaScript can be integers or decimals:

var quantity = 42
var price = 19.99
var total = quantity * price  // 839.58

Common number operations:

var x = 10
var y = 3
var sum = x + y         // 13
var difference = x - y  // 7
var product = x * y     // 30
var quotient = x / y    // 3.333...
var remainder = x % y   // 1 (modulo operation)

JavaScript provides the Math object for more complex operations:

var rounded = Math.round(3.7)    // 4
var floored = Math.floor(3.7)    // 3
var ceiling = Math.ceil(3.2)     // 4
var absolute = Math.abs(-5)      // 5
var power = Math.pow(2, 3)       // 8
var squareRoot = Math.sqrt(16)   // 4

Booleans

Booleans represent true or false values:

var isEnabled = true
var isVisible = false
var isGreater = 10 > 5  // true

Arrays

Arrays store ordered lists of values:

var colors = ["red", "green", "blue"]
var firstColor = colors[0]     // "red"
var arrayLength = colors.length // 3

// Adding elements
colors.push("yellow")           // Adds to end
colors.unshift("purple")        // Adds to beginning

// Removing elements
var lastItem = colors.pop()     // Removes and returns last item
var firstItem = colors.shift()  // Removes and returns first item

Objects

Objects store collections of key-value pairs:

var person = {
    name: "Alice",
    age: 30,
    email: "alice@example.com"
}

var personName = person.name    // "Alice"
person.age = 31                 // Updates age
person.city = "Seattle"         // Adds new property

Null and Undefined

These special values represent the absence of a value:

var emptyValue = null      // Explicitly empty
var notYetDefined          // undefined (declared but not assigned)

Operators

Comparison Operators

Used to compare values and return boolean results:

var a = 5
var b = 10

a == b   // false (equal to)
a != b   // true (not equal to)
a < b    // true (less than)
a > b    // false (greater than)
a <= b   // true (less than or equal to)
a >= b   // false (greater than or equal to)

Note the difference between == and ===:

5 == "5"   // true (loose equality, converts types)
5 === "5"  // false (strict equality, checks type and value)

Logical Operators

Used to combine or modify boolean values:

var x = true
var y = false

x && y   // false (AND - both must be true)
x || y   // true (OR - at least one must be true)
!x       // false (NOT - inverts the value)

Control Flow

If Statements

Execute code based on conditions:

var score = 85

if (score >= 90) {
    console.println("Excellent!")
} else if (score >= 70) {
    console.println("Good job!")
} else {
    console.println("Keep practicing")
}

Switch Statements

Useful when comparing a single value against multiple cases:

var day = "Monday"

switch (day) {
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
    case "Friday":
        console.println("Weekday")
        break
    case "Saturday":
    case "Sunday":
        console.println("Weekend")
        break
    default:
        console.println("Invalid day")
}

For Loops

Repeat code a specific number of times:

// Count from 0 to 4
for (var i = 0; i < 5; i++) {
    console.println("Count: " + i)
}

// Loop through an array
var items = ["apple", "banana", "orange"]
for (var j = 0; j < items.length; j++) {
    console.println(items[j])
}

While Loops

Repeat code while a condition is true:

var counter = 0
while (counter < 3) {
    console.println("Counter: " + counter)
    counter++
}

Break and Continue

Control loop execution:

// Break exits the loop entirely
for (var i = 0; i < 10; i++) {
    if (i === 5) {
        break  // Stops at 5
    }
    console.println(i)
}

// Continue skips to the next iteration
for (var j = 0; j < 5; j++) {
    if (j === 2) {
        continue  // Skips 2
    }
    console.println(j)  // Prints 0, 1, 3, 4
}

Functions

Functions are reusable blocks of code that perform specific tasks:

// Function declaration
function calculateArea(width, height) {
    return width * height
}

// Using the function
var area = calculateArea(10, 5)  // 50

Functions can also be assigned to variables:

var multiply = function(a, b) {
    return a * b
}

var result = multiply(3, 4)  // 12

Functions don't always need to return values:

function displayMessage(message) {
    console.println("Message: " + message)
    // No return statement
}

displayMessage("Hello")  // Prints but returns undefined

Type Conversion

JavaScript automatically converts types in certain situations, but you can also explicitly convert:

// String to Number
var str = "42"
var num = Number(str)        // 42
var num2 = parseInt(str)     // 42
var float = parseFloat("3.14") // 3.14

// Number to String
var n = 100
var s = String(n)            // "100"
var s2 = n.toString()        // "100"

// To Boolean
var b1 = Boolean(1)          // true
var b2 = Boolean(0)          // false
var b3 = Boolean("text")     // true
var b4 = Boolean("")         // false

Error Handling

Protect your code from errors using try-catch blocks:

try {
    // Code that might cause an error
    var result = riskyOperation()
} catch (e) {
    // Handle the error
    console.println("An error occurred: " + e.message)
}

Scope

Variables have scope, which determines where they can be accessed:

var globalVar = "I'm global"  // Available everywhere

function myFunction() {
    var localVar = "I'm local"  // Only available in this function
    console.println(globalVar)  // Can access global
    console.println(localVar)   // Can access local
}

myFunction()
// console.println(localVar)  // Would cause an error - not accessible here

Best Practices

As you begin writing JavaScript for your PDFs, keep these guidelines in mind:

  1. Use meaningful variable names: Instead of var t = 10, use var pageWidth = 10

  2. Initialize variables: Always give variables an initial value when possible

  3. Be consistent with quotes: Pick either single or double quotes for strings and stick with it

  4. Handle edge cases: Consider what happens if a variable is null or undefined

  5. Keep functions focused: Each function should do one thing well

  6. Comment complex logic: If something isn't immediately obvious, add a comment

  7. Test incrementally: Test your code as you write it, don't wait until everything is done

Common Pitfalls

Watch out for these common mistakes:

// Forgetting var creates a global variable (avoid this)
myVariable = 10  // Bad
var myVariable = 10  // Good

// Comparing with = instead of ==
if (x = 5) {  // This assigns 5 to x
    // Wrong!
}
if (x == 5) {  // This compares x to 5
    // Correct
}

// Forgetting that arrays start at 0
var items = ["first", "second", "third"]
var lastItem = items[3]  // undefined - should be items[2]

Moving Forward

This chapter covered the fundamental building blocks of JavaScript. You now know how to work with different data types, control program flow, and create reusable functions. These concepts form the foundation for everything you'll do with JavaScript in Revu.

In the next chapter, we'll explore where and how you can use these JavaScript fundamentals within your PDF documents, examining the different contexts where Revu executes JavaScript code.