1 Basic JavaScript - theoriginalvisagie/JavaScript-Algorithms-and-Data-Structures GitHub Wiki

What is JavaScript.

JavaScript is a scripting Language that enables you to make your web pages responsive/interactive. It is one of the core fundamental languages to understand on the route to becoming a web developer.

Comments:

Comments are lines of code that get ignored by JavaScript. We use them to comment on our code about how the code works or instructions to follow.

There are two ways to write comments in JavaScript:

1 - Using the //. This is called a single line comment. ex:

//A Single Line Comment

2 - /**/ A multiline comment. ex:

/*This is
a multiline
comment*/

It is good practice to write comments as you code to clarify what your code does.

Data Types and Variables:

Data Types:

JavaScript has 8 data types:

  1. undefined
  2. null
  3. boolean
  4. string
  5. symbol
  6. bigint
  7. number
  8. object

Variables:

Variables allows us to store and manipulate data. We use a "label" to point to the data rather than using the data itself. Any of the 8 data types can be stored within a variable.

We create/declare a variable in the following way:

var myName;

This creates a variable called "myName" Variable names can contain numbers,letters "$" or "_" but cannot contain spaces or start with a number.

You can store a value within the variable with the assignment operator (=).

var myName;
myName = "Your Name";

If you have any calculations to the right of the assignment operator, it will be calculated first and the stored in the variable.

You can also declare a variable and assign a value to it in the same line.

var myName = "Your Name";

You can also assign one variable to another.

var myName = "Name";
var newVariable = myName;

As in the above examples we have been using the string variable in JavaScript. This is called a string literal. A string is a series of zero or more characters enclosed in single or double quotes. Numbers on the other hand do not contain the quotes, ex:

var myNum = 5;

In JavaScript all variables and functions are case sensitive, meaning that myVar is not the same as MYVAR.

Best practice is to write variable names using camelCasing.

A big issue with declaring a variable using "var" is that one can easily overwrite a previously declared variable.

var name = "James";
var name = "Susan";

JavaScript one throw an error. To overcome this "let" was introduced in ES6.

let name = "James";
let name = "Susan";

the above code will throw an error in your console:

SyntaxError: unknown: Identifier 'name' has already been declared.

You can also use "const" to declare a variable. const Has all the benefits of let and it is read-only.

const FAV_PET = "Cats";

If you try and reassign a "const" your console will throw an error to you.

NB! It is common practice to use uppercase letter when using immutable(const) variables.

Basic Math Operations:

JavaScript uses the following operators to do basic mathematical calculations, "+","-","*","/".

var addNumbers = 10 + 10; // this equates to 20.
var subtractNumbers = 20 - 10; // this equates to 10.
var divedNumbers = 20 / 10; // this equates to 2.
var multiplyNumbers = 10 * 2; // this equates to 20.

In order to increment or decrement a number there are two ways:

// Increment: 
var myNum = 10;
myNum = myNum + 1; // Result is 11.

// Decrement:
var myNum = 10;
myNum = myNum - 1; // Result is 9.

The better way to do it is:

// Increment: 
var myNum = 10;
myNum++; // Result is 11.

// Decrement:
var myNum = 10;
myNum--; // Result is 9.

You can also store decimal numbers. Decimal numbers are sometimes referred to as floating point numbers or floats.

const OUR_DECIMAL = 5.7;

You can do the same basic math computations with floats as we did with normal numbers.

Remainders:

The remainder operator % gives the remainder of the division of two numbers.

5 % 2 = 1 because
Math.floor(5 / 2) = 2 (Quotient)
2 * 2 = 4
5 - 4 = 1 (Remainder)

One can check if a number is odd or even by checking the remainder of the division between a number and 2.

17 % 2 = 1 (17 is Odd)
48 % 2 = 0 (48 is Even)

Compound Assignment:

We often increase or decrease variables in programming. It has become such common practice that there are methods built into JavaScript to simplify the task for us.

