# Fundamentals of JavaScript

# What is JavaScript

JavaScript is a programming language that is used to make websites interactive by adding interactivity such as animations, form-validation, or uploading texts without reloading the web page.

## Tools and Setup

Some of the tools that will be used throughout this walk through are as follows:

* Code Editor: This is like Microsoft Word but for writing code. The code editor we’ll be using in this case in the Visual Studio Code (VS Code). We also have other code editors like Sublime, Notepad++, Vim and Emacs, etc.
    
* Developer Console: Since we’re humans, we are prone to errors. To see the errors and get a lot of useful information about the errors we’ll be using <mark>developer tool</mark> which is embedded in browsers.
    

## Setup

JavaScript was originally designed to run only in web browsers.

However, in 2009, **Node.js** was introduced—an open-source, cross-platform JavaScript runtime built on Chrome’s V8 engine. Node.js allows developers to run JavaScript code outside the browser, enabling server-side programming with JavaScript for the first time.

Since we’re learning basics of programming, we will be using Node which will allows us run JavaScript on the terminal like any other programming language.

## Installing Node.js

Node.js normally comes preinstalled on Mac or Linux. To confirm this, run the command below on the terminal; `node -v` or `node --version` If you see `v.18.17.1`, it mean you have node version 18 installed on your Mac or Linux machine.

You can also check the npm (Node Version Manager) by running `npm -v`.

### Installing on Windows

