JavaScript Series.
Tags: javascript, basics
Published: 2021-01-05 21:08:06


## What is JavaScript?
Mozilla Developer Network, MDN defined JavaScript as
> JavaScript is a scripting or programming language that allows you to implement complex features on web pages — every time a web page does more than just sit there and display static information for you to look at — displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. — you can bet that JavaScript is probably involved. It is the third layer of the layer cake of standard web technologies, two of which are HTML and CSS.

So, basically JavaScript is used to make a web page become alive.

JavaScript was created in 1995 at Netscape by Brendan Eich. Netscape was a company that developed Netscape Navigator browser which was dominant browser before the browser war which included Microsoft's Internet Explorer.
Netscape created the Mozilla organization which developed the browser known as Firefox today.

Although initially, JavaScript was built to run on the browser and power web pages but currently JavaScript can run almost anywhere.

## JavaScript Variables and Datatypes
When writing computer programs we need to be explicit about what we want to do. Telling a computer to do something is like telling it how to do it. I can tell a human to prepare noodles for me and he/she will do so. But I can't just tell a computer to prepare noodles for me. I need to tell it how to actually prepare the noodles. Telling a computer to prepare a noodle pack will look like this.

```
get a pack of noodle from the grocery store.
tear open the pack of noodle.
get the noodle out.
heat some water.
put the noodle in the boiling water.
add the seasoning and chili, then stir.
after 2 mins bring it down the pot of noodles.
```

Although being explicit can be time consuming, but it affords us the flexibility to be super specific. The program that cooks this noodle would most likely produce the same result every time unlike a human whose noodle will taste differently every single time.

This section of this article is talking about Variables and datatypes, so why all these stories? From the above step by step approach to prepare noodles we can pick out some nouns such as noodle, pot, water, seasoning, chili, grocery store.
In a program a noun can be represented as a variable and also the state of the noun, like the noodle can be in one of three states - raw, being cooked, cooked.
The reason we need to represent those nouns and states as variables is because we will need to refer to them at different points of our program in order to carry out an operation and execute the next step.

Different data have different types, and their types determine the kind of operations that can be carried out on them.
A person's name can be represented as a string(which means a string of characters). You can think of a string as plain text.
A person's age can be represented as a number, And whether a person is up to voting age can be represented as a boolean(true or false).

JavaScript has several data types which can be split into two broad categories.

**Primitive types**
* Number
* Boolean
* String
* BigInt
* Symbol
* null
* undefined

**Reference/Structural types**
* Object
* Function

Primitive types represent simple basic data types that can represent simple pieces of information.

