---
# System prepended metadata

title: Fundamentals of Programming in JavaScript
tags: [Notes]

---

# Fundamentals of Programming in JavaScript


## Data
**Data refers to any information that can be processed, stored, or transmitted by a computer.**

It encompasses a wide range of information, from numbers and text to images, sound, and more.

**Data is the fundamental building block of programs and computing systems. Programs exist to manipulate and work with data in various ways.**


## Data Types
JavaScript has several basic data types, which are essential for storing and manipulating data in programs. 

**A data type categorizes and defines the nature of data, specifying the allowable operations that can be performed on that data..**

Here are some of the key ones:


### Number
The Number data type is used to represent numeric values. You would use it for anything that involves calculations or arithmetic operations. For example, when storing ages, prices, or any kind of numerical data, you'd use the number data type. JavaScript supports both integer and floating-point numbers. For example:

```javascript=
// 25 is an integer
let age = 25;

// 19.99 is a floating-point number
let price = 19.99;
```


### String
The String data type represents sequences of characters used to store and manipulate textual information in programming. Strings consist of alphanumeric characters, symbols, and whitespace, enclosed within either single (' ') or double (" ") quotation marks. For example:

``` javascript
let name = "John";
let greeting = 'How are you?';
let question = "Today's Friday. What's the temperature?"
let response = "95 degrees"
```