For example, if we wanted to add x value to a variable, rather then doing:

myVar = myVar + 5;

We would use the following instead:

myVar += 5;

This means every time this action is performed, myVar will increase by 5, the reverse is also true, i.e.

myVar -= 5;

This also works with multiplication and division:

myVar *= 5;
myVar /= 5;

String Operations:

We know know that a string starts and ends with a single or double quote. What would we need to do if we need to assign the following to a string variable: Alan said, "Peter is learning JavaScript.".

We can escape a string in JavaScript:

const sampleStr = "Alan said, \"Peter is learning JavaScript\".";

We use \"\" to escape a string. This means that JavaScript will encapsulate everything between the "" in quotes for us.

You can start and end a string in either single or double quotes, so long as the start quote and the end quote match. We might want to include quotes within a string or save a <a> with various attributes. The issue arises when you need to use the outermost quotes within the string. We work around this by using the back slash().

const goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"'; 

Quotes are not always the only things we need to escape. The main reason why we escape strings are:

  1. To allow you to use characters you may not otherwise be able to type out, such as a newline.
  2. To allow you to represent multiple quotes in a string without JavaScript misinterpreting what you mean.

Below is a table of escaped examples:

Code Output
\' Single Quote
\" Double Quote
\\ Backslash
\n Newline
\t Tab
\r Carriage Return
\b Word Boundary
\f Form Feed

If you want to out put the following:

FirstLine
    \SecondLine
ThirdLine

You would do it as follows:

const myStr = "FirstLine\n\t\\SecondLine\nThirdLine";

In JavaScript there is a concept called Concatenation. This is when we combine two or more strings into one single string. We use the + operator to do so.

const combinedString = "The first string " + "the second string.";

We can also use the += to combine strings:

let string = "First part. ";
string += "Second part.";

You can insert one or more variables into a string by using the concatenation operator(+).

const myStr = "My name is ";
const newStr = myStr + "James";

More String Operations:

We can find the length of a string by adding .length to the end of a string.

console.log("My Name is".length);
// output would be 10.

We can also do the following:

let myStr = "My Name is";
console.log(myStr.length);
// output would be 10.

We can find the first character in a string by using bracket notation.

NB Most programming languages do not start counting at 1, but at 0. This is called Zero-based indexing.

const firstName = "Charles";
const firstLetter = firstName[0];
// Output will be "C".

We can use bracket notation to find the Nth character in a string as well.

const firstName = "Ada";
const secondLetterOfFirstName = firstName[1];
// Output will be "d".

To find the last character in a string we have to think about counting from the back. i.e.

const firstName = "Ada";
const lastLetter = firstName[firstName.length - 1];
// Output will be "a".

We can use the same principle to find the _ Nth-to-last character_. If we want to find the third to last character in Augusta, we would do the following:

const firstName = "Augusta";
const thirdToLastLetter = firstName[firstName.length - 3];
// Output will be "s".

we use the .length function, because we might not always know how long a string is.

Strings in JavaScript are immutable, meaning you cannot change the first character in a string to something else. This does not mean you cannot reassign a string to something else.

Arrays:

An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number.

We declare arrays in JavaScript the following way:

const FOOD = ["Apple","Burger","Fries"];

The beauty about arrays is we can nest the. this is called multi-dimensional arrays.

const TEAMS = [
    ["Bulls",23],
    ["White Sox", 45]    
];

As we saw with the characters of strings, arrays are also zero-indexed, meaning the first item in an array has a key of 0; If we have an array containing the following numbers, 50,60,70 and we would like to access the number "50", we would do it as follows:

const MY_NUMBERS = [50,60,70];
console.log(MY_NUMBERS[0]);
// Output will be "50".

Unlike strings, we can change the indexes and values of an array even though it has been defined as a constant.

const MY_ARRAY = [50,40,30];
MY_ARRAY[0] = 15;
// Output is [15,40,30];

