CodeBlanks Logo Icon CodeBlanks

Declaring variables

JavaScript course · Beginner · Lesson 1/133

Learn to declare variables with let, const and var and the basic differences between them.

What is a variable?

A variable is a name you give to a value. You can later use this name to read the value, change it or print it on screen. In JavaScript a variable is declared with the let, const or var keyword.

The most common one is let. To assign a value to a let variable you use the = sign: let sehir = "Berlin";. Here sehir is the variable's name and "Berlin" is its value.

Declaring with const

A variable declared with const gets its value once and cannot be reassigned later. When you are sure a value will never change, it is a good habit to use const.

For example you write const pi = 3.14;; if you later write pi = 3.15; JavaScript throws a TypeError. This protects you from changing a constant by mistake.

Printing with console.log

To see the value of a variable you declared, you use console.log(). You put the variable's name inside the parentheses; JavaScript prints that variable's value to the console.

For example, write let yas = 30; and below it console.log(yas);; the console shows 30. console.log is a function; we will cover functions in detail later, for now just use it to print values.

Exercise Declare a variable and print it

Declare a sehir variable and give it a city name. Then print its value with console.log.

Show example solution
let sehir = "Berlin";
console.log(sehir);

Test yourself

  1. Which of these variable declarations is valid?

    • let 1sayi = 5;
    • let sehir = "Berlin";
    • let sehir = Berlin;
    • let = "Berlin";
    Show answer

    let sehir = "Berlin"; — Correct. After let comes a name, then = and the value.

  2. Declare a city variable with let

    ____
    Show answer
    let sehir = "Berlin";
  3. Match each keyword to its role

    let
    Value can change
    const
    Cannot be reassigned
    var
    Old style, best avoided
    console.log
    Prints a value

All lessons in Beginner