Menü schliessen
Created: September 24th 2021
Last updated: September 9th 2022
Categories: Common Web Development,  IT Development,  JavaScript Development
Author: Tim Fürer

JavaScript Basics: First Lesson

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Welcome to the first lesson of JavaScript Basics! In this series, I'll introduce you to JavaScript, step by step. This lesson, we'll discuss the following topics:

  • Using the "alert()" function to display basic notifications
  • The importance of semicolons ( ; ) and commenting
  • Declaring variables and basic usage of them
  • Data types
  • Arithmetic operators
  • Using the "console.log()" function to print information into the developer console

There's plenty to learn today, so let's get started!


Chapter 1: Alert(); Hello World!

When learning a programming language, one of the very first things one is commonly taught to do is to print text to the screen, that text usually being "Hello World". How this is accomplished varies between programming languages. Some make it easier, some harder. What it means to print text to the screen can also differ.

"alert()" is a function that takes a string (of characters; text) and displays it as a notification through your browser. Note that some browsers may block these on default.

Example

Using "alert()" to display a "Hello World!" notification:

alert("Hello World!");

Explanation

We start off by writing the function's name (alert) and follow it up with a pair of parentheses (round brackets) inside which we place our message. As that message is text, thus a value of the data type "string", it's necessary to surround it with quotation marks. We'll talk more about values and data types in Chapters 3, 4, and 5. Finally, we place a semicolon, ending the statement.


cHAPTER 2: sEMICoLONS And Comments

Semicolons are the cause of head aches for many beginners. They're frequently forgotten, which in turn will stop entire scripts from running.

But why are they so crucial?

They're separators that help JavaScript tell for certain, at which point a statement ends. The resulting separated structure can allow for multiple statements to be written on the same line without confusion. However, it's common practice to begin a new line after every semicolon, for the sake of readability.

Comments

Whilst we are on the subject of code readability, we can further improve it with the help of comments. Comments can be used for headings in your code or notes explaining it. It's important for your scripts to be easy to comprehend, so that other people can work reliably on and with them without having to invest loads of time studying them.

