JavaScript Fundamentals: Variables, Functions and Loops

JavaScript ~ 35 minutes

# Welcome to JavaScript

Hello and welcome! In this tutorial, we will learn the three basic building blocks of JavaScript: variables, functions and loops. JavaScript is the language that makes web pages come alive. It also runs on servers with Node.js. Learning it opens many doors.

Do not worry if you are new to programming. We will use very simple words and small examples. Each step builds on the one before.

What you will learn

  • How to store data in variables
  • How to write and call functions
  • How to repeat work with loops
  • How to avoid common beginner mistakes

To run our code, we will use Node.js. It lets us run JavaScript in the terminal, with no browser needed. If you do not have it yet, please download it from the official Node.js website. Let us first check that it works.

Check Node.js
Code Copied to Clipboard

# Your first script

If you see a version number, like v20.11.0, then Node.js is ready. If you see an error, please install Node.js first and try again.

Now, please make a new file called basics.js. Put it in any folder you like. We will write all our code in this one file. After each step, we will run it and see the result.

The simplest tool for showing output is console.log(). It prints a message to the terminal. Programmers use it all the time to check what the code is doing. Let us start with a very small script and then talk about variables.

Please type the code below and save the file.

Variables
Code Copied to Clipboard

# Understanding variables

A variable is like a labeled box. You put a value inside the box, and you use the label to get it back later. In JavaScript, we make variables with const or let.

Use const when the value will not change. Use let when the value can change later. In our code, name stays the same, so it is const. The age changes, so it is let. If you try to change a const, JavaScript will give an error.

There is also an old keyword called var. Please avoid it in new code. It has strange rules that confuse beginners.

Common data types

  • String for text, like 'Sara'
  • Number for numbers, like 20
  • Boolean for true or false
  • Array for a list of values

Let us run the file and see what happens.

Run the script
Code Copied to Clipboard

# Reading the output

You should see four lines in your terminal. First, the name Sara. Then the age 20. Then the new age, 21. And last, the answer for isStudent.

Notice that the output goes from top to bottom. JavaScript reads your code in order, one line after another. This is a basic rule of programming. The order of the lines matters.

Now, let us take a small step forward. Sometimes we need to do the same job many times. For example, we may want to greet many people. Writing the same lines again and again is slow, and it is easy to make mistakes.

The answer is a function. A function is a small block of code with a name. You write it once, and you can use it many times. This idea saves time and keeps your code clean.

Functions
Code Copied to Clipboard

Parameters and return values

Let us look closely at the function. The word person inside the brackets is a parameter. It is like an empty slot. When we call greet('Ali'), the value 'Ali' goes into that slot. We call this value an argument.

The return keyword sends a result back to the place that called the function. If a function has no return, it gives back undefined.

The second function, add, uses a shorter style called an arrow function. It is very common in modern code. Both styles work well. For more details, see the MDN guide on functions.

# Making decisions and repeating work

Now we come to loops. A loop repeats a piece of code many times. Imagine you must print the numbers from 1 to 5. You could write five console.log lines. But what if you need 1000 numbers? A loop does it with only a few lines.

The most common loop is the for loop. It has three parts inside its brackets. First, a starting point, like let i = 1. Second, a condition, like i <= 5. The loop keeps going while this condition is true. Third, a step, like i++, which adds one each time.

There is also the for...of loop. It is perfect for going through every item in an array. It is short and easy to read.

Common loop types

  • for when you know how many times to repeat
  • for...of to visit each item in an array
  • while to repeat until a condition changes

Let us try the first two types now.

Loops
Code Copied to Clipboard

# Run it again

Please add the function and loop code to your basics.js file. You can keep the old code at the top. Then save the file and run it once more with the same command.

This time, you will see many more lines. First your variable output, then the greetings, then the sum of two numbers. After that, the numbers from 1 to 5 appear. At the end, you see three lines about fruits.

If you see an error, please do not worry. Errors are normal, and every programmer sees them each day. Read the message slowly. It usually tells you the line number and the kind of problem. A missing bracket or a missing quote is the most common cause. Fix it, save, and run again. This habit of trying, reading and fixing is how people learn to code.

Run the full script
Code Copied to Clipboard

# Combining everything

Let us now use variables, a function and a loop together. This is how real programs work. They are small parts that join together.

In the example below, we have a list of prices. We write a function called total that goes through the list with a loop. It adds each price to a running sum. At the end, it returns the final result.

Notice that the sum variable is made with let, because its value changes inside the loop. The prices list is made with const, because we do not replace the list itself.

What to observe

  • The function takes a list as its parameter
  • The loop visits each price one by one
  • The return gives back the final sum

Please try it, and then change the prices to see a new total.

A small total calculator
Code Copied to Clipboard
Mistakes to avoid

Here are some very common beginner mistakes. Please read them with care.

First, do not use = when you want to compare. A single = stores a value. To compare two values, use ===. For example, age === 21 asks if age is equal to 21.

Second, be careful with infinite loops. If your loop condition never becomes false, the program will run forever. In the terminal, you can press Ctrl + C to stop it. Always check that your loop moves toward its end.

Third, do not forget that arrays start counting from 0. The first item is at position 0, not 1.

Quick checklist

  • Use const first, and let only when needed
  • Use === to compare values
  • Give functions clear and simple names
  • Test your code often with console.log

These small habits will make you a stronger programmer.

# Summary and next steps

Excellent work! You have learned the three core ideas of JavaScript today.

You can store data in variables with const and let. You can write functions with parameters and return values. You can repeat work with for and for...of loops. You also ran your code with Node.js and fixed small errors.

What to do next

  • Learn about objects and array methods like map and filter
  • Learn how to use if and else for decisions
  • Learn how JavaScript changes a web page with the DOM
  • Read the free JavaScript Guide on MDN

The best way to learn is by building small things. Try making a tiny program that counts, adds or prints a list. Be patient with yourself. Every expert was once a beginner. Keep going, and you will do great!