As mentioned earlier, we can store arrays, within arrays. Once again this is called multi-dimensional arrays. When we use brackets to access our arrays, the first set refers to the outermost level of the array and each subsequent set refers to that level.

const arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
  [[10, 11, 12], 13, 14]
];

const subarray = arr[3]; // Output of [[10, 11, 12], 13, 14]
const nestedSubarray = arr[3][0]; // Output of [10, 11, 12]
const element = arr[3][0][1]; // Output of 11

To add data to the end of an array we use .push().

const arr1 = [1, 2, 3];
arr1.push(4); // Output of  [1, 2, 3, 4]

const arr2 = ["Simpson", "J", "cat"];
arr2.push(["happy", "joy"]); // Output of  ["Simpson", "J", "cat","happy", "joy"]

We can also add elements to the start of an array by using .unshift().

const ourArray = ["Simpson", "J", "cat"];
ourArray.unshift("Happy");
// Output of  ["Happy","Simpson", "J", "cat"]

To remove data off of the end of an array we use .pop(). We can store this "popped" of value by assigning it to a variable.

const threeArr = [1, 4, 6];
const oneDown = threeArr.pop();
console.log(oneDown); // Output of 6
console.log(threeArr); // Output of [1, 4]

If we want to remove the first element of an array we use .shift().

const ourArray = ["Simpson", "J", ["cat"]];
const removedFromOurArray = ourArray.shift(); // Output of "Simpson"

Functions:

Define a function:

We can divide our code into reusable blocks called functions. Below is an example of one:

function helloWord() {
  console.log("Hello World");
}

You can call or "invoke" the function by using its name and a set of parentheses: helloWorld();. This will print out the words "Hello World" to your console.

Function parameters:

We can pass values to a function by using parameters. These are arguments we give to the function to be able to use them within it. Parameters are variables that act as placeholders for the values that are to be input to a function when it is called.

The following function has two parameters, param1 & param2.

function testFun(param1, param2) {
  console.log(param1, param2);
}

We can then call the function and pass a string into each parameter as follows:

testFun("Hello", "World");
// Output is "Hello World".

Return a value from a function:

We can pass values into a function with arguments. You can use a return statement to send a value back out of a function.

function plusThree(num) {
  return num + 3;
}

const answer = plusThree(5);
// Output of 8.

Global Scope:

Scope refers to the visibility of variables. Variables that are defined outside of a function have a Global scope, in other words they are accessible by all the functions. Variables defined within a function can only be accessed by that function.

let myGlobal = 10

function fun1(){
  console.log(myGlobal);
}

It is possible to have both local and global variables with the same name. When you do this, the local variable takes precedence over the global variable.

const someVar = "Hat";

function myFun() {
  const someVar = "Head";
  return someVar; // Output will be "Head".
}

We can include the return statement within a function, but it is not required. WHen we call a function that doesn't have the return statement we get a returned value of undefined.

We can assign a returned value from a function to a local or global variable. Below are examples of both.

let processed = 0;

function processArg(num) {
  return (num + 3) / 5;
}

function localFunc() {
  let processed = processArg(7);
}

processed = processArg(7);

More Data Types:

Queues:

Queues are abstract data structures. Just like in real life, items are added to the back of the queue and taken from the from.

When we used the .pop() function we added items to the back of an array and when we used .shift() we removed items from the front of an array, just like a queue.

function func 1(arr, item) {
  // Add an item to the queue.
  arr.push(item);
  // Remove item from the queue.
  let firstEle = arr.shift();
}

Boolean:

A boolean can either be true or false. It can't be anything else. A boolean is like an on//off switch, where true is on and false is off.

NB Boolean values are never written with quotes.

function welcomeToBooleans() {
  return true; 
}

IF Statements:

Basic structure:

if statements are used to make decisions in code. The keyword if tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as Boolean conditions and they may only be true or false.

When the condition evaluates to true, the program executes the statement inside the curly braces. When the Boolean condition evaluates to false, the statement inside the curly braces will not execute.