So now we have a little idea of what variables and data types are. But how do we define a variable in JavaScript.
```js
var variableIdentifier = VariableValue;
var name = "Victor";
var age;
age = 16;

let isProgrammer = false;

const PI = 3.14;
```
So, basically we use var, let and const keywords to define variables in JavaScript code. But there are rules while naming a variable.
* A variable identifier must not start with a number. e.g `123name`, `9mobile`.
* A variable identifier must not be any [JavaScript reserved keywords](https://www.w3schools.com/js/js_reserved.asp), such as `let`, `if`, `new`.
* A variable identifier must start with a letter, dollar sign($) or underscore(_).
A variable name should be short and descriptive as possible.
By convention, variable identifiers should be in camel case. Camel case starts with small letters and start any other word in capital letter e.g `myName`, `age`, `isOfAge`.

#### What is the difference between var, let and const?

The difference between `let` and `var` can be confusing but we'll cover it in depth later in this series.
`let` behaves in a predictable way that is similar to other programming languages than `var`. So it's advisable to use let unless you really understand the caveat associated with using `var`.

While `let` and `var` allows you to declare variables, `const` enables you to declare a constant.
A constant is a value that can't change in a program. When you know the value of a variable shouldn't change, then declaring a constant can be a good thing in order to make sure the value can't be mutated. This allows us to have a predictable program with less chances of bugs caused by mutation of a value that shouldn't be mutated.

Let's look at each data type one by one.


#### Number
A number type is used to hold numeric values that represent pieces of information such as age, account balance, CGPA.
Number can be used to both integers and floating point numbers.
```js
let age = 16;
let accountBalance = 1_000_000; // large number can be formatted like this
let CGPA = 4.95;
```
Note:
> // means single line comment in JavaScript.
/* means 
   multi
   line
   comment
*/
Anything preceded by double slash is seen as a comment and ignored by JavaScript interpreter.
Anything in between /\* and */ is seen as multi line comment and also ignored by JavaScript interpreter.

#### Boolean
Boolean type is used to represent a true or false value.
In our programs we need to ascertain if a certain condition is true or false in order to make decision. That's where booleans play a vital role.
```js
let isRich = false;
let isSmart = true;
let isLearning = true;
```
#### String
String is a data type that we can be used to represent textual values, stuff like name, WhatsApp message or Facebook post.

```js
/* String must be written within quotation marks or back ticks */
const name = "Victor"; // double quotation marks;
let department = "Biochemistry";
let bestLanguage = 'JavaScript'; // single quotation marks
let topic = `Data types`; // back ticks
```
#### BigInt
BigInt is a numeric datatype, but it differs from the number type in some ways. BigInt hold values with greater precision, values that are very big(above 2<sup>53</sup> - 1).
A limitation to this type is that it doesn't work with floating point values. When declaring a BigInt literal, we append an "n" to the number.
```js
let astronomicalValue = 400_000_000_000_000_000_000_000_000n;
```

#### Symbol
Symbol is a primitive type that guarantees a new and unique every time it's created.
```js
let sym1 = Symbol();
let sym2 = Symbol('id');
```
We'll Discuss more about the symbol type in an article covering Object Oriented Programming.


#### Null
`null` is the only value of it's type. It represents an empty value.


#### Undefined
`undefined` is also the only value of it's type. It represents no value at all.


#### Undefined vs Null
These two might seem alike but there are subtle differences.
When a variable is set to `null`, it means that the variable contains a value representing nothing. While `undefined` means that the variable contains nothing, not even the placeholder value, `null`.


So, let's look at our structured/reference types.

#### Object
An object in JavaScript can be thought of as a data type which can represent real world objects in code. Things like `Arrays`, `Date`, `window`, `document` are objects. Objects have properties and methods(functions).
```js
/*since window object is already available to us in the browser, we can access one of it's properties*/
let currentUrl = window.location.href;
console.log(currentUrl);

let date = new Date();
let fullYear = date.getFullYear(); // calling the getFullYear method of date object.
console.log(fullYear);

let person = new Person();
person.name // accessing the name property of person
```
To create a new instance of an object we use the new keyword.


#### Function
Functions are a way to group pieces of code that does a particular task together, and can be called later.
```js
function logCurrentUrl() {
    let url = window.location.href;
    console.log(url);
}
logCurrentUrl(); // calling the function
```
Objects and Functions are referred to as structural/reference types because they have an internal state or structure. We'll learn more about objects in OOP section.


## Operators
JavaScript operators enable us to write and evaluate expressions. We will cover several categories of operators.
JavaScript has unary, binary and ternary operators which acts on one, two and three operands respectively.

* Assignment operators.
* Comparison operators.
* Arithmetic operators.
* Logical operators.
* Conditional operators.

#### Arithmetic Operators

* `+` is known as **addition** operator. It is used to add two numbers together.
```js
let sum = 10 + 5;
console.log(sum) // outputs 15
```
This addition operator can also be used on strings. When used on strings, the two strings are concatenated together as one larger string.
```js
let firstName = "Victor";
let lastName = "Elezua";
let fullName = firstName + lastName;
console.log(fullName); // outputs VictorElezua
```
> NB: When using `+` operator. JavaScript does implicit type conversion. When adding a string and a number, JavaScript converts the number to a string and concatenates both. If JavaScript encounters booleans, it converts true to 1 and false to 0. `+` is the only arithmetic operator that works on operand of string type.

```js
let hiFive = "Hi" + 5; // results to Hi5
let truth = true + true; // results to 2
let nullPlus = null + null // results to 0
let undefinedPlus = undefined + undefined // results to NaN
let hiNull = "Hi" + null // results to Hinull
```
You can test these out in your browser console to see what you'll get.

* `-` unlike the addition operator, **subtraction** operator doesn't work with operands of string type. This operator is used to, as you already know, subtract one number from another.
```js
let yearOfBirth = 1995;
let currentYear = 2020;
let age = currentYear - yearOfBirth;
console.log(age); // outputs 25
```
* `/` is **division** operator. It is used to divide one number by another number.
```js
const PI = 22/7;
console.log(PI);
```
* `*` is **multiplication** operator. It is used to multiply two numbers.
```js
let totalNumberOfColors = 256 * 256 * 256;
console.log(totalNumberOfColors); // outputs 16777216
```
* `**` is the **exponentiation** operator. It's used to raise a number to the power of another number.
```js
let age = 4 ** 2;
console.log(age); // outputs 16
```
* `%` is the **modulus** operator. It's used to get the remainder of a division.
```js
let remainder = 11 % 2;
console.log(remainder); // outputs 1
```
* `++` is called **increment** operator. This operator can be prefixed or post-fixed to a number variable in order to increment by one. There is a subtle difference `++n` and `n++`.
```js
let x = 0;
console.log(++x); // outputs 1
console.log(x); // outputs 1

let y = 0;
console.log(y++); // outputs 0
console.log(y); // outputs 1
```
The prefixed increment operator increments the variable and then returns the new value. While the post-fixed increment operator return the current value, then increments the variable.

* `--` is called the **decrement** operator. It decrements the value of a variable by one. It's used in a similar manner as the increment operator.

#### Assignment Operators
* `=` is the **assignment** operator. It is used to assign an operand at the right side to a variable at the left side.
```js
let x;
console.log(x); // outputs undefined
x = 5;
console.log(x); // outputs 5
```
* `+=` is the **addition assignment** operator. It is a shorthand syntax for adding the value of both operands and assigning the result to the variable at the left side.
```js
let age = 17;
age += 1; // similar to age = age + 1;
console.log(age); // outputs 18
```
* `-=` is the **subtraction assignment** operator. It is a shorthand syntax for subtracting the value of the operand at the right side from the value of the operand from the left side, and assigning the result to the variable at the left side.
```js
let age = 17;
age -= 1; // similar to age = age - 1;
console.log(age); // outputs 16
```
Other binary arithmetic,and some logical operator can be used as the above.


#### Comparison Operators
A comparison operator compares it's operands and returns a boolean value.

* `==` is known as **equality** operator. It returns true if both operands are equal, else false. This operator tries to coerce the types of the operands into compatible before checking for equality.
```js
const adultAge = 18;
let age = 18;
let isOfAge = age == adultAge;
console.log(isOfAge); // outputs true

coerces types before comparison
console.log("20" == 20); // outputs true

// type coercion before comparison
console.log("" == 0); // outputs true
```
* `!=` is the **inequality** operator. It returns true if operands are not equal to each other, else false. This operator also coerces types just like `==` operator. It's just the exact opposite of `==`.
```js
console.log("vic" != "vic"); // outputs false
console.log(20 != 18); // outputs true
```
* `===` is known as **strict equality** operator. This operator doesn't coerce types. It first checks the type before comparing equality between the operands. If the types are not the same it returns false.
```js
console.log("20" === 20); // outputs false
console.log(20 === 20); // outputs true
```
* `!==` is known as **strict inequality** operator. This operator is the exact opposite of `===`. It returns true if the type of the values are same and the values are unequal.
```js
console.log(20 !== 23); // outputs true
console.log(20 !== "20"); // outputs true
```
* `<` is **less than** operator. It checks if the value on the left side is lesser than the value on the right side. When comparing strings, strings are compared based on their alphabetical or lexicographic ordering. Basically, if a word come before another word in the dictionary, then it is less than the latter. This comparison coerces types.
```js
console.log("vic" < "victor"); // outputs true
console.log(99 < 100); // outputs true
console.log(90 < 49); // outputs false
console.log(false < true); // outputs true
console.log(1 < ""); // outputs false
```
* `>` is called the **greater than** operator. This is used to check if the operand at the left side is greater than that at the right side. It is the exact opposite of `<` operator.
```js
console.log(5.0 > 4.5); // outputs true
console.log(true > 0); // outputs true
```
* `<=` is **less than or equal to** operator. This operator check if the operand at the left side is less than or equal to the operand on the right side.
```js
console.log(10 <= 19); // outputs true
console.log(10 <= "10"); // outputs true
console.log(20 <= 9); // outputs false
```
* `>=` is the **greater than or equal to** operator. This operator is the exact opposite of `<=` operator. It checks if the operand at the left side is greater than or equal to the operand at the right side.

#### Logical Operators
These operator are typically used with boolean values. When used with boolean values, usually they return a boolean result.

* `&&` is called **Logical AND** operator. This operator returns true when both boolean operands are true. This operator is not strictly used with only boolean operands. This operator functions in a rather surprising manner. If the left side operand is truthy, this operator then goes on to check the truthiness of the operand at the right side. Anytime a falsy value is encountered, it returns it, else it returns the truthy value at the right side. In short, this operator looks for a falsy value to return, if none, it returns the truthy value at the right side.
```js
console.log(true && true); // outputs true
console.log(true && false); // outputs false
console.log(false && true); // outputs false
console.log(false && false); // outputs false
console.log(null && true); // outputs null
console.log(null && undefined); // null
console.log(undefined && null); // undefined
console.log(0 && true); // 0
```
> Truthiness is a concept in JavaScript which allows the evaluation of non-boolean expressions/values in a boolean context.
`false`, `0`, `""`, `null` and `undefined` are all falsy values. Any other value aside from the aforementioned ones are truthy.

* `||` is the **logical OR** operator. This operator is typically used with boolean operands. It returns true when at least one of it's boolean operands is true. This operator also works with non-boolean operands. Basically, this operator looks for a falsy value to return, if none, returns the truthy value at the right side.
```js
console.log(true || true); // outputs true
console.log(true || false); // outputs true
console.log(false || false); // outputs false
console.log(false || true); // outputs true
console.log("" || 1); // outputs 1
console.log(null || true); // outputs true
console.log(false || null); // outputs null
```
* `!` is called **logical NOT** operator. This operator coerces the type of the operand into a boolean value then negates and return the value.
```js
console.log(!true); // outputs false
console.log(!false); // outputs true
console.log(!0); // outputs true
console.log(!null); // outputs true
console.log(!""); // outputs true
console.log(!undefined); // outputs true
console.log(!"Hello"); // outputs false
console.log(!20); // outputs false
```
#### Conditional Operator
Also known as ternary operator - it takes three operands. The first operand is an expression which should resolve to a boolean value, the second operand is the expression to be evaluated and returned to be if the first operand resolves to a truthy value. The third operand is an expression to be evaluated and returned if the value of the first operand is falsy.

```js
var age = 20;

var result = age > 18 ? "You can vote" : "Naaa, you can't vote";
console.log(result) // you can't vote

// similar to

if (age > 18) {
    result = "You can vote"
} else {
    result = "Naaa, you can't vote"
}
```

JavaScript has a lot more operators, but those covered above are frequently used operators. To learn more about JavaScript operators check out [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators).