JavaScript for beginners – variables and data types

A beginner’s guide to JavaScript variables and data types. The first part of a series on JavaScript basics.

What we will learn

In this tutorial we will look into the basics of JavaScript syntax, variables and variable data types. We will be using both ES5 and ES6 syntax throughout the tutorial.

Firstly, what is JavaScript?

JavaScript used to be a front-end or client side programming language which was used for interactivity on the front-end of a website, such as; click events, animations and more.

I have written more about what JavaScript is in my last post, read it here – JavaScript – The beginner’s guide

A lot of people get confused between Java and JavaScript but they are completely different programming languages.

JavaScript Variables

A variable in JavaScript can store different types of data to be used later in your program.

In JavaScript you declare variables using one of the following methods:

var x = 0; // A dynamic variable scoped by function.

let y = 1; // A dynamic variable scoped by block.

const z = 2; // A static variable that cannot be changed.

There are two variable types (not to be confused with data types), dynamic and static. A dynamic variable can be changed even after it has already been declared. Whereas a static variable cannot be changed once it has been declared.

From the above code snippet you can see each sentence ends in a semicolon. This is optional but it let’s the browser know this is the end of the code block.

You can also see that after each semicolon we have added a // which let’s the browser know this is only a comment and has no function.

Dynamic variable

let x = 0; // Declaration of variable x to 0.

x = 5; // Changing the variable x to 5.

console.log(x); // This outputs 5 to the console.

Static variable

const x = 0; // Declaration of variable x to 0;

// x = 5; Trying to change the variable will throw an error in the console.

console.log(x); // This outputs 0 to the console. 

console.log() will print variables and data to the console.

You can compare variable values by using == or === to compare if the variables match.

let x = 5;
let y = 5;

console.log(x === y) // Prints true

y = 10;

console.log(x === y) // Prints false

You can also use the following to compare variables < (less than), > (more than), <= (less than or equal to), >= (more than or equal to).

let x = 5;
let y = 10;

console.log(x < y) // Prints true
console.log(x > y) // Prints false
console.log(x <= y) // Prints true
console.log(x >= y) // Prints false

Data types

We have gone over variables but we have only used integers (whole numbers).

There is two types of data types, primitives and objects. A primitive can only contain one data type whereas an object can contain multiple data types.

Primitive data types

String

A string is a combination of characters.

Strings use special syntax, they need to be wrapped in quotes. You can use either double quotes "" or single quotes ''.

let name = "Tyler Potts"; // Double Quotes
let name = 'Tyler Potts'; // Single Quotes

// let name = "Tyler Potts'; Both Single and Double strings do not work. Both the start and end quote must match.

Number

A number is a numerical value such as 1, 2, 4 and so on… These are called integers, a number can also hold floats and negative versions of these two.

let x = 1; // Integer
let y = 1.1; // Float
let z = -1; // Negative Integer

Numbers don’t need special syntax such as quotes to wrap them like strings.

Boolean

A boolean has two possible values, true or false.

Booleans are one of the most common data types used in programming as these are what are returned when comparing values.

You can use variables to represent the state of something, or to check if a users password matches when logging into an account.

let dinnerReady = false;
console.log(dinnerReady); // false

setTimeout(function () {
    dinnerReady = true;
    console.log(dinnerReady); // true
}, 1000);

In the snippet above, I am creating a variable with a boolean data type and setting it equal to false. After one second or one thousand milliseconds, we set the variable to true. In this case we use it to tell us in the console when “dinner is ready”.

Null & Undefined

A null is an intentional absence of value. A variable is usually set to null on purpose, this is so its value can be declared later in the code.

There is a similar primitive data type known as undefined, which is an unintentional absence of value, this is usually what is returned when a value has not been set or the variable / value does not exist.

// Null
let player = null;
console.log(player); // Returns null

function playerReady () {
    player = {
        name: "Test",
        age: 21
    }
    console.log(player) // Returns {name: "Test", age: 21}
}

// Undefined
console.log(bank); // Returns undefined

let bank = 1000;
console.log(bank); // Returns 1000

In the code snippet above you can see that we wait for the playerReady function to be called before the player variable is set, so prior to this function we declare the variable and set it to null.

We also try to log the bank variable which has not yet been defined so it returns undefined.

Object data types

Arrays

Arrays are the most popular object data type, they can hold multiple types of primitive data and other objects including nested arrays.

let number_array = [0, 1, 2, 3, 4, 5]; 

let string_array = ["A", "B", "C", "D", "E"];

let mixed_array = ["A", 3, "C", 9];

In the above snippet you can see the different ways arrays can store data. We can access each individual array item by using it’s index value.

console.log(mixed_array[3]); // Returns 9

In the snippet above you can see that by using square brackets and inserting a numeric index value returns the corresponding value in the array. You might have noticed that looking at index 3 returned the fourth item in the array. This is because arrays start at 0, so index 3 would be the fourth item in the array.

Objects

Another Object data type is an object itself. An object is like an array but instead of storing values individually, it allows you to store values with a key known as a key value pair.

let user = {
    name: "Tyler",
    age: 22
};

In the above snippet you can see how an object is defined, it is defined by wrapping a comma separated key value pair in curly brackets. It then has a key on the left separated by a colon then the value on the right.

To access a value in an object you can use its key. See snippet below

console.log(user[age]); // Returns 22

Functions

Functions are another Object data type, it is a reusable piece of code that performs a task or calculates a value.

To use a function you must declare it and call it. See code snippet below for example.

function greeting () {
    console.log("Hello, World");
}

greeting(); // Returns "Hello, World"

In the above snippet you can see the syntax used to define and call a function.

To add to the above you can pass parameters to functions. See below code snippet.

function greeting (name) {
    console.log("Hello, " + name);
}

greeting("Tyler"); // Returns "Hello, Tyler"

In the code snippet above we pass through a parameter called name that can be used inside the function scope. We pass through a value when calling the greeting function and it will replace name with that value inside the function.


Let’s recap what we learned in this tutorial.

We looked into the different types of variables including; let, const and var. We looked into different data types including primitive data types such as; string, number, boolean and null. We looked into object data types such as; Objects and Arrays which hold multiple data types. Finally, we looked into basic functions and parameters.

I hope you learned something from this post. I will release the next installment in the near future which will dive deeper into javascript functions and scope.

If you want to continue learning JavaScript I post videos on it all the time.

Check out my channel: https://youtube.com/c/tylerpotts

Thanks for reading!

– JavaScript Wizard