function test (myCondition) {
  if (myCondition) {
    return "It was true";
  }
  return "It was false";
}

test(true); // Output is  "It was true".
test(false); // Output is "It was false".

Comparisons:

JavaScript as many comparison operators. All of them either return true or false.

Equality Operator:

The most basic one is ==. The equality operator compares two values and returns true if they're equivalent or false if they are not.

function equalityTest(myVal) {
  if (myVal == 10) {
    return "Equal";
  }
  return "Not Equal";
}

In order for JavaScript to compare different data types, it must convert on type to the other, this is known as Coercion. We can then do the following:

1   ==  1  // true
1   ==  2  // false
1   == '1' // true
"3" ==  3  // true

If we would like to do more strict comparisons, we use the strict equality operator(===). The strict operator does not perform a type conversion, thus we can check if both the type and the value are the same.

3 ===  3  // true
3 === '3' // false

Side Note! we can determine the type of a variable by using typeof(). ex. typeof(3).

Inequality Operator:

The inequality operator (!=) is the opposite of the equality operator. It means not equal and returns false where equality would return true and vice versa.

1 !=  2    // true
1 != "1"   // false
1 != '1'   // false
1 != true  // false
0 != false // false
function inequalityTest(myVal) {
  if (myVal != 10) {
    return "Not Equal";
  }
  return "Equal";
}

The strict inequality operator (!==) is the logical opposite of the strict equality operator. It means "Strictly Not Equal" and returns false where strict equality would return true and vice versa.

3 !==  3  // false
3 !== '3' // true
4 !==  3  // true

Greater Than Operator:

The greater than operator (>) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns true. Otherwise, it returns false.

5   >  3  // true
7   > '3' // true
2   >  3  // false
'1' >  9  // false
function greaterThan(myVal) {
  if (myVal > 10) {
    return "Greater Than";
  }
  return "Not Greater Than";
}

The greater than or equal to operator (>=) compares the values of two numbers. If the number to the left is greater than or equal to the number to the right, it returns true. Otherwise, it returns false.

6   >=  6  // true
7   >= '3' // true
2   >=  3  // false
'7' >=  9  // false
function greaterThanOrEqualTo(myVal) {
  if (myVal >= 10) {
    return "Greater Than Or Equal To";
  }
  return "Not Greater Than Or Equal To";
}

Less Than Operator:

The less than operator (<) compares the values of two numbers. If the number to the left is less than the number to the right, it returns true. Otherwise, it returns false. Like the equality operator, the less than operator converts data types while comparing.

2   < 5 // true
'3' < 7 // true
5   < 5 // false
3   < 2 // false
'8' < 4 // false
functionlessThan(myVal) {
  if (myVal < 10) {
    return "Less Than";
  }
  return "Not Less Than";
}

The less than or equal to operator (<=) compares the values of two numbers. If the number to the left is less than or equal to the number to the right, it returns true. If the number on the left is greater than the number on the right, it returns false. Like the equality operator, the less than or equal to operator converts data types.

4   <= 5 // true
'7' <= 7 // true
5   <= 5 // true
3   <= 2 // false
'8' <= 4 // false
functionlessThanOrEqualTo(myVal) {
  if (myVal <= 10) {
    return "Less Than Or Equal To";
  }
  return "Not Less Than Or Equal To";
}

Logical And Operator:

Sometimes you will need to test more than one thing at a time. The logical and operator (&&) returns true if and only if the operands to the left and right of it are true.

if (num > 5 && num < 10) {
  return "Yes";
}
return "No";

Logical Or Operator:

The logical or operator (||) returns true if either of the operands is true. Otherwise, it returns false.

The logical or operator is composed of two pipe symbols: (||). This can typically be found between your Backspace and Enter keys.

if (num > 10 || num < 5) {
  return "No";
}
return "Yes";

ELSE Statements:

With else statements we can further expand our code to compensate for conditions where the "if" was not true.

if (num > 10) {
  return "Bigger than 10";
} else {
  return "10 or Less";
}

We can further expand this by adding else if() to our code.

if (num > 15) {
  return "Bigger than 15";
} else if (num < 5) {
  return "Smaller than 5";
} else {
  return "Between 5 and 15";
}

Logical order If Else Statements:

Order is important in if, else if statements.

The function is executed from top to bottom so you will want to be careful of what statement comes first.

If we consider the following two statements:

function foo(x) {
  if (x < 1) {
    return "Less than one";
  } else if (x < 2) {
    return "Less than two";
  } else {
    return "Greater than or equal to two";
  }
}
function bar(x) {
  if (x < 2) {
    return "Less than two";
  } else if (x < 1) {
    return "Less than one";
  } else {
    return "Greater than or equal to two";
  }
}

foo(0) will return the string Less than one, and bar(0) will return the string Less than two.

Chaining IF ELSE statements:

if/else statements can be chained together for complex logic. Here is pseudocode of multiple chained if / else if statements:

if (condition1) {
  statement1
} else if (condition2) {
  statement2
} else if (condition3) {
  statement3
. . .
} else {
  statementN
}

Switch Statements:

A switch statement tests a value and can have many case statements which define various possible values. Statements are executed from the first matched case value until a break is encountered.

switch (lowercaseLetter) {
  case "a":
    console.log("A");
    break;
  case "b":
    console.log("B");
    break;
}

Case values are tested with strict equality (===). The break tells JavaScript to stop executing statements. If the break is omitted, the next statement will be executed.

In a switch statement you may not be able to specify all possible values as case statements. Instead, you can add the default statement which will be executed if no matching case statements are found.

switch (num) {
  case value1:
    statement1;
    break;
  case value2:
    statement2;
    break;
...
  default:
    defaultStatement;
    break;
}

If you have multiple inputs with the same output, you can represent them in a switch statement like this:

let result = "";
switch (val) {
  case 1:
  case 2:
  case 3:
    result = "1, 2, or 3";
    break;
  case 4:
    result = "4 alone";
}

Some more IF/ELSE statements:

Sometimes we use if/else statements as follows:

function isEqual(a, b) {
  if (a === b) {
    return true;
  } else {
    return false;
  }
}

There is a better way to do it. Since === returns true or false, we can return the result of the comparison:

function isEqual(a, b) {
  return a === b;
}

When a return statement is reached, the execution of the current function stops and control returns to the calling location.

function myFun() {
  console.log("Hello");
  return "World";
  console.log("byebye")
}
myFun();

The above will display the string Hello in the console, and return the string World. The string byebye will never display in the console, because the function exits at the return statement.

Objects:

Create an object:

Objects are similar to arrays. One difference is how we acceess the data. We use the properties of an object to access it's data instead of a key like with arrays.

const cat = {
  "name": "Whiskers",
  "legs": 4,
  "tails": 1,
  "enemies": ["Water", "Dogs"]
};

In the above example all the properties are to the left of the ":" symbol and their corresponding data is to the right of it.

So, the "name" property has a value of "Whiskers".

Accessing object properties:

We can access the properties on an object with dot notation.

const cat = {
  "name": "Whiskers",
  "legs": 4,
  "tails": 1,
  "enemies": ["Water", "Dogs"]
};

console.log(cat.name);
console.log(cat.enemies);

We can also use brackets to access the properties of an object.

const myObj = {
  "Space Name": "Kirk",
  "More Space": "Spock",
  "NoSpace": "USS Enterprise"
};

myObj["Space Name"];
myObj['More Space'];
myObj["NoSpace"];

Another way we can access the properties is by using variables.

const dogs = {
  Fido: "Mutt",
  Hunter: "Doberman",
  Snoopie: "Beagle"
};

const myDog = "Hunter";
const myBreed = dogs[myDog];
console.log(myBreed);

Changing object properties:

After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.

const ourDog = {
  "name": "Camper",
  "legs": 4,
  "tails": 1,
  "friends": ["everything!"]
};

ourDog.name = "Happy Camper";
// OR
ourDog["name"] = "Happy Camper";

Adding properties to an object:

You can add new properties to existing JavaScript objects the same way you would modify them.

const ourDog = {
  "name": "Camper",
  "legs": 4,
  "tails": 1,
  "friends": ["everything!"]
};

ourDog.bark = "bow-wow";
// OR
ourDog["bark"] = "bow-wow";

Removing properties to an object:

We can also delete properties from objects like this:

const ourDog = {
  "name": "Camper",
  "legs": 4,
  "tails": 1,
  "friends": ["everything!"],
  "bark": "bow-wow"
};

delete ourDog.bark;

Using Objects for Lookups:

Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to lookup values.

const alpha = {
  1:"Z",
  2:"Y",
  3:"X",
  4:"W",
  ...
  24:"C",
  25:"B",
  26:"A"
};

const thirdLetter = alpha[2];
const lastLetter = alpha[24];

const value = 2;
const valueLookup = alpha[value];

Testing Objects for Properties:

Sometimes it is useful to check if the property of a given object exists or not. We can use the .hasOwnProperty(propname) method of objects to determine if that object has the given property name. .hasOwnProperty() returns true or false if the property is found or not.

const myObj = {
  top: "hat",
  bottom: "pants"
};

myObj.hasOwnProperty("top"); // return true.
myObj.hasOwnProperty("middle"); // return false.

More Objects:

Objects are a way to handle lots of flexible data. They allow for arbitrary combinations of strings, numbers, booleans, arrays, functions, and objects.

Below is an array containing objects within it. The objects are within the curly {} braces.

const ourMusic = [
  {
    "artist": "Daft Punk",
    "title": "Homework",
    "release_year": 1997,
    "formats": [ 
      "CD", 
      "Cassette", 
      "LP"
    ],
    "gold": true
  },
  {
    artist: "Deep Purple",
    title: "Smoke on the water",
    release_year: 1976,
    formats: [
      "CD", 
      "8T", 
      "LP"
    ],
    "gold": false
  }
];

We can access the nested properties the same way we accessed them in previous lessons. All we do is chain together dot or bracket notation.

const ourStorage = {
  "desk": {
    "drawer": "stapler"
  },
  "cabinet": {
    "top drawer": { 
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottom drawer": "soda"
  }
};

ourStorage.cabinet["top drawer"].folder2;
ourStorage.desk.drawer;

As we have seen in earlier examples, objects can contain both nested objects and nested arrays. Similar to accessing nested objects, array bracket notation can be chained to access nested arrays.

const ourPets = [
  {
    animalType: "cat",
    names: [
      "Meowzer",
      "Fluffy",
      "Kit-Cat"
    ]
  },
  {
    animalType: "dog",
    names: [
      "Spot",
      "Bowser",
      "Frankie"
    ]
  }
];

ourPets[0].names[1];
ourPets[1].names[0];

Loops:

You can run the same code multiple times by using a loop. This makes it easier for us as developers as we only have to write one small block of code te perform the same function multiple times.

While Loops:

The first type of loop we will learn is called a while loop because it runs while a specified condition is true and stops once that condition is no longer true.

const ourArray = [];
let i = 0;

while (i < 5) {
  ourArray.push(i);
  i++;
}

For Loops:

The most common type of JavaScript loop is called a for loop because it runs for a specific number of times.

For loops are declared with three optional expressions separated by semicolons for (a; b; c):

  • a: initialization statement
  • b: condition statement
  • c: final expression

In the following example we initialize with i = 0 and iterate while our condition i < 5 is true. We'll increment i by 1 in each loop iteration with i++ as our final expression.

const ourArray = [];

for (let i = 0; i < 5; i++) {
  ourArray.push(i);
}

We can change the final expression to "skip" counts i.e.

const myArray = [];

for (let i = 1; i <= 9; i+=2) {
  myArray.push(i);
}

In the above example we are pushing all the ODD numbers between 1 and 9 into myArray by incrementing i with 2 instead of 1.

We can also count backwards with a for loop. We just need to make sure our initialization statement is greater than 0 and our final expression is i-- OR i-=.

const ourArray = [];

for (let i = 10; i > 0; i -= 2) {
  ourArray.push(i);
}

For loops and arrays:

A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a for loop. This code will output each element of the array arr to the console:

const arr = [10, 9, 8, 7, 6];

for (let i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}

Nesting For Loops:

If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example.

const arr = [
  [1, 2], [3, 4], [5, 6]
];

for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr[i].length; j++) {
    console.log(arr[i][j]);
  }
}

