First Principles
Math & Statistics

Simple Linear Regression

A step-by-step walkthrough of simple linear regression — calculating slope, intercept, and R² with a practical dataset and a JavaScript implementation.

By Fadjar Rafi. Published 21 Oct 2025. 6 min read.

Contents
  1. What Linear Regression Is For
  2. Calculating Linear Regression
  3. Classical Assumptions of Linear Regression
  4. Testing the Fit with R²

How does a company decide how much to spend on advertising, or an agent price a house? Often the tool behind the decision is simple linear regression — a way to describe and predict the relationship between two variables. Think of it as finding the thread that ties advertising spend (xx) to sales (yy).

Mathematically, that relationship looks like this:

y=β0+β1x+εy = \beta_0 + \beta_1 x + \varepsilon

Where:

SymbolMeaning
xxIndependent variable
yyDependent variable
β₀Intercept (value of yy when xx = 0)
β₁Slope (how much yy changes for each unit change in xx)
εError term

What Linear Regression Is For#

It does two jobs:

  1. Verify a relationship — prove statistically whether two variables are actually related, and measure how strong that link is. Does education level really affect income?
  2. Predict — estimate future values from past data. If we raise the ad budget by xx, how much more do we sell (yy)?

Calculating Linear Regression#

Say we want the relationship between advertising cost (xx) and sales (yy), with this data:

Advertising CostUnits
100500
200700
300900
4001100
5001300

To fit the line we need two numbers: the slope β1\beta_1 and the intercept β0\beta_0.

Calculating the Slope (β1\beta_1)#

The slope is how much yy moves for each change in xx:

β1=∑(xi−xˉ)(yi−yˉ)∑(xi−xˉ)2\beta_1 = \frac{\sum(x_i - \bar{x})(y_i - \bar{y})}{\sum(x_i - \bar{x})^2}

Where:

SymbolMeaning
xix_iIndividual values of the independent variable
yiy_iIndividual values of the dependent variable
xˉ\bar{x}Mean of the independent variable
yˉ\bar{y}Mean of the dependent variable

Start with the two means:

xˉ=(100+200+300+400+500)/5=300\bar{x} = (100 + 200 + 300 + 400 + 500) / 5 = 300 yˉ=(500+700+900+1100+1300)/5=900\bar{y} = (500 + 700 + 900 + 1100 + 1300) / 5 = 900

Now the numerator — each (xi−xˉ)(yi−yˉ)(x_i - \bar{x})(y_i - \bar{y}):

(100−300)(500−900)=(−200)(−400)=80,000(100 - 300)(500 - 900) = (-200)(-400) = 80,000 (200−300)(700−900)=(−100)(−200)=20,000(200 - 300)(700 - 900) = (-100)(-200) = 20,000 (300−300)(900−900)=(0)(0)=0(300 - 300)(900 - 900) = (0)(0) = 0 (400−300)(1100−900)=(100)(200)=20,000(400 - 300)(1100 - 900) = (100)(200) = 20,000 (500−300)(1300−900)=(200)(400)=80,000(500 - 300)(1300 - 900) = (200)(400) = 80,000

Total=200,000\text{Total} = 200,000

And the denominator — each (xi−xˉ)2(x_i - \bar{x})^2:

(100−300)2=(−200)2=40,000(100 - 300)^2 = (-200)^2 = 40,000 (200−300)2=(−100)2=10,000(200 - 300)^2 = (-100)^2 = 10,000 (300−300)2=(0)2=0(300 - 300)^2 = (0)^2 = 0 (400−300)2=(100)2=10,000(400 - 300)^2 = (100)^2 = 10,000 (500−300)2=(200)2=40,000(500 - 300)^2 = (200)^2 = 40,000

Total=100,000\text{Total} = 100,000 β1=200,000/100,000=2\beta_1 = 200,000 / 100,000 = 2

A slope of 2 means every extra unit of cost (xx) brings 2 more units of sales (yy).

Calculating the Intercept (β0\beta_0)#

With the slope in hand, the intercept is:

β0=yˉ−β1xˉ\beta_0 = \bar{y} - \beta_1\bar{x}

Where:

SymbolMeaning
yˉ\bar{y}Mean of the dependent variable
xˉ\bar{x}Mean of the independent variable
β1\beta_1Slope

β0=900−(2×300)\beta_0 = 900 - (2 × 300) β0=300\beta_0 = 300

So when advertising cost is 0, predicted sales are 300 units. Put the slope and intercept together and we get the regression line:

y=300+2xy = 300 + 2x

To predict, just plug in a value. How many sales from spending 250 on ads?

y=300+2(250)=300+500=800y = 300 + 2(250) = 300 + 500 = 800

So 250 in ad spend predicts 800 units. Plotted, the line and the five data points look like this:

Scatter plot of advertising cost vs units sold with the fitted line y = 300 + 2x; all five points sit on the line, and x = 250 predicts y = 800

Here's the same calculation as a program:

// Sales and advertising data
const sales_data = {
    advertising_cost: [100, 200, 300, 400, 500],
    units_sold: [500, 700, 900, 1100, 1300]
};

// Calculate average of array
function calculate_mean(data) {
    return data.reduce((total, value) => total + value, 0) / data.length;
}

// Calculate slope (β₁) from data
function calculate_slope(data) {
    const mean_x = calculate_mean(data.advertising_cost);
    const mean_y = calculate_mean(data.units_sold);
    
    let numerator = 0;
    let denominator = 0;
    
    // Calculate numerator and denominator for slope formula
    for (let i = 0; i < data.advertising_cost.length; i++) {
        const diff_x = data.advertising_cost[i] - mean_x;
        const diff_y = data.units_sold[i] - mean_y;
        
        numerator += diff_x * diff_y;
        denominator += diff_x * diff_x;
    }
    
    return numerator / denominator;
}

