Basics of JavaScript programming

After some introduction to basic terms and concepts related to programming and JavaScript on its own, it's time to code something for real! In this blog post, we'll learn about the fundamental constructs used in JS (as well as many other programming languages) and how they all come together. Let's get started!

Variables

We'll start with variables - a way of storing values under predetermined names. Take a look at their syntax:

var value = 1;
let second_value = "value";
const thirdValue = true;

In JS, all three methods of declaring a variable look similarly. First comes the keyword - var, let or const, then the variable's name and finally, the optional value assignment. At the end of pretty much any statement (e.g., variable declaration), you should put a semicolon, but it's not always necessary.

Keywords

Keywords hold special meaning in JS. They usually indicate certain language constructs. In the case of variables, the use of any of the three mentioned keywords results in a variable declaration. However, there are some differences.

  • var (abbreviation from a variable) is the oldest way of declaring a variable in JS. Up until ES6 from 2015, var was your only choice.
  • const - introduced in ES6, it's a keyword used to declare constants. They must have their values assigned in the moment of their declarations, and cannot be reassigned.
  • let - introduced alongside const. Somewhat of an alternative to old var but with some tweaks that we'll learn more later in the series.

Naming

After the keyword comes the variable's name. In JS, the names are composed of Unicode characters. What this means is that you can use complex symbols (like those known from Asian languages), but there are some exceptions. Most importantly, your names cannot be the same as language's keywords (so no variable named var). They also have to be unique (for us to have a way of referencing them later), cannot start with a digit and contain any whitespace character or a hyphen. But, it's also recommended for the names to be descriptive and meaningful. Thus, they often consist of more than one word, which requires special formatting to improve readability. There are quite a few different formattings, like the snake case (second_value) or probably the most popular camel case (thirdValue). Speaking of formatting, JS is case sensitive, so thirdValue isn't the same as thirdvalue.

The keyword is followed by the name of the variable. In JS, the names are composed of Unicode characters. What this means is that you can use complex symbols (like those known from the Asian languages), but there are some exceptions. Most importantly, your names cannot be the same as language's keywords (so no variable named var). They also have to be unique (for us to have a way of referencing them later), cannot start with a digit, and contain any whitespace character (tabs, spaces, etc.) or a hyphen. But, it's also recommended for the names to be descriptive and meaningful. Thus, they often consist of more than one word, which requires special formatting to improve readability. There are quite a few different casing styles, like the snake_case (second_value) and probably the most popular camelCase (thirdValue). Speaking of formatting, JS is case sensitive, so thirdValue isn't the same as thirdvalue.

Data types

When you declare a variable, you can assign a value to it. On the right side of the assignment, you'll find the data, which comes in many forms. Let's take a look at some of JS's data types.

Numbers

Numbers hold a unique position in programming. In JS, all numbers are stored in a 64-bit floating-point format. Because of that, you can use some pretty big numbers in your code, within specific, but extensive limits.

const integer = 11;
const floatingPoint = 1.4;
const negativeInteger = -12;
const negativeFloatingPoint = -4.6;
const bigNumber = 5e7;

Numbers are relatively easy to use. Aside from all the usual, floating-point, and negative numbers, you can also use the bigger ones with the special e letter notation. It makes your number higher by 10 to the power of the number following e (exponent). The exponent can be either negative or positive, but not floating-point.

There's a lot that can be done with numbers in JS, but for now, we'll keep things simple by learning only the simplest operations.

1 + 1; // 2
6 - 2; // 4
3 * 2; // 6
16 / 2; /*
	This expression is equal to 8
*/

Above, you can see number operations as they are used in JS - addition, subtraction, multiplication, and division. What you can see on the right of each expression is the result of the performed operation inside a comment. A comment allows you to document your code easily. All the stuff that's inside of it won't be analyzed or executed. It can be created by either the // (till the end of the line) or with /* and */ symbols.

Previously, when I showed you the variable declaration, I called it a statement, while now I'm calling the operations above expressions. That's because there're some differences between them. The one that interests us the most is that expressions can be assigned directly to variables, while statements cannot.

const calculatedValue = 2 * 3; // 6

You might often find yourself wanting to operate on a value stored in the given variable and assign the result to the same variable. It may sound complicated, but it's such a common operation that there're some shortcuts built right into the language.

let value = 2;
value += 2; // 4 -> assign 2 to the value stored in the variable and store the result

