> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wizflow.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Variables

> Create dynamic values from chatflow responses, trigger outputs, and data models

Variables enable dynamic computation and data transformation, acting like spreadsheet formulas that calculate values in real-time based on user responses and other data sources. Transform, calculate, and derive new values from existing data without requiring server-side processing.

<video src="https://mintcdn.com/dreamplan-d87d53ea/viRt_XlW91kdGh5Z/resources/pr-5297-variables-support.mp4?fit=max&auto=format&n=viRt_XlW91kdGh5Z&q=85&s=8c3d1de81f6cfe791418c9f859612d1b" controls width="720" data-path="resources/pr-5297-variables-support.mp4" />

## How Variables Work

<CardGroup cols={2}>
  <Card title="Real-time Evaluation" icon="bolt">
    Variables update instantly as users provide responses, enabling dynamic content and calculations throughout your chatflow.
  </Card>

  <Card title="Aliases & Expressions" icon="code">
    Create readable names for data sources, then write JavaScript expressions using these aliases to perform calculations.
  </Card>

  <Card title="Chaining Capability" icon="link">
    Variables can reference other variables, enabling complex multi-step calculations and data transformations.
  </Card>

  <Card title="Transparent Calculations" icon="eye">
    All calculations are visible and auditable through JavaScript expressions, ensuring complete transparency.
  </Card>
</CardGroup>

## Common Use Cases

<Tabs>
  <Tab title="Mathematical Calculations">
    **Financial Formulas & Computations**

    * Basic arithmetic: `income * 12` for annual salary
    * Advanced math: `Math.pow()`, `Math.sqrt()`, `Math.round()`
    * Financial calculations: loan payments, compound interest, ROI
    * Statistical operations: averages, percentages, ratios

    ```javascript theme={null}
    // Calculate BMI
    weight / (height * height)

    // Monthly loan payment calculation  
    principal * (rate * Math.pow(1 + rate, months)) / (Math.pow(1 + rate, months) - 1)
    ```
  </Tab>

  <Tab title="Text Transformations">
    **String Manipulation & Formatting**

    * Extract first/last names: `userFullName.split(' ')[0]`
    * Case conversion: `.toUpperCase()`, `.toLowerCase()`
    * Text parsing: split strings, extract substrings
    * Data concatenation: combine multiple fields

    ```javascript theme={null}
    // Extract first name for personalization
    userFullName.split(' ')[0]

    // Format phone number display
    `(${phone.slice(0,3)}) ${phone.slice(3,6)}-${phone.slice(6)}`
    ```
  </Tab>

  <Tab title="Conditional Logic">
    **Smart Decision Making**

    * Ternary operators: `age >= 18 ? "adult" : "minor"`
    * Multi-condition evaluations for business rules
    * Risk scoring based on multiple criteria
    * Data validation with fallbacks

    ```javascript theme={null}
    // Age-based eligibility
    age >= 18 ? "eligible" : "requires_guardian"

    // Risk assessment scoring
    (creditScore > 700 ? 50 : 0) + (income > 50000 ? 30 : 0) + (hasAssets ? 20 : 0)
    ```
  </Tab>

  <Tab title="Data Processing">
    **Complex Data Manipulation**

    * Array operations: process lists and extract elements
    * Object manipulation: access nested properties
    * Type conversions: safely convert between data types
    * Data cleaning: remove unwanted characters, normalize formats

    ```javascript theme={null}
    // Calculate total from array of values
    expensesList.reduce((sum, expense) => sum + expense.amount, 0)

    // Clean and format currency
    Math.round(parseFloat(userInput.replace(/[^0-9.-]/g, '')) * 100) / 100
    ```
  </Tab>
</Tabs>

## Variable Editor

### Expression System

Variables use **aliases** connected to **JavaScript expressions**:

<Steps>
  <Step title="Create Aliases">
    Define readable names for your data sources:

    * `userAge` instead of complex resource references
    * `monthlyIncome` for salary responses
    * `creditScore` from external API calls
  </Step>

  <Step title="Write Expressions">
    Use JavaScript with your aliases to create calculations:

    ```javascript theme={null}
    // Simple calculation
    userAge >= 65 ? pensionAmount * 1.2 : pensionAmount

    // Complex financial formula
    Math.min(monthlyIncome * 0.28, (monthlyIncome * 0.36) - monthlyDebt)
    ```
  </Step>

  <Step title="Test & Validate">
    Use the expression tester with mock values to ensure your logic works correctly before deployment.
  </Step>

  <Step title="Deploy & Reference">
    Use your variables throughout the chatflow in messages, conditions, and other variables.
  </Step>
</Steps>

### Editor Features

<CardGroup cols={2}>
  <Card title="Smart Autocompletion" icon="sparkles">
    * **Ctrl+Space** triggers intelligent suggestions
    * Auto-detects available response fields
    * Suggests variable names and functions
    * Context-aware completions
  </Card>

  <Card title="Alias Management" icon="link">
    * Visual mapping of aliases to data sources
    * Automatic detection of undefined aliases
    * Smart suggestions for missing connections
    * Resource browser integration
  </Card>

  <Card title="Expression Testing" icon="flask">
    * Test expressions with mock values
    * Validate complex calculations
    * Debug multi-step logic
    * Preview results before deployment
  </Card>

  <Card title="Error Handling" icon="shield-check">
    * Built-in null checking capabilities
    * Default value support
    * Type validation assistance
    * Runtime error prevention
  </Card>