// Calculate intercept (β₀) from data
function calculate_intercept(data, slope) {
    const mean_x = calculate_mean(data.advertising_cost);
    const mean_y = calculate_mean(data.units_sold);
    
    return mean_y - (slope * mean_x);
}

// Predict units sold based on advertising cost
function predict_sales(advertising_cost, slope, intercept) {
    return intercept + (slope * advertising_cost);
}

// Calculate regression
const slope = calculate_slope(sales_data);
const intercept = calculate_intercept(sales_data, slope);

// Display results
console.log(`Slope (β₁): ${slope}`); // output: 2
console.log(`Intercept (β₀): ${intercept}`); // output: 300

// Example prediction
const new_cost = 250;
const prediction = predict_sales(new_cost, slope, intercept);
console.log(`${prediction} units`);

Classical Assumptions of Linear Regression#

Regression only holds up if a few assumptions do. Worth checking before you trust the result:

  1. Linearity. The relationship between xx and yy should be roughly a straight line. A scatter plot is the quick check — if the points curve instead, transform the data first (a log or square root often helps).
  2. Independence. Each observation should stand on its own. This bites most with time-series data: today's sales shouldn't depend on yesterday's. Autocorrelation (checked with an ACF plot or the Durbin-Watson test) biases the results.
  3. Homoscedasticity. The spread of the errors should stay constant across all values of xx — prediction error shouldn't be tiny for cheap ad spend and huge for expensive. Plot the residuals against predicted values; a funnel shape means the assumption fails.
  4. Normality. The residuals should follow a normal distribution — a symmetrical bell when you histogram them. This matters most for hypothesis tests and confidence intervals. Check with a Q-Q plot, or a formal test like Shapiro-Wilk.

Testing the Fit with R²#

How well does the line actually explain the data? That's what the coefficient of determination, R2R^2, measures:

R2=1−∑(yi−yi^)2∑(yi−yˉ)2R^2 = 1 - \frac{\sum(y_i - \hat{y_i})^2}{\sum(y_i - \bar{y})^2}

Where:

SymbolMeaning
yiy_iActual value
yi^\hat{y_i}Predicted value
yˉ\bar{y}Mean of actual values

R2R^2 runs from 0 to 1 and tells you the share of the variation in yy the model captures — multiply by 100 to read it as a percentage. To compute it, we need the predicted values, the total sum of squares, and the residual sum of squares.

Predicted Values (yi^\hat{y_i})#

Run each xx through y=300+2xy = 300 + 2x:

Advertising Cost (xx)Units (yy)y^\hat{y} (predicted)
100500300 + 2(100) = 500
200700300 + 2(200) = 700
300900300 + 2(300) = 900
4001100300 + 2(400) = 1100
5001300300 + 2(500) = 1300

Total Sum of Squares (SStotalSS_{total})#

This is the spread of the actual values around their mean, ∑(yi−yˉ)2\sum(y_i - \bar{y})^2:

(500−900)2=(−400)2=160,000(500 - 900)^2 = (-400)^2 = 160,000 (700−900)2=(−200)2=40,000(700 - 900)^2 = (-200)^2 = 40,000 (900−900)2=0(900 - 900)^2 = 0 (1100−900)2=(200)2=40,000(1100 - 900)^2 = (200)^2 = 40,000 (1300−900)2=(400)2=160,000(1300 - 900)^2 = (400)^2 = 160,000 SStotal=400,000SS_{total} = 400,000

Residual Sum of Squares (SSresidualSS_{residual})#

This is what the model misses — the gap between actual and predicted, ∑(yi−yi^)2\sum(y_i - \hat{y_i})^2:

(500−500)2=0(500 - 500)^2 = 0 (700−700)2=0(700 - 700)^2 = 0 (900−900)2=0(900 - 900)^2 = 0 (1100−1100)2=0(1100 - 1100)^2 = 0 (1300−1300)2=0(1300 - 1300)^2 = 0 SSresidual=0SS_{residual} = 0

Putting It Together#

R2=1−SSresidualSStotal=1−0400,000=1R^2 = 1 - \frac{SS_{residual}}{SS_{total}} = 1 - \frac{0}{400,000} = 1

An R2R^2 of 1 means:

  1. the model explains 100% of the variation in the data,
  2. every point lies exactly on the line, and
  3. predictions are perfect for this data.

That happens here because the data is perfectly linear — every residual is zero. Real-world data almost never lands this cleanly. Here's the calculation in code:

// Calculate coefficient of determination (R²)
function calculate_r_squared(data, slope, intercept) {
    const mean_y = calculate_mean(data.units_sold);
    
    let ss_total = 0;  // Sum of squares total
    let ss_residual = 0;  // Sum of squares residual
    
    for (let i = 0; i < data.advertising_cost.length; i++) {
        const y_predicted = intercept + (slope * data.advertising_cost[i]);
        const y_actual = data.units_sold[i];
        
        ss_total += Math.pow(y_actual - mean_y, 2);
        ss_residual += Math.pow(y_actual - y_predicted, 2);
    }
    
    return 1 - (ss_residual / ss_total);
}

// Usage
const r_squared = calculate_r_squared(sales_data, slope, intercept);
console.log(`R² (Coefficient of Determination): ${r_squared.toFixed(4)}`); // Output: 1.0000