Strings can also be enclosed in backticks (\` \`). Backticks allow for string interpolation. String interpolation is a way to put variables or values inside a string to make it more dynamic. For example:

``` javascript
let noun = "boy";
let verb1 = "walk";
let verb2 = "talk";

// The string below uses string interpolation
// The variables noun, verb1, verb2 will all be inserted into the string
let stringInt = `There is a ${noun} who likes to ${verb1} and ${verb2}`
```

### Boolean
Booleans represent true or false values and are crucial for making decisions in your code. For example:

```javascript
let isStudent = true;
let isWorking = false;
```

> *Booleans are used to represent true or false values, and they're commonly used for decision-making in your code. You might use booleans in conditions or to keep track of states or flags in your program. For instance, checking if a user is logged in (true) or not (false).*

### Null
Null is a deliberate absence of any object value.

```javascript
let emptyValue = null;
```

> *Null represents the intentional absence of any object value. It's used when you want to explicitly indicate that a variable or object doesn't have a meaningful value or hasn't been assigned yet. For example, when initializing variables before they have a proper value.*
---
## Data Manipulation
Data manipulation in programming involves modifying, transforming, or processing data to achieve specific tasks or objectives. It's at the core of what programs do.

This manipulation can encompass a variety of operations, including arithmetic calculations, text processing, filtering, sorting, and more. Manioulation typically involves the use of an operator.

Manipulation can be broken down into three steps.

1. Take Input
    a. Binary Operators (+, -, *, /) take two inputs
    b. Unary Operators (!,etc.) take one input
3. Process Input
4. Return Result

### Number Manipulation
#### Addition Operator (+)
The addition operator (+) is used to add two or more numbers.

Example:
```javascript=
// sum will be 15
let sum = 10 + 5;
```

#### Subtraction Operator (-)
The subtraction operator (-) is used to subtract one number from another.

Example:
```javascript=
// difference will be 12
let difference = 20 - 8;
```

#### Multiplication Operator (*)
The multiplication operator (*) is used to multiply two or more numbers.

Example:
```javascript=
// product will be 21
let product = 7 * 3;
```

#### Division Operator (/)
The division operator (/) is used to divide one number by another.

Example:
```javascript=
// quotient will be 5
let quotient = 15 / 3;
```

#### Modulus Operator (%)
The modulus operator (%) returns the remainder of a division operation.

Example:
```javascript=
// remainder will be 2 (17 divided by 5 leaves a remainder of 2)
let remainder = 17 % 5;
```

#### Increment Operator (+=)
The increment operator (+=) is used to add the value on the right side to the variable on the left side and assign the result back to the variable.

Example:

```javascript=
Copy code
let num = 5;
// num will be 8 (5 + 3)
num += 3;
```

#### Decrement Operator (-=)
The decrement operator (-=) is used to subtract the value on the right side from the variable on the left side and assign the result back to the variable.

Example:

```javascript=
Copy code
let total = 20;
// total will be 13 (20 - 7)
total -= 7;
```
---
### String Manipulation
#### toUpperCase()
The `toUpperCase()` method in JavaScript is used to convert all the characters in a string to uppercase.

Example:
```javascript
let str = "hello world";
let upperStr = str.toUpperCase(); // upperStr will be "HELLO WORLD"
```

#### toLowerCase()
The `toLowerCase()` method in JavaScript is used to convert all the characters in a string to lowercase.

Example:
```javascript
let str = "Hello World";
let lowerStr = str.toLowerCase(); // lowerStr will be "hello world"
```

#### concat()
The `concat()` method in JavaScript is used to concatenate (join together) two or more strings.

Example:
```javascript
let str1 = "Hello";
let str2 = " World";
let result = str1.concat(str2); // result will be "Hello World"
```

#### Interpolation
Strings can also be enclosed in backticks (\` \`). Backticks allow for string interpolation. String interpolation is a way to put variables or values inside a string to make it more dynamic. For example:

``` javascript
let noun = "boy";
let verb1 = "walk";
let verb2 = "talk";

// The string below uses string interpolation
// The variables noun, verb1, verb2 will all be inserted into the string
let stringInt = `There is a ${noun} who likes to ${verb1} and ${verb2}`
```

***In JavaScript, string manipulation methods do not change the original strings; instead, they create a new string with the desired modifications. Here's a simple way to verify this:***

```javascript=
// Define an original string
let originalString = "Hello, world!"; 
// Use a string manipulation method (toUpperCase)
let modifiedString = originalString.toUpperCase(); 

// Output the original string
console.log("Original string:", originalString);

// Output the modified string
console.log("Modified string:", modifiedString);
```
---
## Variables
**Variables in programming act as containers or placeholders for data.**

They provide a way to store and manage different types of information, which can be data of various forms like numbers, text, or more complex structures.

**Variables are essentially buckets for computer data. They store data like a bucket stores water**

### Variable Declaration
In JavaScript, variables are declared using the `let` or `const` keywords. For example:
 ```javascript=
 let name;
 let age;
 ```
**Note: The variables above are only DECLARED. They do not currently contain values. They are EMPTY variables**

### Variable Assignment 
In JavaScript, variables can be assigned values using the assignment operator `=`. For example:
```javascript=
let name = Bobbert;
let age = 21;
```
  
### Variable Reassignment
Variables can be reassigned to new values at any time using the assignment operator `=`. For example:
```javascript=
//The variable age is initially assigned the value 20
let age = 20;
//The variable age is then reassigned the value 21
age = 21
```
 ---
## Data Flow
**Data flow refers to the movement of data into and out of a program.** 

Let's use a simple calculator program as an example:

Data Flow in a Calculator Program:

- Data Going IN (Input): In a calculator program, the data going in typically includes the numbers and operators that a person enters to perform a calculation. For example, if a user wants to calculate the sum of 5 and 3, they would input the numbers "5" and "3" along with the addition operator "+".

- Data Processing: The program processes the input data by performing the specified mathematical operation. In this case, it would add the numbers together.

- Data Going OUT (Output): The result of the calculation is the data going out. In this example, if the program successfully adds 5 and 3, the result "8" is the output data.


Data flow in JavaScript involves displaying output to the console and receiving input from the user. Two key methods used for this purpose are `console.log()` and `prompt()`.

### console.log()
The `console.log()` method is used to output information to the console. It is commonly used for debugging and displaying messages or the values of variables. Here's an example of using `console.log()`:

```javascript=
console.log("Hello, world!");
let name = "Brian";
console.log(name);
```
- In the first line, the string "Hello, world!" is displayed in the console. In the second line, the value of the name variable (assuming it has been assigned a value) is printed to the console.

### prompt()
The `prompt()` method displays a dialog box to the user with a message and an input field. It allows users to enter data, which can be stored in variables for further use. Here's an example of using `prompt()`:

```javascript=
let userInput = prompt("Enter your name:");
```

- In the above code, a dialog box appears with the message "Enter your name:" and an input field. The value entered by the user is stored in the userInput variable, which can then be used in subsequent operations.

***The `prompt()` method returns the user's input as a string. If you need to convert the input to a different data type, such as a number, you can use appropriate conversion functions like `parseInt()` or `parseFloat()`.***

These data flow mechanisms, `console.log()` and `prompt()`, are essential for interacting with users and monitoring the output of your JavaScript programs.

#### Data Conversion
When using the prompt() method to obtain user input, the value entered is stored as a string. However, there are cases when we need to perform calculations or comparisons using numeric data rather than strings. That's where parseInt() and parseFloat() come into play.

- **parseInt()**: The parseInt() function is used to convert a string into an integer. It extracts and returns the whole number part from the given string, ignoring any decimal places or non-numeric characters. This function is particularly useful when dealing with numerical input from the user. Here's an example:
```javascript=
let userInput = prompt("Enter your age:");
let age = parseInt(userInput);

```
In the above code, the value entered by the user through `prompt()` is stored in the `userInput` variable as a string. By applying `parseInt()` to `userInput`, the string is converted into an integer and assigned to the `age` variable. This conversion allows us to use the `age` value for numerical operations like calculations or comparisons.

- **parseFloat()**: Similarly, the `parseFloat()` function is used to convert a string into a floating-point number. It extracts and returns the numeric value, including any decimal places, from the given string. This function is helpful when dealing with numerical input that may include decimal values. Here's an example:
```javascript=
let userInput = prompt("Enter the temperature:");
let temperature = parseFloat(userInput);
```

In the code snippet above, the user is prompted to enter a temperature value, which is stored in the `userInput` variable as a string. By applying `parseFloat()` to `userInput`, the string is converted into a floating-point number and assigned to the `temperature` variable. This conversion enables us to perform operations involving decimal values, such as calculations or comparisons.

By using `prompt()` to receive user input and then applying `parseInt()` or `parseFloat()` as needed, we can ensure that the input is properly converted into numeric data for further processing in JavaScript.

## Arrays
Arrays are flexible data structures designed to store ordered collections of elements, which can be of the same or different data types. They are essential for managing and manipulating sets of data efficiently.

### Declaring and Initializing Arrays
- **Declaring an Array:** Use square brackets `[]` to declare an empty array.
```javascript
// Declare an empty array
let myArray = [];
```
- **Initializing an Array with Values:** Populate an array with initial values using square brackets and separating elements with commas.
```javascript
// Initialize an array with numbers 1 through 5
let myArray = [1, 2, 3, 4, 5];
```

### Accessing and Modifying Array Elements
- **Accessing Elements:** Use square brackets `[]` and the index to access an element. Arrays are zero-indexed, meaning the first element is at index 0.
```javascript
// Define an array and access its elements
let myArray = ["a", "b", "c", "d", "e"];
let firstElement = myArray[0]; // Retrieves "a"
let secondElement = myArray[1]; // Retrieves "b"
```
- **Modifying Elements:** Directly modify elements of an array using their indices.
```javascript
// Update the third element in the array
let myArray = [1, 2, 3, 4, 5];
myArray[2] = 10; // Changes the third element from 3 to 10
```

### Utilizing Loops with Arrays
Efficiently process all elements in an array using loops.

- **Using `for` Loops:** Iterate over each element with a `for` loop, which provides control over the index.
```javascript
// Loop through an array with a for loop
let numbers = [1, 2, 3, 4, 5, 6, 8, 1000];
for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}
```
- **Using `forEach` Loops:** The `forEach` method executes a function for each array element, simplifying syntax and focusing on element processing.
```javascript
// Iterate over elements with forEach
let numbers = [1, 2, 3, 4, 5, 6, 8, 1000];
numbers.forEach(function(number) {
    console.log(number);
});
```
- **Using `while` Loops:** Utilize a `while` loop when the number of iterations isn't predetermined.
```javascript
// Use a while loop to iterate through an array
let i = 0;
let myArray = [1, 2, 3, 4, 5];
while (i < myArray.length) {
    console.log(myArray[i]);
    i++;
}
```

### Array Properties and Methods
Arrays come equipped with built-in properties and methods that facilitate common manipulations.

- **`length` Property:** Returns the number of elements in the array.
```javascript
// Determine the length of an array
let myArray = [1, 2, 3, 4, 5];
console.log(myArray.length); // Outputs 5
```
- **`push` and `pop` Methods:** Add or remove elements from the end of an array.
```javascript
// Adding and removing elements using push and pop
let myArray = [1, 2, 3];
myArray.push(4); // Adds 4 to the end
let removedElement = myArray.pop(); // Removes the last element
```
- **`shift` and `unshift` Methods:** Add or remove elements from the beginning of an array.
```javascript
// Using shift and unshift to modify the start of the array
let myArray = [1, 2, 3];
myArray.unshift(0); // Adds 0 to the beginning
let removedFirst = myArray.shift(); // Removes the first element
```
- **`splice` Method:** Modify an array by adding or removing elements at any position.
```javascript
// Modify an array with splice to add and remove elements
let fruits = ["apple", "banana", "cherry", "date"];
fruits.splice(1, 2, "grape"); // Replaces "banana" and "cherry" with "grape"
```

---
## Objects
Objects in JavaScript are collections of key-value pairs, serving as one of the fundamental data structures for organizing and managing data. They are versatile and can represent real-world entities within your code by grouping related data and behaviors.

### Declaring an Object
Declare an empty object using curly braces `{}`. This creates an object without any properties or methods.
```javascript
// Declare an empty object
let myObject = {};
```

### Initializing an Object with Properties
Initialize an object with properties by listing key-value pairs inside curly braces. Keys are property names and are always strings, while values can be any data type.
```javascript
// Initialize an object with properties
let person = {
  name: "John Doe",
  age: 25,
  email: "john.doe@example.com"
};
```

### Accessing Object Properties
Access properties of an object using either dot notation or square bracket notation. Dot notation is more succinct and is generally preferred when you know the property name.
```javascript
// Define an object with several properties
let person = {
  name: "John Doe",
  age: 25,
  email: "john.doe@example.com"
};

