🟨
Coding🎓 Ages 14-18Beginner 12 min read

JavaScript Variables and Functions

A teen-friendly JavaScript tutorial on variables and functions: declare with let and const, work with strings and numbers, write and call functions, use parameters and return values, with runnable code and a quiz.

Key takeaways

  • Use let for values that change and const for values that should not
  • Variables hold data like numbers, strings and true/false (booleans)
  • A function is a named, reusable block of code you call by its name
  • Parameters pass information into a function; return sends a value back out
  • Template literals with backticks make it easy to build strings from variables

Why variables and functions matter

Variables and functions are the two ideas you'll use in almost every line of JavaScript you ever write. Variables store information; functions package up actions so you can reuse them. Master these two and the rest of the language falls into place much faster.

JavaScript runs in every web browser, so you can try every example here in your browser's developer console (press F12, then click "Console") with no setup at all.

Declaring variables with let and const

A variable is a named container for a value. In modern JavaScript you create one with let or const:

let score = 0;
const playerName = "Sam";

console.log(score);        // 0
console.log(playerName);   // Sam

The difference is simple but important:

  • let is for values that will change. You can reassign it later.
  • const is for values that should stay the same. Trying to reassign it causes an error.
let score = 0;
score = score + 10;   // ✅ allowed, score is now 10

const playerName = "Sam";
playerName = "Alex";  // ❌ error! const cannot be reassigned

The rule of thumb: use const by default, and switch to let only when you know the value needs to change. This makes your code safer because it prevents accidental changes.

Types of values

Variables can hold different kinds of data. The three you'll meet first are:

TypeExampleMeaning
number42, 3.14numbers, whole or decimal
string"hello"text, in quotes
booleantrue, falseyes/no, on/off values
const age = 16;            // number
const city = "Madrid";     // string
const isStudent = true;    // boolean

JavaScript figures out the type automatically from the value you give it.

Doing things with variables

You can combine and change variables. Numbers use the usual math operators:

let a = 8;
let b = 3;

console.log(a + b);   // 11
console.log(a * b);   // 24
console.log(a % b);   // 2  (the remainder of 8 ÷ 3)

Strings join together with +, but the cleanest way to build text from variables is a template literal — a string in backticks (` `) with ${...}` placeholders:

const name = "Sam";
const points = 50;

console.log(`Hi ${name}, you have ${points} points!`);
// Hi Sam, you have 50 points!

Each ${...} is replaced by the value inside it. This is far easier to read than gluing strings with lots of + signs.

What is a function?

A function is a named block of code that does a job. You write it once, give it a name, and then call it whenever you need that job done. This saves you from copying the same code again and again — the same reason functions matter in Functions Explained.

Here is the simplest possible function:

function sayHello() {
    console.log("Hello!");
}

sayHello();   // Hello!
sayHello();   // Hello!

Two parts to notice:

  1. Defining the function: function sayHello() { ... } describes what it does but does not run it yet.
  2. Calling the function: sayHello() actually runs the code inside. We called it twice, so "Hello!" prints twice.

Parameters: passing information in

A function becomes far more useful when you can give it inputs. These inputs are called parameters. You list them in the parentheses, and they act like variables inside the function.

function greet(name) {
    console.log(`Hello, ${name}!`);
}

greet("Sam");    // Hello, Sam!
greet("Alex");   // Hello, Alex!

Here name is a parameter. When you call greet("Sam"), the value "Sam" is copied into name, and the function uses it. One function, many different greetings.

You can have more than one parameter:

function addPoints(name, points) {
    console.log(`${name} now has ${points} points.`);
}

addPoints("Sam", 50);    // Sam now has 50 points.
addPoints("Alex", 30);   // Alex now has 30 points.

Return: sending a value back

So far our functions just printed things. Often you want a function to calculate something and hand the result back. That's what return does.

function add(a, b) {
    return a + b;
}

const total = add(4, 5);
console.log(total);    // 9

Let's trace it:

  1. add(4, 5) runs with a = 4 and b = 5.
  2. return a + b sends back 9 to wherever the function was called.
  3. That 9 is stored in total.
  4. console.log(total) prints 9.

The key difference: console.log shows a value on screen; return gives a value back to your code so you can store it, reuse it, or pass it into another function. A function stops running the moment it hits return.

A worked example: a tip calculator

Let's combine everything into a small, real example — a function that works out a restaurant tip.

function calculateTip(bill, percent) {
    const tip = bill * (percent / 100);
    return tip;
}

const myBill = 40;
const myTip = calculateTip(myBill, 15);

console.log(`Bill: $${myBill}`);
console.log(`Tip: $${myTip}`);
console.log(`Total: $${myBill + myTip}`);

Step by step:

  • calculateTip takes two parameters: the bill and the tip percent.
  • Inside, it stores the calculated tip in a const and returns it.
  • We call it with a $40 bill and 15%, getting 6 back into myTip.
  • Template literals build friendly output lines.

Output:

Bill: $40
Tip: $6
Total: $46

Because the logic lives in a function, you can reuse it for any bill and any percentage just by calling it again with different numbers.

A quick note on arrow functions

You'll often see a shorter way to write functions, called arrow functions. This does the same job as our add function:

const add = (a, b) => a + b;

console.log(add(4, 5));   // 9

It's just a more compact style. Both forms take parameters and return a value — choose whichever reads more clearly to you for now.

Try it yourself

  1. Square it: Write a function square(n) that returns n * n. Test it with square(6) (should be 36).
  2. Greeting builder: Write makeGreeting(name, time) that returns a string like "Good morning, Sam!" using a template literal.
  3. Average: Write average(a, b, c) that returns the average of three numbers. Remember to divide by 3.
  4. const vs let: Take the tip calculator and try changing a const after it's set. Watch the error, then decide whether let or const is correct for each variable.

Challenge: write a function convertTemp(celsius) that returns the temperature in Fahrenheit (celsius * 9 / 5 + 32), then call it for several temperatures and print each with a template literal. Once you're comfortable, the next step is to connect functions to buttons on a web page — see JavaScript and the DOM to make your functions react to clicks.

Quick quiz

Test yourself and earn XP

Which keyword declares a variable whose value should NOT change?

What does this print? ``` let x = 5; x = x + 3; console.log(x); ```

In `function greet(name) { ... }`, what is `name`?

What does `return` do inside a function?

What does `` `Hi, ${name}!` `` produce when name is 'Sam'?

FAQ

Prefer const. Reach for it whenever a value won't be reassigned, because it makes your intent clear and prevents accidental changes. Use let only when you genuinely need to change the value later.

console.log just displays a value on the screen for you to see. return hands a value back to the code that called the function so it can be stored or reused. They solve different problems.