1. Download the installer from Node official website here: [Node installer](https://nodejs.org/en)
    
2. Install node and npm by running the installer.
    
3. Check node and npm version on the command prompt by running `node -v` and `npm -v` .
    

### Installing on Mac

If node is not installed on your Mac PC, follow the below instructions;

1. Open your terminal and run the command `brew install node`
    
2. Then run `node -v` and `npm -v` to check the version of node installed in your machine.
    

### Using nvm

nvm stands for Node Version Manager — a tool for managing Node versions on your device.

1. Download nvm with the install script using `curl` or `wget`.
    
    ```bash
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
    
    # OR
    
    wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
    ```
    
2. Verify nvm installation by running `nvm —version` , if you see something like `0.39.7` on the terminal, it means nvm is installed successfully.
    
3. Now install the latest version of node by running `nvm install node` .
    
    To list all available Node versions, run: `nvm ls-remote`
    
    To install particular node version, e.g., v23.6.0, run: `nvm install v23.6.0`
    
    To list all node version installed on your machine, run: `nvm ls`
    
    To set your node version to a particular version, e.g., set version to v23.6.0, run: `nvm use v23.6.0`
    
    To uninstall a certain node version run: `nvm uninstall v23.6.0`
    
4. Verify Node version by running `node -v` or `node --version`
    

# JavaScript Syntax

Syntax is defined as set of rules that defines how to write code in a particular language. Think of it like a grammar for human language.

In JavaScript, correct syntax ensures code runs without errors. To understand the JavaScript ins and outs, lets explore the following;

1. ### Comments
    

Comments are used to explain code, they don’t get executed.

A single line comment is set using double slashes (`//`) while a multi-line comment is set using (`/** **/`).

```javascript
// Single line comment

/*
    Multi-line comment
*/
```

2. ### Statement
    

JavaScript statements are commands that perform an action. Each line in a JavaScript is a statement that ends in a semi-colon `(;)`

For example;

`let age = 25;`

`console.log(“Hello World!“);`

3. ### Variables
    

Variables are data stores.

# Variables and Data Types

A variable is a container or a store for a value. For example, we can store a sum of numbers in a variable named sum, or a string we might use as part of a sentence.

To use a variable, we first create it. This is referred to as <mark>declaring a variable</mark>. To declare a variable, we use the JavaScript keyword `let`.

The syntax for declaring a variable is as below;

`let [variableName];`

example; `let name;`

Once a variable is declared, you can initialize it with a value. This is done by typing the variable name followed by equal sign (=) and the value to assign to the variable.

For example; Let’s declare a variable and initialize it with a value.

`let age;`

`age = 25;`

You can declare and initialize a variable on the same line as shown below;

`let age = 25;`

Once a variable has been initialized with a value, you can change(update) that value by giving it a different value.

# Operators

Operators are symbols or keywords that are used to perform operations on values and variables. They form the backbone of almost every action in JavaScript from math to logic.

## Types of Operators

### Arithmetic Operators:

These are used to perform mathematical operations on variables. They include;

| **Operator** | **Description** | **Example** | **Result** |
| --- | --- | --- | --- |
| + | Addition | 5 + 3 | 8 |
| \- | Subtraction | 10 - 7 | 3 |
| \* | Multiplication | 4 \* 2 | 8 |
| / | Division | 10 / 2 | 5 |
| % | Modulus (Remainder) | 7 % 2 | 1 |
| \*\* | Exponentiation | 3 \*\* 2 | 9 |
| ++ | Increment | x++ | x + 1 |
| \-- | Decrement | x-- | x - 1 |

### Assignment Operator

These are used to assign values to variables. They include;

| Operator | Description | Example | Same As |
| --- | --- | --- | --- |
| \= | Assignment | x = 5 | \- |
| += | Addition assignment | x += 3 | x = x + 3 |
| \-= | Subtraction assignment | x -= 3 | x = x - 3 |
| \*= | Multiplication assignment | x \*= 4 | x = x \* 4 |
| /= | Division assignment | x /= 2 | x = x / 2 |
| %= | Modulus assignment | x %= 3 | x = x % |

Comparison Operators

These are used to compare two values and return a Boolean (true or false).

| Operator | Description | Example | Result |
| --- | --- | --- | --- |
| \== | Equal (loose equality) | 5 == ‘5’ | true |
| \=== | Strict equal (type + value) | 5 === ‘5’ | false |
| ! = | Not equal | 5 ≠ 3 | true |
| ! == | Strict not equal | 5 ! == ‘5’ | true |
| \&gt; | Greater than | 7 &gt; 3 | true |
| &lt; | Less than | 2 &lt; 5 | true |
| \&gt;= | Greater than or equal | 3 &gt;= 3 | true |
| &lt;= | Less than or equal | 4 &lt;= 6 | true |

Logical Operators

These are used to combine multiple Boolean expressions

| Operator | Description | Example | Result |
| --- | --- | --- | --- |
| && | Logical AND | true && false | false |
| ! | Logical NOT | !true | false |

## Writing JavaScript code

printing a simple “Hello World!” on the console.

```javascript
console.log("Hello, world!");
```

Variables using let and const.

```javascript
let name = "Alice";
const age = 30;

console.log(name, age);
```

Basic arithmetic

```javascript
let a = 10;
let b = 3;

console.log("Add:", a + b);
console.log("Subtract:", a - b);
console.log("Multiply:", a * b);
console.log("Divide:", a / b);
console.log("Modulus:", a % b);
```

# Control Structure and Basic Functions

Control Structures allow developers dictate the flow of the program’s execution based on conditions.

Functions on the other hand are encapsulated code-blocks for reuse and clarity.

Control structures are categorized as follows;

## a. Conditional Statements

These statements allow your code make decisions and execute certain blocks of code only if specific conditions are true/met. You may think of them as *“If this, then do that”* part of your code.

They are as follows;

1. ### if statement:
    

if statements are used to run code only if a condition is true. The syntax for if statement is as below;

```javascript
if (condition) {
    // Code to execute if the condition is true
}
```

Example:

```javascript
let age = 25;

if (age > 18) {
    console.log("You are an adult!");
}
```

2. ### if…else statement
    

The if block executes its block of code of the condition is true, and if the condition is false, the else block get’s executed.

Syntax

```javascript
if (condition) {
    // Code to execute if condtion true
} else {
    // Code to execute if condition is false
}
```

Example:

```javascript
let isRaining = true;

if (isRaining) {
    console.log("Take an Umbrella!");
} else {
    console.log("No need for an Umbrella!");
}
```

3. ### if…else if…else statement
    

This is used when you have multiple conditions to check in sequence.

Syntax

```javascript
if (condition1) {
    // code if condition is true
} else if (condition2) {
    // code if condition2 is true
} else {
    // code if none are true
}
```

Example:

```javascript
let score = 75;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else if (score >= 70) {
    console.log("Grade: C");
} else {
    console.log("Grade: F");
}
```

4. ### Switch
    

Switch is used when you want to test one variable against many exact values.

Syntax

```javascript
switch (expression) {
    case value1:
        // code to run if expression is equal to value1
        break;
    case value2:
        // code to run if expression is equal to value2
        break;
   default:
        // code if none match
}
```

Example:

```javascript
let day = "Tuesday";

switch (day) {
    case "Monday":
        console.log("First day of the week.");
        break;
    case "Tuesday":
        console.log("Second day of the week.");
        break;
    case "Wednesday":
        console.log("Third day of the week.");
        break;
    case "Thursday":
        console.log("Fourth day of the week.");
        break;
    case "Friday":
        console.log("Fifth day of the week.");
        break;
    case "Saturday":
        console.log("Sixth day of the week.");
        break;
    default:
        console.log("Just another day of the week.");
        break;
}
```

## b. Loops

Loops allow developers repeat a block of code multiple times. Loops are useful when running multiple tasks, looping through items in an array/object, avoiding repeating code manually, etc.

They include the following;

1. ### for loop
    

For loop is used to loop through a block of code a known number of times.

Syntax:

```javascript
for (initialization; condition; increment) {
    // code to run each time
}
```

Example:

```javascript
for (let i = 1; i <= 5; i++) {
    console.log(i);
}
```

let i = 1 —&gt; The start of the loop at i = 1.

i &lt;= 5 —&gt; The loop keeps running as long as this condition is true.

i++ —&gt; Adds 1 after each loop.

2. ### while loop
    

While loop loops as long as a condition is true. It is used when you do not know ahead of time how many times the loop will run.

Syntax:

```javascript
while (condition) {
    // code to run
}
```

Example:

```javascript
let i = 1;

while (i <= 5) {
    console.log(i);
    i++;
}
```

3. ### do…while
    

A do…while loop works like a while loop, but it runs at least once.

Syntax:

```javascript
do {
    // code to run
} while (condition);
```

Example:

```javascript
let i = 10;

do {
    console.log(i);
    i++;
} while (i <= 5)
```

In the above example, even though i is not equal to 5, it runs once before checking the condition.

### for…of loop

This loop is used to loop through arrays, strings, or other iterable values

Syntax:

```javascript
for (let item of iterable) {
    // use item here
}
```

Example:

```javascript
let fruits = ["apple", "bananas", "orange"];

for (let fruit of fruits) {
    console.log(fruit);
}
```

Functions

These are reusable block of codes that perform a specific task. They are used to avoid repeating code, make code modular and organized, improve readability and maintainability, etc.

Syntax:

```javascript
function functionName(parameter) {
    // code to execute
}
```

Example:

```javascript
function greet() {
    console.log("Hello World");
}
```

To use a function, you call using the function name and the parenthesis as follows;

```javascript
greet();

// output will be "Hello World"
```