// Accessing properties using dot notation
console.log(person.name);  // Output: John Doe

// Accessing properties using square bracket notation
console.log(person["age"]);  // Output: 25
```

### Updating and Adding Object Properties
Update existing properties or add new properties to an object using the same notation used for accessing properties. If the property doesn't exist, it will be added to the object.
```javascript
// Define an object
let person = {
  name: "John Doe",
  age: 25,
  email: "john.doe@example.com"
};

// Updating an existing property
person.age = 30;

// Adding a new property
person.gender = "male";

// Display the updated object
console.log(person);  // Output: { name: 'John Doe', age: 30, email: 'john.doe@example.com', gender: 'male' }
```

### Deleting Object Properties
Remove a property from an object using the `delete` keyword. This operation modifies the object in place.
```javascript
// Define an object with several properties
let person = {
  name: "John Doe",
  age: 25,
  email: "john.doe@example.com"
};

// Deleting a property
delete person.email;

// Display the object after deletion
console.log(person);  // Output: { name: 'John Doe', age: 25 }
```

### Adding Functions/Methods to Objects
Methods are functions associated with an object, and they can manipulate the object's data. Define methods similarly to properties but assign a function as the value.
```javascript
// Define an object with a method
let person = {
  name: "John Doe",
  age: 25,
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

// Call the method
person.greet();  // Output: Hello, my name is John Doe
```
This method uses the `this` keyword, which refers to the object the method is a part of, allowing access to the object's properties and other methods.

---

## Software Engineering

### Program Purpose & Function

#### Program Purpose:
The program purpose defines the overarching goal or objective that a software application or script is designed to achieve. It encapsulates the reason why the program is created and what problem or task it aims to solve. The purpose provides clarity on the intended outcome or functionality that users or stakeholders can expect from the program.

#### Program Function (Algorithm):
The program function or algorithm refers to the step-by-step procedure or set of instructions that the program follows to accomplish its defined purpose. It outlines the logical sequence of operations that manipulate input data to produce desired output. Algorithms are structured and systematic, detailing how data is processed, transformed, and outputted based on specific rules or formulas.

#### Example
```javascript=
// Function to perform addition
function add(a, b) {
    return a + b;
}

// Function to perform subtraction
function subtract(a, b) {
    return a - b;
}

// Function to perform multiplication
function multiply(a, b) {
    return a * b;
}

// Function to perform division
function divide(a, b) {
    // Check if dividing by zero
    if (b === 0) {
        return "Error: Division by zero";
    }
    return a / b;
}

// Example usage:
let num1 = 10;
let num2 = 5;

console.log(`Addition: ${num1} + ${num2} = ${add(num1, num2)}`);
console.log(`Subtraction: ${num1} - ${num2} = ${subtract(num1, num2)}`);
console.log(`Multiplication: ${num1} * ${num2} = ${multiply(num1, num2)}`);
console.log(`Division: ${num1} / ${num2} = ${divide(num1, num2)}`);
```

Program Purpose: The calculator program is designed to serve as a digital tool for performing mathematical calculations swiftly and accurately, enhancing efficiency in performing arithmetic operations.

Program Function (Algorithm): The program follows a sequence of steps where it takes user input (numeric values and arithmetic operator), performs the specified arithmetic operation using conditional statements or switch-case statements, and outputs the result. It ensures accurate calculations while handling potential errors, such as division by zero, to provide a reliable tool for users needing mathematical computations.

---

### Debugging

Debugging is the meticulous process of identifying and resolving issues within a computer program that hinder its ability to achieve its defined purpose. It involves investigating unexpected behaviors, errors, and glitches to ensure that the program aligns with its intended objectives. Debugging is crucial to refine and optimize the code, making it effective in solving the targeted problems and meeting user needs

#### Syntax Errors

These errors occur when the code violates the rules of the JavaScript language. Examples include missing or misplaced brackets, parentheses, or semicolons. Syntax errors prevent the code from running or executing correctly.

#### Reference Errors

These errors occur when the code tries to access a variable or function that has not been declared or is out of scope. It can also occur when using variables that have been misspelled or are not defined.

#### Type Errors

These errors occur when an operation is performed on an inappropriate data type, or when certain operations are not supported for a specific data type. For example, trying to perform arithmetic operations on non-numeric values or calling methods on undefined variables.

#### Logical Errors

These errors occur when the code does not produce the expected or desired outcome due to flawed logic or incorrect algorithms. Logical errors can be challenging to identify as they do not result in error messages but affect the functionality or correctness of the program.

#### Runtime Errors

These errors occur during the execution of the program and are often caused by unexpected situations or input. Examples include division by zero, infinite loops, or invalid data input by the user.