Learn to Code With JavaScript: Part 1, The Basics

Installation and Setup

First, we will set up our development environment so that we can run our code on our own computer. Alternatively, you can test code examples in an online editor like OneCompiler.

The easiest way to do so would be to use your web browser. This is especially true if you have no prior experience with programming in general. All you need to do is press Control-Shift-K in Firefox or Control-Shift-J in Chrome to get started. This should give you something like the image below, where I have already executed a line of code.

Browser ConsoleBrowser ConsoleBrowser Console

Alternatively, you can also consider using Node if you are comfortable with installing and setting up your own runtime environment. You will be able to put it on your resume and impress your employer later.

First, you will need a text editor to write your code in. I recommend Sublime Text or Visual Studio Code. Next, download and install Node to your computer. You can get the software on the Node.js website. Confirm that the installation worked by typing the command node -v from your terminal. If everything is fine, you will see the version number of your Node installation.

One of the things you can do with Node is run JavaScript code from within your terminal. This takes place in what is called an REPL shell. The term REPL stands for Read-Eval-Print-Loop. Basically, the shell will Read the code you enter, Evaluate what you wrote, Print the result, and keep Looping until you exit. To try it out—enter the command node in your terminal.

Next, let’s print the message “Hello, World”. Type the following into the terminal:

Node.js REPLNode.js REPLNode.js REPL

To exit the REPL, press Control-C twice. Using the REPL comes in handy when you want to test simple statements like the example above. This can prove more convenient than saving code to a file—especially if you’re writing throwaway code.

To execute a program you have written in a file, in your terminal run the command node filename, where filename is replaced with the name of your JavaScript file. You do not have to type the js extension of the filename to run the script. And you must be in the root directory where the file lives.

Let’s try an example. Create a file named hello.js. Inside, we will put the following code:

Run the code from the terminal:

If all is well, you will see the text “Hello, World” output to the terminal.

Node.js File CodeNode.js File CodeNode.js File Code

From now on, you can test the code examples from this tutorial either by using the Node REPL or by saving to a file.

Designing a Program

Before you write any code, you should take the time to understand the problem. What data do you need? What is the outcome? What tests does your program need to pass?

When you understand the requirements of the program, then you can write the steps to solve it. The steps are your algorithm. Your algorithm is not code. It is plain English (replace English with your native language) instructions for solving the problem. For example, if you want to write an algorithm for cooking top ramen, it might look like this:

  1. Remove top from cup.
  2. Empty seasoning pack into cup.
  3. Fill cup with water.
  4. Microwave on high for 2 minutes.
  5. Cool for 1 minute.

Yes, I was hungry when I thought of this. And no, this is not something you would actually be given as a programming problem. Here is an example of a problem that is more practical. It is an algorithm to calculate the average of a list of numbers.

  1. Calculate the sum of all the numbers.
  2. Get the total number of numbers.
  3. Divide the sum by the total.
  4. Return the result.

Understanding the problem and coming up with an algorithm are the most important steps in programming. When you feel confident in your algorithm, then you should write some test cases. The tests will show how your code should behave. Once you have your tests, then you write code and tweak it until your tests pass. Depending on how complex your problem is, each one of the steps in your algorithm may need to be broken down further.

Task

Write an algorithm to calculate the factorial of a number. The factorial of a number n is the product of all integers from 1 to n. For example, 4! (4 factorial) is 1 x 2 x 3 x 4 = 24.

Syntax

A program is similar to the language we speak with. The only difference is that a programming language is meant to communicate with the computer (and other programmers who have to use it). The rules for constructing the program are its syntax. Programs consist of statements. A statement can be thought of as a sentence. In JavaScript, you must put a semicolon at the end of a statement. Example:

Statements consist of expressions. Expressions are like the subject/predicate parts of a sentence. In a programming language, expressions have a value. Expressions consist of keywords like var and for which are the built-in vocabulary of the language; data like a number or string; and operators like + and =. Example:

Here is a list of arithmetic operators:










Operator Meaning
+ addition
- subtraction
** exponentiation
* multiplication
/ division
% remainder
++ increment
-- decrement

The remainder operator returns the remainder after dividing two numbers. For example, 4 % 2 returns 0, and 5 % 3 returns 2. The remainder operator is commonly used to find out if a value is even or odd. Even values will have a remainder of 0.

One thing that I would like to mention is that the remainder operator is different from the modulo operator, which uses the same symbol. In short, the result of a modulo operation will always have the same sign as the divisor. On the other hand, the result of a remainder operation will always have the same sign as the dividend.

Task

Find the value of the following expressions. Write down your answers first, and then check them in your REPL.

  • 9 % 3
  • 3 % 9
  • 3 % 6
  • 3 % 4
  • 3 % 3
  • 3 % 2

Variables

A variable is a name that represents a value in the computer’s memory. Any value we would like to store or use over and over should be placed in a variable. One way of creating variables is with the var keyword, but the preferred way is to use the let or const keywords. Here are some examples of using let to create variables:

Declaring a variable:

Declaring and initializing a variable:

Reassigning a variable:

Constants are variables that cannot change. Their value can only be assigned once, and it has to happen during initialization. Constants that have objects or arrays as values can still be modified because they are assigned by reference. The variables do not hold a value; instead, they point to the location of the object. Example:

However, this will give you an error:

As a general rule, you should always create variables using the const keyword and use let only when you know that the variable value will be reassigned in the future. This will make debugging easier for you or anyone else browsing through your code as you will know that the value of a const variable that you encountered again many lines later still has the same value that you assigned earlier.

Data Types

When writing programs, you will usually have to deal with different kinds of data. This data is represented by different data types. Data types have rules for how they can be operated on. For example, if we add two numbers, we get their sum. But if we add a number with a string, we get a string.

Here is a list of the different data types:

  • undefined: a variable that has not been assigned a value
  • Boolean: an entity that has the value true or false
  • String: a sequence of characters
  • Symbol: a unique, unchanging key
  • Number: useful for working with integer and decimal values
  • BigInt: useful for operating on large numbers that can even go beyond the Number.MAX_SAFE_INTEGER limit
  • Object: a collection of properties

In addition, there is null, a special value of type Object. null is used to indicate an empty or non-existent object.

undefined vs. null

While undefined and null might seem to be similar, they are in fact very different. Whenever there is an absence of some value, it is treated as undefined. On the other hand, you have to explicitly make things null. For example, a function that doesn’t return any value is assumed to return undefined instead of null.

Boolean

The Boolean type represents two values, true and false. They are useful when you are writing code where you only want to know if something is true or not. For example, you can use a variable like isItNight and check if its value is true or false to determine whether to apply a dark or light theme.

Strings

A String is a data type that consists of characters. A string will be surrounded with single quotes, double quotes, or the backtick character.

We use strings to store textual data such as the name of a person. The String object also has a variety of methods you can use to perform actions on them. The following are some examples of actions you can perform on strings.

Keep in mind that strings in JavaScript are immutable, and any method that you use on a string will result in the creation of new strings while leaving the original untouched. Here are a few examples of string methods.

Determine if a string begins with a substring:

Determine if a string ends with a substring:

Determine if a substring is located anywhere in a string:

Repeat a string a specified number of times:

We can turn a string into an array of individual characters (strings of length 1) with the spread operator: ...

Template literals are a special kind of string that use backticks. We can use them to insert variables within a string like this:

We can create multiline strings like this:

Number

The Number type in JavaScript comes in handy when you are dealing with, well, numbers. It allows you to store and manipulate numbers. You can use this type to work with positive or negative numbers as well as fractions. Here is an example:

Did you complete the task under the Designing a Program section where you had to write an algorithm to calculate the factorial of a number? The above code shows you how to implement something like that in JavaScript.

We defined our own function named factorial() that accepts a number as input and gives us its factorial. Defining a function allows us to avoid repetition of code. For example, we did not have to write our code four times to calculate the factorial of four different numbers. You will learn about functions in more detail in a later tutorial.

There are two things that you might have noticed above. First, the function calculates the factorial as expected. However, it doesn’t return an exact number for a factorial of 50. Second, it doesn’t return any kind of number but simply says Infinity when calculating the factorial of 500.

We all know that the factorial of 500 is not going to be Infinity. However, JavaScript will convert any number over Number.MAX_VALUE or 21024 to Infinity.

Is there any way for us to get an actual value for the factorial of 500? Yes, there is! We will learn about the BigInt type next.

BigInt

The BigInt type allows you to work with numbers of arbitrary magnitude. This means that your values can go beyond Number.MAX_VALUE without returning something vague like Infinity.

There are two ways of creating a BigInt. You can either append n at the end of your integral value or you can call the BigInt() function. Let’s rewrite the above code to get factorials using the BigInt type.

As you can see, we do get an actual numeric value as our result for the factorial of 500. However, keep in mind that BigInt is only helpful for storing integers. You cannot use it to do calculations with fractional numbers of arbitrary magnitude.

One more thing to remember is that you cannot mix BigInt and regular Number types while doing arithmetic operations. This is the reason we converted all our numbers, even small ones such as 1, to BigInt type by appending n at the end.

Object

As mentioned earlier in the tutorial, objects in JavaScript are a collection of properties, and these properties are simply key-value pairs to store information. Functions in JavaScript are also basically objects which we can call. Arrays, which are used to store multiple values inside a single variable, are also objects.

Don’t worry about objects and arrays for now as we will learn about them in more detail in other tutorials in the series.

Symbol

A Symbol is a built-in JavaScript primitive that is always guaranteed to be unique. This makes it ideal for creating unique property keys that won’t collide with object keys that might be added by some other code.

Each call to Symbol() returns a unique symbol. However, you can use the for() method to get back the same symbol for a particular key.

Review

We have seen how to set up our development environment using Node. The first step in programming is writing the steps to solve the problem. This is called the algorithm. The actual code will consist of many statements. Statements are the program’s instructions and are made up of expressions.

Expressions are useful in our program if we assign them to variables. Variables are created with the let or const keywords. Variables will usually store different types of data that we just discussed.

In the next part, I will explain conditionals that allow you to run a different set of tasks under different circumstances, e.g. whether a user is logged in or logged out.

Resources

This post has been updated with contributions from Monty Shokeen. Monty is a full-stack developer who also loves to write tutorials and to learn about new JavaScript libraries.

Leave a comment

Your email address will not be published.