Do...While Loops:

The next type of loop you will learn is called a do...while loop. It is called a do...while loop because it will first do one pass of the code inside the loop no matter what, and then continue to run the loop while the specified condition evaluates to true.

const ourArray = [];
let i = 0;

do {
  ourArray.push(i);
  i++;
} while (i < 5);

Recursion:

Recursion is the concept that a function can be expressed in terms of itself. To help understand this, start by thinking about the following task: multiply the first n elements of an array to create the product of those elements. Using a for loop, you could do this:

  function multiply(arr, n) {
    let product = 1;
    for (let i = 0; i < n; i++) {
      product *= arr[i];
    }
    return product;
  }

However, notice that multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]. That means you can rewrite multiply in terms of itself and never need to use a loop.

 function multiply(arr, n) {
    if (n <= 0) {
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1];
    }
  }

The recursive version of multiply breaks down like this. In the base case, where n <= 0, it returns 1. For larger values of n, it calls itself, but with n - 1. That function call is evaluated in the same way, calling multiply again until n <= 0. At this point, all the functions can return and the original multiply returns the answer.

Math Functions:

Math.random():

Random numbers are useful for creating random behavior.

JavaScript has a Math.random() function that generates a random decimal number between 0 (inclusive) and 1 (exclusive). Thus Math.random() can return a 0 but never return a 1.

function randomFraction() {
  return Math.random();
}

Math.floor():

The Math.floor() function rounds the value down to the nearest whole number.

function floorFraction() {
  let value = 2.4;
  return Math.floor(value);
  // Output of 2.
}

paseInt:

The parseInt() function parses a string and returns an integer. Here's an example:

const a = parseInt("007");
// Output is 7.

The parseInt() function parses a string and returns an integer. It takes a second argument for the radix, which specifies the base of the number in the string. The radix can be an integer between 2 and 36.

const a = parseInt("11", 2);
// Output is 3 as "11" is the binary equivalent of 3.

The radix variable says that 11 is in the binary system, or base 2. This example converts the string 11 to an integer 3.

In other words, the string that you pass is the binary equivalent of the integer.

The Ternary Operator:

The conditional operator, also called the ternary operator, can be used as a one line if-else expression.

The syntax is a ? b : c.

  • a: The condition.
  • b: The code to run if condition is true.
  • c: The code to run if condition is false.

We can thus take the following if statement:

function findGreater(a, b) {
  if(a > b) {
    return "a is greater";
  }
  else {
    return "b is greater or equal";
  }
}

And change it to this:

function findGreater(a, b) {
  return a > b ? "a is greater" : "b is greater or equal";
}

Multiple Ternary Operators:

The following function uses if, else if, and else statements to check multiple conditions:

function findGreaterOrEqual(a, b) {
  if (a === b) {
    return "a and b are equal";
  }
  else if (a > b) {
    return "a is greater";
  }
  else {
    return "b is greater";
  }
}

We can rewrite it as follows:

function findGreaterOrEqual(a, b) {
  return (a === b) ? "a and b are equal" 
    : (a > b) ? "a is greater" 
    : "b is greater";
}