</CardGroup>

## Where to Use Variables

Variables integrate seamlessly throughout your chatflow:

<Accordion title="Dynamic Content in Messages">
  **Personalized Communication**

  Display calculated values in messages using dynamic content. Perfect for showing personalized results, progress indicators, or calculated recommendations.

  *Example: "Based on your income of \$X, your recommended savings rate is Y%"*
</Accordion>

<Accordion title="Conditional Flow Logic">
  **Smart Branching**

  Use calculated values in conditions to create intelligent flow paths. Enable complex eligibility checks, risk-based routing, and personalized user journeys.

  *Example: Route users to different application processes based on calculated risk scores*
</Accordion>

<Accordion title="Trigger Inputs">
  **External System Integration**

  Pass calculated values to triggers for external processing, API calls, or data storage. Enable complex data transformation before sending to external systems.

  *Example: Send calculated financial metrics to CRM or generate personalized PDF reports*
</Accordion>

<Accordion title="Nested Variable Chains">
  **Complex Multi-Step Calculations**

  Reference other variables to build sophisticated calculation chains. Break complex formulas into manageable, reusable components.

  *Example: Base loan eligibility → Credit risk score → Final approval decision*
</Accordion>

## Real-World Examples

### Financial Services

<CodeGroup>
  ```javascript Loan Eligibility theme={null}
  // Calculate maximum loan amount
  Math.min(
    monthlyIncome * 0.28 * 12 * loanTermYears, 
    (monthlyIncome * 0.36 - monthlyDebt) * 12 * loanTermYears
  )
  ```

  ```javascript Risk Assessment theme={null}
  // Multi-factor risk scoring
  (creditScore >= 750 ? 40 : creditScore >= 650 ? 25 : 10) + 
  (debtToIncomeRatio <= 0.3 ? 30 : debtToIncomeRatio <= 0.4 ? 15 : 5) +
  (yearsAtJob >= 2 ? 20 : 10) + 
  (hasAssets ? 10 : 0)
  ```

  ```javascript Pension Calculation theme={null}
  // Annual pension projection
  currentAge <= 65 ? 
    savingsAmount * Math.pow(1 + returnRate, 65 - currentAge) : 
    savingsAmount * withdrawalRate
  ```
</CodeGroup>

### Health & Insurance

<CodeGroup>
  ```javascript BMI Calculation theme={null}
  // Body Mass Index with classification
  weight / Math.pow(height / 100, 2)
  ```

  ```javascript Insurance Premium theme={null}
  // Age-based premium calculation
  basePremium * (age < 30 ? 0.8 : age < 50 ? 1.0 : age < 65 ? 1.3 : 1.6) *
  (smoker ? 1.5 : 1.0) * (hasConditions ? 1.2 : 1.0)
  ```
</CodeGroup>

## Best Practices

<CardGroup cols={2}>
  <Card title="Descriptive Naming" icon="tag">
    **Use Clear Variable Names**

    Choose names that explain the variable's purpose:

    * `monthlyMortgagePayment` not `payment`
    * `userAgeInYears` not `age`
    * `totalAnnualIncome` not `income`
  </Card>

  <Card title="Error Prevention" icon="shield-exclamation">
    **Handle Edge Cases**

    Include validation and default values:

    ```javascript theme={null}
    // Safe division with fallback
    income > 0 ? expenses / income : 0

    // Null checking
    userName ? userName.trim() : "Guest"
    ```
  </Card>

  <Card title="Modular Design" icon="puzzle-piece">
    **Break Down Complex Logic**

    Create smaller, reusable variables:

    * `grossMonthlyIncome` → `netMonthlyIncome` → `loanEligibility`
    * Build calculation chains step by step
    * Make debugging easier
  </Card>

  <Card title="Documentation" icon="file-text">
    **Document Complex Formulas**

    Use descriptive variable names and comments:

    * Explain business rules and assumptions
    * Document data sources and calculations
    * Include examples of expected inputs/outputs
  </Card>
</CardGroup>

## Performance & Reliability

<Note>
  **Real-time Calculation**

  Variables are calculated instantly as users progress through your chatflow:

  * **Lightweight Processing** - Client-side JavaScript execution
  * **No Server Delays** - Calculations happen in the user's browser
  * **Dynamic Updates** - Values refresh automatically as inputs change
  * **Reliable Performance** - No external dependencies for basic calculations
</Note>

<Warning>
  **Calculation Limitations**

  Variables support standard JavaScript with some restrictions:

  * **Synchronous only** - No async operations or API calls
  * **No function declarations** - Use expressions and built-in functions
  * **Client-side only** - Complex server-side calculations should use triggers
  * **Memory limits** - Very large datasets should be processed server-side
</Warning>

***

## Related Features

<CardGroup cols={2}>
  <Card title="Conditional Logic" href="/features/conditional-logic-routing">
    Use variables in branching logic to create dynamic flow paths
  </Card>

  <Card title="Triggers" href="/features/triggers-automation">
    Pass calculated values to external systems and automations
  </Card>

  <Card title="Entities Overview" href="/features/entities-overview">
    Understanding the data sources available for variable calculations
  </Card>

  <Card title="Calculations" href="/features/calculation">
    Advanced financial calculation capabilities and triggers
  </Card>
</CardGroup>