A similarly-looking shortcuts exist for all the mentioned operators, so there's +=, -=, *=, and /=.

Strings

Strings are probably the most important data type after numbers, used to represent a sequence of characters.

const characterSequence = "word";

Strings, just like names, can contain all Unicode characters, but this time without any limitations. Only some unique, often hidden characters like newline (\\n), tab (\\t), and a quote sign (\\") are required to be escaped - preceded by a backslash. Otherwise, they'll be interpreted as a usual n, t, or " character which would result in ending the sequence.

Strings don't have as many operators available as the numbers have. They have only one - + used for string substitution/concatenation, i.e., addition.

const result = "this" + " is" + " something"; // "this is something"

Just like with numbers, you can use the operator multiple times and assign the result to a variable.

You might remember (if you've read the previous post) that JS is a weakly and dynamically-typed language. What the "dynamic" part means, is that you don't have to provide a data type explicitly, when e.g., declaring a variable. It's determined at runtime instead, which, when considering the "weak" part, allows for your data to have somewhat of a loose data type. Consider the example below:

const stringValue = "10" + "1"; // "101"
const numericValue = "10" - "1"; // 9

That's probably one of the most well-known examples of JS's weakly-typed nature. While the + operator does its job well (string substitution), there's no way (at least in JS) to subtract two strings. Thus, JS converts them into numbers and operates on that instead. If strings contain only properly positioned digits, then it'll be fine, but if there's something not right, the result will always be NaN (Not a Number). So, it's not a good practice to subtract strings. ;)

Boolean

With booleans, things are simple - it's either true or false. But, even with all this simplicity, booleans are still a very versatile and useful data type.

Just like numbers, booleans have a set of their own operators.

const andOperation = true && false; // false
const orOperation = true || false; // true
const negationOperation = !true; // false
const mix = (andOperation || orOperation) && negationOperation; // false
  • The and operator (&&) results in true only when both of its operands (the values that it's used with) are true.
  • The or operator (||) results in true when at least one of its operands is true.
  • The negation operator (!) negates the operand, and thus changes true to false and vice versa.

Boolean operators can be mixed (just like with numbers), together with other variables and round brackets (for ordering).

Booleans can be created either by using the true or false value directly or by evaluating an expression. With right operators, you can create booleans from e.g., numbers or strings. Take a look.

4 > 2; // true
5 >= 5; // true
3 < 2; // false
3 <= 4; // true
6 == 6; // true
6 == "6"; // true
6 === "6"; // false

8 != "8"; // false
8 !== "8"; // true

The lesser than, higher or equal to, and equal to operations are well-known to you. I think that only the equality operator requires a little explanation. You must remember that instead of one, it consists of two or three = signs. While the == checks for loose equality, where JS's weak typing comes into play, the === is more restrictive, and thus 6 === "6" results in false. The != and !== operators are simply the opposite (inequality checks) of the == and === operators.

If statements

Booleans are most often use with conditional if/else statements, which are used to execute a given block of code conditionally.

let value = 10;

if (value < 100) {
	// do something
} else if (value < 200) { 
	// do something when value < 200
} else {
	// do something else
}

An if statement always starts with the if keyword. Then comes a pair of round brackets (parenthesis), inside of which there's a boolean to be checked. All the code that should be executed when the boolean is truthy, must be put within the curly brackets ({}). After that, we can provide an optional else if clauses (as many as you want), for checking for other conditions. The final (and also optional) else clause (must come at the end), will be executed when all other conditions fail.

An if statement is checked from top to the bottom. So when the first or second condition is truthy and the respective code block is executed, everything else is ignored.

Arrays

By now, we've only discussed what's called the primitive data types. Numbers, strings, booleans - all of them are the most basic (but also the most useful) data types in the language. With arrays, we're getting into something more complex.

const arr = [1, 2, 4, "word"];

Arrays are list-like constructs that contain values of different types. They can be created with square brackets ([]) and values put inside them, separated by commas.

As arrays can contain all types of values, they can also contain other arrays! For example, take the array below, which is often called a 2D array.

const arr = [[1,2], [3,4]];

Elements of an array can be accessed using the square bracket notation, provided an index of the desired element.

const arr = ["a", "b", "c", ["d", "e"]];
arr[0]; // "a"
arr[2]; // "b"
arr[3][1]; // "e"
arr[4]; // undefined

Indexing starts from 0 for the first element and goes up from there. If a negative or too big index is provided, it will result in an undefined value. Elements of multi-dimensional arrays (2D, 3D, etc.) can be accessed using a similar method.

Objects

Objects hold an exceptional position in JS. They're very complex and versatile structures that we'll be exploring deeper, later in the series. Right now, take a look at the example.

const car = {
	color: "red",
	inGoodShape: true,
	"production-age": 2019
}

Above, you can see a car object I created. An object is created using curly brackets, with the object's properties placed inside them. Properties have names and values. The name comes first and can either follow the variable naming conventions or have a form of a string. The value comes later, after the colon. When the next property is expected, the current one should end with a comma.

car.color; // "red"
car["inGoodShape"]; // true
car["production-age"]; // 2019

Object properties' values can be accessed using either the dot or square bracket notation. The first is more widely-used, while the second one is required when working with string-based names.

Loops

Now that we've talked a fair bit about data types let's try something different. Loops allow you to execute the given code multiple times easily. In JS, there are 3 (or technically 5) main types of loops. Here, we'll learn only the most popular and useful one - the for loop.

for(let i = 0; i < 10; i++) {
	// do something.
} 

So, we're starting with the for keyword. Then come the parenthesis and curly brackets, where our looped code is located. But, it's within the rounded brackets that the magic happens. Let's take a closer look.

First, we declare a variable i. For loops provide a special section for that, but you can declare your variable earlier, before the loop itself. You only have to leave the semicolon so that the JS engine will know that you've stepped out from the first section. By the way, the i name is commonly used within for loops and comes from the word iteration, with means pretty much the same as looping.

In the second section, we find our boolean condition. It's meant to check whether the block of code should be executed again (another loop) or not. Don't miss the semicolon dividing the sections!

Lastly, we've got the i++ thing at the end. We know what i stands for, but what about the ++ operator? Well, it's used with numbers and increases the value stored in the variable by 1. Its opposite - the -- operator decreases the value. So, here we're just increasing the value of i e.g., from 0 to 1 in the first run.

The for loop first checks all the stuff within parenthesis and determines whether the provided code block should be run.

Functions

Last for today, we've got functions - an excellent way of reusing our code. For now, we'll learn only one way of creating a function, but if you feel adventurous, you can check out one of my previous posts to learn more about the topic right now.

function doSomething() {
	// do something
}

Above, you can see what's called a function declaration. It's composed of a function keyword followed by the function's name, with a parenthesis and a pair of curly brackets where our code is located. Such a function can later be used by calling it, how many times you want.

doSomething();
doSomething();

As code gets more and more complex, you'll most likely have to create more and more functions to abstract the created complexity away. It's almost sure that you'll at some point have to call functions from a body of a different function. Now, functions can also do more than simply be called. They can accept parameters and return values.

function average(num1, num2, num3) {
	const sum = num1 + num2 + num3;
	
	return sum/3;
}
const example = average(2,3,4); // 3

From the function declaration side, parameters, in order to be accessed, must be placed within the parenthesis and given some names for later reference. Inside the function body, you can do whatever you want and then return a value using the return keyword, followed by the value you want to return. Then, when using the function, you pass the arguments by placing them within the parenthesis. The number of passed arguments doesn't necessarily have to equal the number of parameters that the function accepts. When there's more - the additional arguments are ignored. When there's less - inside the function, you'll get undefined. The value returned from the function can easily be assigned to a variable and used from there.

What's next?

Well, that was a lot, wasn't it? It may seem so, but it really wasn't. In fact, we're just getting started! Don't worry - I know that for those new to programming, this all may seem pretty weird and illogical - how you're meant to create something meaningful from all of this? It's completely normal. That's why I'll dedicate the next part of this series to slow down a little, create our first JS program and learn a bit about the art of problem-solving along the way. If you can't wait and want to try to code something right know, or test out the provided code snippets, I recommend you go to a website like codepen.io or jsbin.com, or simply open your desktop web browser, hit F12 and go from there.

If you like this article, consider sharing it. If you want to stay up-to-date with my latest content, follow me on Facebook, Twitter, Reddit, or through my weekly newsletter. I've also started a YouTube channel, which you might also want to check out. Finally, if you can, consider supporting me and my work through Patreon. Thanks for reading!

Become a Patron!