This content originally appeared on Envato Tuts+ Tutorials and was authored by Alberta Williams
JavaScript is a language that we can use to write programs that run in a browser or on a server using Node. Because of Node, you can use JavaScript to build full web applications like Twitter or multi-player games.
This is the first lesson in a four-part series where I will teach you the programming fundamentals you will need so you can learn to build your own apps. In part 1, I will introduce you to the syntax of JavaScript and ES6. ES6 stands for ECMAScript 6, which is a modern version of JavaScript. We will also cover some other basic concepts such as variables and data types.
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 on 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 Ctrl + Shift + K in Firefox or Ctrl + 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.
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 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 stand for Read-Eval-Print-Loop. Basically, the shell will Read the code your 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:
> console.log("Hello, World");
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:
console.log("Hello, World");
Run the code from the terminal:
$ node hello
If all is well, you will see the text "Hello, World" output to the terminal.
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:
- Remove top from cup.
- Empty seasoning pack into cup.
- Fill cup with water.
- Microwave on high for 2 minutes.
- 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.
- Calculate the sum all of the numbers.
- Get the total number of numbers.
- Divide the sum by the total.
- 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 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:
a = 2 + 2;
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:
2+2
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 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 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 to 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:
let a;
Declaring and initializing a variable:
let a = 1;
Reassigning a variable:
a = 2;
Constants are variables that cannot change. There 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:
const a = {foo:1,bar:2}; a.baz = 3; console.log( a ); // displays { foo: 1, bar: 2, baz: 3 }
However, this will give you an error:
const a = {foo:1,bar:2}; a = {}; console.log( a );
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 theNumber.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 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:
"Hello, World".startsWith("Hello"); //true
Determine if a string ends with a substring:
"Hello, World".endsWith("World"); //true
Determine if a substring is located anywhere in a string:
"Hello, World".includes("World"); //true
Repeat a string a specified number of times:
"Hello".repeat(3); //HelloHelloHello
We can turn a string into an array of individual characters (strings of length 1) with the spread operator: ...
let str = [..."hello"]; console.log(str); //[ 'h', 'e', 'l', 'l', 'o' ]
Template literals are a special kind of string that use backticks. We can use them to insert variables within a string like this:
let name = "World"; let greeting = `Hello, ${name}`; console.log(greeting); //Hello, World
We can create multiline strings like this:
` <div> <h1>Hello, World</h1> </div> `
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:
function factorial(x) { let result = 1; while(x > 1) { result *= n; x -= 1; } return result; } // 120 console.log(factorial(5)); // 362880 console.log(factorial(10)); // 3.0414093201713376e+64 console.log(factorial(50)); // Infinity console.log(factorial(500));
Did you complete the task under 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 number 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.
function factorial(x) { let result = 1n; while(x > 1n) { result *= n; x -= 1n; } return result; } // 120n console.log(factorial(5n)); // 3628800n console.log(factorial(10n)); // 30414093201713378043612608166064768844377641568960512000000000000n console.log(factorial(50n)); // 1220136825991110068701238785423046926253574342803192842192413588385845373153881997605496447502203281863013616477148203584163378722078177200480785205159329285477907571939330603772960859086270429174547882424912726344305670173270769461062802310452644218878789465754777149863494367781037644274033827365397471386477878495438489595537537990423241061271326984327745715546309977202781014561081188373709531016356324432987029563896628911658974769572087926928871281780070265174507768410719624390394322536422605234945850129918571501248706961568141625359056693423813008856249246891564126775654481886506593847951775360894005745238940335798476363944905313062323749066445048824665075946735862074637925184200459369692981022263971952597190945217823331756934581508552332820762820023402626907898342451712006207714640979456116127629145951237229913340169552363850942885592018727433795173014586357570828355780158735432768888680120399882384702151467605445407663535984174430480128938313896881639487469658817504506926365338175055478128640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000n console.log(factorial(500n));
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 helpful for only 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 abut objects and arrays for now as we will learn about them in more detail in other tutorials of the series.
Symbol
A Symbol
is a built-in JavaScript primitive that is just always guaranteed to be unique. This makes them 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 in order to get back the same symbol for a particular key.
const x = Symbol(); const y = Symbol(); const a = Symbol.for("potato"); const b = Symbol.for("potato"); // Symbol Mismatch if(x === y) { console.log('Same Symbol'); } else { console.log('Symbol Mismatch'); } // This should Match if(a === b) { console.log("This should Match"); }
Review
We have seen how to set up our development environment using Node. The first step to 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
keyword. 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 different set of tasks under different circumstances like whether a users 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.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Alberta Williams
Alberta Williams | Sciencx (2017-08-02T09:40:49+00:00) Learn to Code With JavaScript: Part 1, The Basics. Retrieved from https://www.scien.cx/2017/08/02/learn-to-code-with-javascript-part-1-the-basics/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.