There are two types of comments. Single-line, which begin with a double slash ( // ) and stay in effect for the remainder of the line, and multi-line comments, which begin with a slash and an asterisk ( /* ), and end with an asterisk and a slash ( */ ), allowing them to span across multiple lines.

Single-line comment:

// This is a single-line comment

Multi-line comment:

/* This is a
multi-line comment */

Chapter 3: Declaring Variables

Variables are used to store values. They are referenced by the name they are declared with. In JavaScript, the variable declaration process can be done through three different keywords of which each have their specific quirks and uses. "var" is the most basic one and was the first to be introduced. It's determined outdated by today's standards and is superseded by the two other keywords, "let" and "const", which both were introduced in 2015.

"let" and "const" differ from each other in that a "let" variable's value can be re-assigned whilst a "const" (constant) variable's cannot. Because of that, "const" variables are secure and predictable. We know that their values will always remain the same.

Declaration

To declare a variable, write one of the above-mentioned keywords followed by a unique name. When choosing a name, consider the following rules:

  • Names may consist of letters, digits, underscores, and or dollar signs
  • Names must never begin with a digit
  • Names are case sensitive, thus "a" and "A" are NOT the same
  • Reserved words, such as keywords, are illegal for usage as names
  • Names must be unique within their scope

What do I mean by scope?

A variable is only accessible from the point and level of script it's declared at. We'll go more in-depth with this in future lessons.

Example...

...of variable declaration:

let price;

Variable declarations of the same keyword type may also be combined. When doing so, only write the keyword behind the first variable's name, and place commas instead of semi colons after each of the variables' names but the final one's.

Without combining:

let price1;
let price2;
let price3;

With combining:

let price1,
    price2,
    price3;

Note: The spacing hereby, while optional, improves the readability, and is recommended.

At this point of declaration, the variable hasn't yet been assigned a value. If attempted to return, the variable's value would be considered undefined.

Value Assignment

To assign a value to a variable, write an in the current scope existing variable's name followed by an equals ( = ) and then a value.

Example...

...of variable value assignment:

price = 15;

The processes of declaring and assigning a value to a variable can be combined as shown in the following example:

let price = 15;

Such may be further combined, too:

Without combining:

let price1 = 5;
let price2 = 10;
let price3 = 15;

With combining:

let price1 = 5,
    price2 = 10,
    price3 = 15;

Getting a Variable's Value

You can use variables' names to return their values.

For example, a variable may be assigned the value of another like so:

priceA = 5;
priceB = priceA;
// priceA is equal to 5
// PriceB, too, is equal to 5

A variable may also be used as a substitute for a static value:

message = "Hello World!";
alert(message); // will alert: "Hello World!"

Utilising variables in place of static values can result in much more dynamic and repetition-free code. Not only can values of variables (which aren't "const") be changed during runtime (whilst the program is running), instead of typing the same message over and over you can simply create a variable with the message as its value and refer to that variable. If you then have to ever do a change to the message, you only have to do it in one place: Where you assigned it to the variable.

Static:

alert("Hello World!");
alert("Hello World!");
alert("Hello World!");

Dynamic:

message = "Hello World!";

alert(message);
alert(message);
alert(message);

Fun-Fact

JavaScript was first released in 1997 and its official name is "ECMAScript".

JavaScript inventor Brendan Eich - Wikipedia

Source: Wikipedia

Brendan Eich

The inventor and creator of JavaScript.


Chapter 4: Data Types

Values are differentiated by data types, which also define the structure they are written in. JavaScript generally uses the following:

  • Boolean
  • Number
  • String
  • Array
  • Object

Boolean

This data type is binary (has two possible states): Either true or false.

isEnabled = true;
has_done_chores = false;

 

Number

Simply numbers. Negative and comma numbers included, too.

price = 15;
money = -3;
distance = 0.5;

String

As already briefly mentioned in the first chapter, these are strings of characters. Essentially, what is meant by that is text. It's necessary to surround string values with quotations. Both single ( ' ) and double ( " ) quotations are allowed in JavaScript, and there are benefits to that.

Why do we require quotations?

Quotations allow us, for example, to make sure that mathematical numbers and numbers merely meant as text are not confused. They, like semicolons and "const" variables, increase security in certainty.

Why can we use both single and double quotations?

In a case where you need either quotation in text, you can simply use the other for wrapping. Furthermore, some may visually prefer single quotations over double and vice-versa.

message = "I am hungry.";
response = "Hello hungry, I'm dad!";
preference = 'I prefer single over double.';

 

Array

Arrays represent collections of values. Their contents are wrapped in square brackets, and each value contained must be separated by a comma.

myArray = ["apple", 'bread', 4, true];

How do I specify which value I want to return from an array?

Each array has an index starting at 0 (from the first value on), counting up with every value contained. Write the array's name, as you would do when returning any other variable, and follow up with a pair of square brackets. Inside them, enter the index number of the value you'd like to return. The first value is at index 0, the second at index 1, and so on.

secondValue = myArray[1];
// secondValue is equal to 'bread'

You can also use variables to specify which value to return.

one = 1; secondValue = myArray[one];

Object

Objects are similar to arrays. But, instead of ordered numbers being used to refer to the values, with objects, so-called keys must be manually defined. Also different with objects is that they're wrapped in curly brackets. However, the comma separation works the same as with arrays.

What are keys?

Keys are names by which you refer to the values you give them to. They are placed before their values, with a colon ( : ) separating them.

shoppingList = {apples: 6, bananas: "five", total: '10$', bought: true};

How do I specify which value I want to return from an object?

Write the object's name, add a dot, and then the key of the value you'd like to return.

appleAmount = shoppingList.apples;
// appleAmount is equal to 6

Alternatively, you can also use square brackets like with arrays. You need to write the key as a string.

bananaAmount = shoppingList["bananas"]; // bananaAmount is equal to "five"

Chapter 5: Arithmetic Operators

Arithmetic operators allow us to do typical mathematical equations and more.

The following operators are available:

  • Addition ( + )
  • Subtraction ( - )
  • Multiplication ( * )
  • Division ( / )
  • Incrementation ( ++ )
  • Decrementation ( - - )
  • Exponentiation ( ** )
  • Modulus ( % )

Note: The order, in which operations are done in mathematics usually, is to be respected in JavaScript, too. You may use parentheses to control it.

Addition ( + )

With the addition operator, we can add number values together:

simpleAddition = 7 + 8;
// simpleAddition is equal to 15

It also allows us to connect string values:

simpleConnection = "Hello " + "World!";
// simpleConnection  is equal to "Hello World!"

What happens if I try to add a number value to a string value?

The number value in that case will be handled like a string value:

stringAndNumber = "He is " + 21 + " years old.";
// stringAndNumber is equal to "He is 21 years old."

Subtraction ( - )

With the subtraction operator, we can subtract number values by each other:

simpleSubtraction = 5 - 10;
// simpleSubtraction is equal to -5

Multiplication ( * )

With the multiplication operator, we can multiply number values by each other:

simpleMultiplication = 15 * 2;
// simpleMultiplication is equal to 30

Division ( / )

With the division operator, we can divide number values by each other:

simpleDivision = 5 / 2;
// simpleDivision is equal to 2.5

Incrementation ( ++ )

With the incrementation operator, we can increment a number variable by one:

simpleIncrementation = 1;
simpleIncrementation++;
// simpleIncrementation is equal to 2

This essentially is a shorthand to:

simpleIncrementation = 1;
simpleIncrementation = simpleIncrementation + 1;
// simpleIncrementation is equal to 2

Decrementation ( - - )

With the decrementation operator, we can decrement a number variable by one:

simpleDecrementation = 1;
simpleDecrementation--;
// simpleDecrementation is equal to 0

This essentially is a shorthand to:

simpleDecrementation = 1;
simpleDecrementation = simpleDecrementation - 1;
// simpleDecrementation is equal to 0

Exponentiation ( ** )

With the exponentiation operator, we can exponentially multiply number values by each other:

simpleExponentiation = 2 ** 8;
// simpleExponentiation is equal to 256

Modulus ( % )

With the modulus operator, we can divide number values by each other and return the remainder:

simpleRemainder = 9 % 2;
// simpleRemainder is equal to 1

Assignment Operations

You may combine an arithmetic operator with an equals (operator first, then equals). This has the same effect as using the variable, to which the result is being assigned to, as the first value, too.

Without assignment operation:

simpleIncrease = 10;
simpleIncrease = simpleIncrease + 5;
// simpleIncrease is equal to 15

With assignment operation:

simpleIncrease = 10;
simpleIncrease += 5;
// simpleIncrease is equal to 15

Chapter 6: Console.Log(); Hello world, the sequel!

"console.log()" is a function that's main use is for debugging, which is an extremely important process in programming. It works similarly to "alert()" in that it, too, displays a given value. The big difference lies in where said value is displayed. In the case of "console.log()", the developer console.

The developer console is part of the development tools built into your browser. They are accessed by right clicking and selecting the option "inspect". Alternatively, on most modern browsers you can also use the shortcut "CTRL + SHIFT + I". From the now open development tools menu, head to the "console" tab. This is where you'll find all "console.log()" messages.

You might say, this is a fairly well-hidden place to display a message at. That is to "console.log()'s" advantage, as this aspect makes it a great tool to display message we don't want normal users to see.

Note:"console.log()" will print values of any data type.

Example

Using "console.log()" to display a "Hello World, The Sequel!" notification:

console.log("Hello World, The Sequel!");

Conclusion

Thus ends the first lesson of JavaScript basics. Next time, we'll take a look at functions, logic operators, debugging, and more.

JavaScript Basics; Second Lesson

Helpful Resources