javaScript Basics

Perfect people don't drink, don't fight, don't lie, don't make mistakes and...don't exist

Paulo Coelho

Hello, my Name is Christopher. I'm learning Frontend Web Devlopment on my own. I've found several resourses available to anyone wanting to learn web development.

I use a few different web sites for free courses and reference material, like "Free code Camp", "W3 Schools" and "MDN Web Docs". I use these sites for theory, testing and documentation. I also found lots of videos on YouTube that were great for beginers right up to more advanced programming. I did find the theory and having lectures from videos beneficial but they just didn't complete the learning process, I had to take notes too. I try to reference the sites I used for source material when possible in my notes.

I've started to build several reference document web pages to practice building web pages while taking notes on different subjects.


JavaScript

JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat. JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.

freeCodeCamp

javaScript Algorithms and Data Structures

Free Code Camp

Softcorp TV

Vanilla javaScript

  comment your Javascript code 4:22
  data types and variables 5:58
  storing values with assignment operator 9:14
  initializing variables with assignment operator 11:33
  uninitialized variables 12:00
  case sensitivity in variables 12:41
  adding numbers 14:05
  subtracting numbers 14:36
  multiplying numbers 14:53
  dividing numbers15:11
  incermenting numbers 15:30
  decrementing numbers15:59
  decimal numbers 16:23
  multiply decimals 16:50
  divide decimals 17:18
  finding a remainder 17:35
  compound assignment with augmented addition 18:22
  compound assignment with augmented subtraction 19:21
  compound assignment with augmented multiplication 20:20
  compound assignment with augmented division 20:52
  declare string variables 21:21
  escaping literal quotes in strings 22:02
  quotinq strings with single quotes 22:43
  escape sequences in strings 25:19
  concatenating string with plus operator 26:48
  concatenating string with variables 29:01
  appending variables to strings 30:15
  find a length of string 31:12
  bracket notation to find first character in string 32:01
  bracket notation to find Nth character in string34:24
  bracket notation to find last character in string34:54
  word blanks 36:31
  store multiple values with arrays40:45
  nested arrays 41:44
  access array data with indexes42:35
  modify array data with indexes 43:37
  access multi-dimensional arrays with indexes 44:47
  manipulate arrays with pop() 47:28
  manipulate arrays with shift() 48:35
  manipulate arrays with unshift() 49:23
  shopping list 50:37
  write reusable code with functions 51:43
  passing values to functions with arguments 53:41
  global scope and functions 55:44
  local scope and functions 59:32
  understand undefined value returned from a function 1:03:56
  assignment with a returned value1:04:53
  stand in line 1:05:53
  boolean values 1:08:41
  use conditional logic with if statements 1:09:24
  comparison with the strict equality operator 1:13:20
  practice comparing different values 1:14:42
  comparison with inequality operator1:15:38
  comparison with greater than or equal to operator1:17:39
  comparison with less than or equal to operator1:18:45
  comparison with the logical and operator1:19:18
  comparison with the logical or operator 1:20:42
  else statements 1:21:38
  else if statements 1:22:28
  chaining if else statements 1:24:45
  golf code 1:27:47
  switch statement1:32:14
  default option in switch statements 1:35:46
  multiple identical options in switch statements 1:37:25
  replacing if else chins with switch 1:39:20
  returning boolean value form functions1:41:11
  returning an early pattern from functions1:42:20
  counting cards 1:43:38
  build javascript objects1:49:12
  accessing object properties with dot notation1:50:47
  accessing object properties with bracket notation1:51:34
  accessing object properties with variables1:52:48
  updating object properties 1:53:36
  add new property to an object 1:54:31
  delete properties form an object1:55:19
  using objects for lookups 1:55:55
  testing objects for properties 1:57:46
  manipulating complex objects1:59:15
  accessing nested objects 2:01:03
  accessing nested arrays 2:01:52
  record collection 2:03:05
  iterate with while oop 2:10:15
  iterate with for loops 2:11:34
  iterate odd numbers with a for loop 2:13:56
  count backwards with a for loop2:15:29
  iterative through an array with for loop 2:17:08
  nesting for loops 2:19:43
  nesting with do..while loops 2:22:45
  profile lookup 2:24:12
  generate random fractions 2:28:18
  generate random whole numbers 2:28:55
  generate random whole numbers within a range 2:30:24
  use the parseInt function 2:31:47
  use the parseInt function with a radix 2:32:37
  use the conditional(ternary) operator 2:33:29
  use multiple conditional (ternary)operators 2:34:58
  difference between the var and let keywords2:36:58
  compare scopes of the var and let keywords2:39:05
  declare a read-only variable with the const keyword2:41:35
  mutate an array declared with const 2:43:41
  prevent object mutation 2:44:53
  use arrow function to write concise anonymous functions 2:47:17
  write arrow functions with parameters 2:48:23
  write higher order arrow functions2:49:26
  write higher order arrow functions 2:53:05
  use the spread operator to evaluate arrays In-Place 2:55:33
  use destruction in assignment to assign variables from objects 2:57:18
  destructuring assignment with nested objects 3:00:17
  use destructuring assignment to assign variables from arrays 3:01:54
  use destructuring assignment with the rest operator 3:03:42
  create string using template literals 3:06:39
  write concise object literal declarations using simple fields 3:10:42
  write concise declarative functions 3:12:24
  use class syntax to define a constructor function 3:12:59
  use getters and setters to control access to an object 3:15:10
  understanding the differences between import and require 3:20:25
  use export to reuse a code block 3:22:33
  use * to import everything from a file 3:23:40
  create an export fallback with export default 3:24:50
  import a default export 3:25:25
  Outro  3:26:18
    

Data Types:

JavaScript provides eight different data types.

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

Every Variable has a data type that tells what kind of data is being stored in a variable. There are two types of data types in JavaScript namely Primitive data types and Non-primitive data types.

Primitive Data Types:

The predefined data types provided by JavaScript language are known as primitive data types. Primitive data types are also known as in-built data types.

  1. undefined
  2. null
  3. boolean
  4. string
  5. number

Non-Primitive Data Types:

The data types that are derived from primitive data types of the JavaScript language are known as non-primitive data types. It is also known as derived data types or reference data types.

  • object
  • array

Data Type Definitions

undefined: A variable that has not been assigned a value has the value: undefined.


null: The Null type has exactly one value: null.


boolean: Boolean represents a logical entity and can have two values: true and false.


string: JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it.

Unlike some programming languages (such as C), JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it.

However, it is still possible to create another string based on an operation on the original string.


number:


symbol: A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called "atoms".


bigint: The BigInt type is a numeric primitive in JavaScript that can represent integers with arbitrary precision.


object: In computer science, an object is a value in memory which is possibly referenced by an identifier.

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String value or a Symbol value.

There are two types of object properties: The data property and the accessor property.

Data property: Associates a key with a value

Accessor property: Associates a key with one of two accessor functions (get and set) to retrieve or store a value.


Variables:

Declare JavaScript Variables

In computer science, data is anything that is meaningful to the computer. JavaScript provides eight different data types which are undefined, null, boolean, string, symbol, bigint, number, and object.

For example, computers distinguish between numbers, such as the number 12, and strings, such as "12", "dog", or "123 cats", which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.

Variables allow computers to store and manipulate data in a dynamic fashion. They do this by using a "label" to point to the data rather than using the data itself. Any of the eight data types may be stored in a variable.

Variables are similar to the x and y variables you use in mathematics, which means they're a simple name to represent the data we want to refer to. Computer variables differ from mathematical variables in that they can store different values at different times.

We tell JavaScript to create or declare a variable by putting the keyword var, let or const in front of it

In JavaScript, you can store a value in a variable with the assignment operator (=).

var

          
  var myVar = "Hello World!";

  console.log(myVar);
            
        

If there are any calculations to the right of the = operator, those are performed before the value is assigned to the variable on the left of the operator.

          
  var myVar = 2 + 2;

  console.log(myVar);
            
        

Note:

One of the biggest problems with declaring variables with the var keyword is that you can easily overwrite variable declarations:

In a small application, you might not run into this type of problem. But as your codebase becomes larger, you might accidentally overwrite a variable that you did not intend to. Because this behavior does not throw an error, searching for and fixing bugs becomes more difficult.


ES6 variables

let

So unlike var, when you use let, a variable with the same name can only be declared once.

          
  var camper = "James";
  var camper = "David";

  console.log(camper);
            
        

This will not cause an error using the keyword var.

          
  let camper = "James";
  let camper = "David";
  
  console.log(camper);
            
        

This will cause a redeclaration of let error.

          
  let camper = "James";
  camper = "David";
  
  console.log(camper);
            
        

This will not cause an error. You are not redeclaring the variable just changing the value.


const

The keyword let is not the only new way to declare variables. In ES6, you can also declare variables using the const keyword.

const has all the awesome features that let has, with the added bonus that variables declared using const are read-only. They are a constant value, which means that once a variable is assigned with const, it cannot be reassigned:

          
  const FAV_PET = "Cats";
  FAV_PET = "Dogs";

  console.log(FAV_PET);
          
        

This will cause an invalid assignment to const error.


A common practice when naming constants is to use all uppercase letters, with words separated by an underscore.

You should always name variables you don't want to reassign using the const keyword. This helps when you accidentally attempt to reassign a variable that is meant to stay constant.


Note:

It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays). You will learn more about objects, arrays, and immutable and mutable values in later challenges. Also in later challenges, you will see examples of uppercase, lowercase, or camelCase variable identifiers.


Best Practices

Write variable names in JavaScript in camelCase. In camelCase, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.


Uninitialized Variables

When JavaScript variables are declared, they have an initial value of undefined. If you do a mathematical operation on an undefined variable your result will be NaN which means "Not a Number". If you concatenate a string with an undefined variable, you will get a literal string of undefined.


Numbers

Adding numbers

Number is a data type in JavaScript which represents numeric data.

JavaScript uses the + symbol as an addition operator when placed between two numbers.

        
  const myVar = 5 + 10;

  console.log(myVar);
          
      

myVar now has the value 15.


Subtracting numbers

We can also subtract one number from another.

JavaScript uses the - symbol for subtraction.

const myVar = 12 - 6; console.log(myVar);

myVar would have the value 6.


Multiplying numbers

We can also multiply one number by another.

JavaScript uses the * symbol for multiplication of two numbers.

        
const myVar = 13 * 13;

console.log(myVar);
          
      

myVar would have the value 169.


Dividing numbers

We can also divide one number by another.

JavaScript uses the / symbol for division.

        
  const myVar = 16 / 2;
  
  console.log(myVar);
          
      

myVar now has the value 8.


Increment a number

You can easily increment or add one to a variable with the ++ operator.

        
 i++;
        
      

is the equivalent of

        
 i = i + 1; 
        
      

Note:

The entire line becomes i++;, eliminating the need for the equal sign.


Decrement a Number

You can easily decrement or decrease a variable by one with the -- operator.

i--;

is the equivalent of

           
  i = i - 1; 
          
        

Note:

The entire line becomes i--;, eliminating the need for the equal sign.


Decimal Numbers

We can store decimal numbers in variables too. Decimal numbers are sometimes referred to as floating point numbers or floats.

Note:

Not all real numbers can accurately be represented in floating point. This can lead to rounding errors.

Floating-point arithmetic


Multiply Two Decimals

In JavaScript, you can also perform calculations with decimal numbers, just like whole numbers.

const product = 2.0 * 5.5; console.log(product);

product now has a value of 11


Divide One Decimal by Another

const quotient = 4.4 / 2.0; console.log(quotient); 2.2

quotient now has a value of 2.2


Finding a Remainder

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)

Usage:

In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by 2.

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

Note:

The remainder operator is sometimes incorrectly referred to as the modulus operator. It is very similar to modulus, but does not work properly with negative numbers.


Compound Assignment With Augmented Addition

In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say:

          
  let myVar = 1;
  myVar = myVar + 5;

  console.log(myVar);
          
        

to add 5 to myVar. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.

One such operator is the += operator.

          
  let myVar = 1;
  myVar += 5;

  console.log(myVar);
          
        

6 would be displayed in the console in both code examples.


Compound Assignment With Augmented Subtraction

Like the += operator, -= subtracts a number from a variable.

          
  let myVar = 15;
  myVar = myVar - 5;

  console.log(myVar);
          
        

will subtract 5 from myVar. This can be rewritten as:

          
  let myVar = 15;
  myVar -= 5;

  console.log(myVar);
          
        

10 would be displayed in the console in both code examples.


Compound Assignment With Augmented Multiplication

The *= operator multiplies a variable by a number.

          
  let myVar = 5;
  myVar = myVar * 5;

  console.log(myVar);
          
        

will multiply myVar by 5. This can be rewritten as:

          
  let myVar = 5;
  myVar *= 5;

  console.log(myVar);
          
        

25 would be displayed in the console in both code examples.


Compound Assignment With Augmented Division

The /= operator divides a variable by another number.

          
  let myVar = 15;
  myVar = myVar / 5;

  console.log(myVar);
          
        

will multiply myVar by 5. This can be rewritten as:

          
  let myVar = 15;
  myVar /= 5;

  console.log(myVar);
          
        

3 would be displayed in the console in both code examples.


Strings

Escaping Literal Quotes in Strings

When you are defining a string you must start and end with a single or double quote. What happens when you need a literal quote: " or ' inside of your string?

In JavaScript, you can escape a quote from considering it as an end of string quote by placing a backslash (\) in front of the quote.

        
  const sampleStr = "Alan said, \"Peter is learning JavaScript\".";
          
  console.log(sampleStr)
        
      

This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string. So if you were to print this to the console, you would get:

This will print to the console as

Alan said, "Peter is learning JavaScript".


Quoting Strings with Single Quotes

String values in JavaScript may be written with single or double quotes, as long as you start and end with the same type of quote. Unlike some other programming languages, single and double quotes work the same in JavaScript.

        
  const doubleQuoteStr = "This is a string";

  const singleQuoteStr = 'This is also a string';
        
      

The reason why you might want to use one type of quote over the other is if you want to use both in a string. This might happen if you want to save a conversation in a string and have the conversation in quotes. Another use for it would be saving an <a> tag with various attributes in quotes, all within a string.

        
  const conversation = 'Fin exclaims to Jake, "Algebraic"';
        
      

However, this becomes a problem if you need to use the outermost quotes within it. Remember, a string has the same kind of quote at the beginning and end. But if you have that same quote somewhere in the middle, the string will stop early and throw an error.

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

  const badStr = 'Finn responds, "Let's go!"';
            
          

Here badStr will throw an error.

In the goodStr above, you can use both quotes safely by using the backslash \ as an escape character.

Note:

The backslash \ should not be confused with the forward slash /. They do not do the same thing.


Escape Sequences in Strings

Quotes are not the only characters that can be escaped inside a string. There are two reasons to use escaping characters:

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

code output
\' single quote
\" double quote
\\ backslash
\n newline
\r carriage return
\t tab
\b word boundry
\f form feed

Note:

The backslash itself must be escaped in order to display as a backslash.


Concatenating Strings with Plus Operator

In JavaScript, when the + operator is used with a String value, it is called the concatenation operator. You can build a new string out of other strings by concatenating them together.

        
  const ourStr = "I come first. " + "I come second.";

  console.log(ourStr)
        
      

This will print to the console as.

I come first. I come second.

Note:

Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.

Concatenating Strings with the Plus Equals Operator

We can also use the += operator to concatenate a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines.

        
  let ourStr = "I come first. ";
  ourStr += "I come second.";
          
  console.log(ourStr);
        
      

This will print to the console as

I come first. I come second.

Note:

Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.

Constructing Strings with Variables

Sometimes you will need to build a string. By using the concatenation operator (+), you can insert one or more variables into a string you're building.

        
  const ourName = "freeCodeCamp";
  const ourStr = "Hello, our name is " + ourName + ", how are you?";

  console.log(ourName);
        
      

This will print to the console as

Hello, our name is freeCodeCamp, how are you?


Appending Variables to Strings

Just as we can build a string over multiple lines out of string literals, we can also append variables to a string using the plus equals (+=) operator.

        
  const anAdjective = "awesome!";
  let ourStr = "freeCodeCamp is ";
  ourStr += anAdjective;

  console.log(ourStr)
        
      

This will print to the console as

freeCodeCamp is awesome!


Find the Length of a String

You can find the length of a String value by writing .length after the string variable or string literal.

string literal

        
  console.log("Alan Peter".length);
        
      

This will print to the console as

10

string variable

        
  const firstName = "Ada";

  console.log(firstName.length);
        
      

This will print to the console as

3


Bracket Notation to Find the First Character in a String

Bracket notation is a way to get a character at a specific index within a string.

Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as Zero-based indexing.

For example, the character at index 0 in the word Charles is C. So if const firstName = "Charles", you can get the value of the first letter of the string by using firstName[0].

        
  const firstName = "Charles";
  const firstLetter = firstName[0];

  console.log(firstLetter);
        
      

This will print to the console as

C


Understand String Immutability

In JavaScript, String values are immutable, which means that they cannot be altered once created.

For example, the following code:

        
  let myStr = "Bob";
  myStr[0] = "J";
        
      

cannot change the value of myStr to Job, because the contents of myStr cannot be altered. Note that this does not mean that myStr cannot be changed, just that the individual characters of a string literal cannot be changed. The only way to change myStr would be to assign it with a new string, like this:

        
  let myStr = "Bob";
  myStr = "Job";
        
      

Bracket Notation to Find the Nth Character in a String

You can also use bracket notation to get the character at other positions within a string.

Remember that computers start counting at 0, so the first character is actually the zeroth character.

        
  const firstName = "Ada";
  const secondLetterOfFirstName = firstName[1];

  console.log(secondLetterOfFirstName);
        
      

This will print to the console as

d


Bracket Notation to Find the Last Character in a String

In order to get the last letter of a string, you can subtract one from the string's length.

For example, if const firstName = "Ada", you can get the value of the last letter of the string by using firstName[firstName.length - 1].

        
  const firstName = "Ada";
  const lastLetter = firstName[firstName.length - 1];

  console.log(lastLetter);
        
      

This will print to the console as

a


Bracket Notation to Find the Nth-to-Last Character in a String

You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.

For example, you can get the value of the third-to-last letter of the const firstName = "Augusta" string by using firstName[firstName.length - 3]

        
  const firstName = "Augusta";
  const thirdToLastLetter = firstName[firstName.length - 3];

  console.log(thirdToLastLetter);
        
      

This will print to the console as

s


Arrays

Store Multiple Values in one Variable using JavaScript Arrays

With JavaScript array variables, we can store several pieces of data in one place.

You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:

        
  const sandwich = ["peanut butter", "jelly", "bread"];
        
      

Nest one Array within Another Array

You can also nest arrays within other arrays, like below:

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

This is also called a multi-dimensional array.


Access Array Data with Indexes

We can access the data inside arrays using indexes.

Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use zero-based indexing, so the first element in an array has an index of 0.

        
  const array = [50, 60, 70];
  array[0];
  const data = array[1];
        
      

array[0] is now 50, and data has the value 60.

Note:

There shouldn't be any spaces between the array name and the square brackets, like array [0]. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.


Modify Array Data With Indexes

Unlike strings, the entries of arrays are mutable and can be changed freely, even if the array was declared with const.

        
  const ourArray = [50, 40, 30];
  ourArray[0] = 15;

  console.log(ourArray);
        
      

This will print to the console as

[15, 40, 30]


Access Multi-Dimensional Arrays With Indexes

One way to think of a multi-dimensional array, is as an array of arrays. When you use brackets to access your array, the first set of brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside.

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

  console.log(arr[3]);
  console.log(arr[3][0]);
  console.log(arr[3][0][1]);
        
      

This will print to the console respectively as

[[10, 11, 12], 13, 14]

[10, 11, 12]

[11]

Note:

There shouldn't be any spaces between the array name and the square brackets, like array [0][0] and even this array [0] [0] is not allowed.


Manipulate Arrays With push()

An easy way to append data to the end of an array is via the .push() function.

.push() takes one or more parameters and "pushes" them onto the end of the array.

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

  const arr2 = ["Stimpson", "J", "cat"];
  arr2.push(["happy", "joy"]);

  console.log(arr1);
  console.log(arr2);
        
      

This will print to the console respectively as;

[1, 2, 3, 4]

["Stimpson", "J", "cat", ["happy", "joy"]]


Manipulate Arrays With pop()

Another way to change the data in an array is with the .pop() function.

.pop() is used to pop a value off of the end of an array. We can store this popped off value by assigning it to a variable. In other words, .pop() removes the last element from an array and returns that element.

Any type of entry can be popped off of an array - numbers, strings, even nested arrays.

This will remove the last element in the array

        
  const threeArr = [1, 4, 6];
  threeArr.pop();

  console.log(threeArr);
        
      

This will print to the console as;

[1, 4]

Note:

When using this code you won't know what element was removed.

Best Practice

If you want to know what element was removed you can do so by putting it into a variable and use the .pop() on the array.

        
  const threeArr = [1, 4, 6];
  const popElementIntoVar = threeArr.pop();

  console.log(threeArr);
  console.log(popElementIntoVar);
        
      

This will print to the console respectively as;

[1, 4]

6


Manipulate Arrays With shift()

pop() always removes the last element of an array. What if you want to remove the first?

That's where .shift() comes in. It works just like .pop(), except it removes the first element instead of the last.

This will remove the first element in the array

        
  const ourArray = ["Stimpson", "J", ["cat"]];
  ourArray.shift();

  console.log(ourArray;)
        
      

This will print to the console as;

["J", ["cat"]]


Best Practice

If you want to know what element was removed you can do so by putting it into a variable and use the .shift() on the array.

        
  const ourArray = ["Stimpson", "J", ["cat"]];
  const shiftElementIntoVar = ourArray.shift();

  console.log(ourArray);
  console.log(shiftElementIntoVar);
        
      

This will print to the console respectively as;

["J", ["cat"]]

Stimpson


Manipulate Arrays With unshift()

Not only can you shift elements off of the beginning of an array, you can also unshift elements to the beginning of an array i.e. add elements in front of the array.

.unshift() works exactly like .push(), but instead of adding the element at the end of the array, unshift() adds the element at the beginning of the array.

        
  const ourArray = ["Stimpson", "J", "cat"];
  ourArray.shift();
  ourArray.unshift("Happy");
        
      

After the shift, ourArray would have the value ["J", "cat"]. After the unshift, ourArray would have the value ["Happy", "J", "cat"].


Functions

Write Reusable JavaScript with Functions

In JavaScript, we can divide up our code into reusable parts called functions.

Here's an example of a function:

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

  functionName();
        
      

You can call or invoke this function by using its name followed by parentheses, like this: functionName(); Each time the function is called it will print out the message Hello World on the dev console. All of the code between the curly braces will be executed every time the function is called.

This will print to the console as;

Hello World


Passing Values to Functions with Arguments

Parameters are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or "passed") into a function when it is called are known as arguments.

Here is a function with two parameters, param1 and param2:

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

  testFun("Hello", "World");
        
      

Then we can call testFun like this: testFun("Hello", "World");. We have passed two string arguments, Hello and World. Inside the function, param1 will equal the string Hello and param2 will equal the string World. Note that you could call testFun again with different arguments and the parameters would take on the value of the new arguments.

This will print to the console as;

Hello World


This is the same code but using numbers as arguments and doing a simple math evaluation to find the sum of the two parameters.

        
  function testFun(a, b) {
    console.log(a + b);
  }

  testFun(7, 9);
        
      

This will print to the console as;

16


Return a Value from a Function with Return

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);
          
        

answer has the value 8.

plusThree takes an argument for num and returns a value equal to num + 3.


Global Scope and Functions

In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.

Variables which are declared without the let or const keywords are automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with let or const.


Local Scope and Functions

Variables which are declared within a function, as well as the function parameters, have local scope. That means they are only visible within that function.

Here is a function myTest with a local variable called loc.

          
  function myTest() {
    const loc = "foo";
    console.log(loc);
  }

  myTest();
  console.log(loc);
          
        

The myTest() function call will display the string foo in the console from the console.log(loc) inside the function. The console.log(loc) line will throw an error, as loc is not defined outside of the function.


Global vs. Local Scope in Functions

          
  const someVar = "Hat";

  function myFun() {
    const someVar = "Head";
    return someVar;
  }

  console.log(myFun())
          
        

The function myFun will return the string Head because the local version of the variable is present.


Understanding Undefined Value returned from a Function

A function can include the return statement but it does not have to. In the case that the function doesn't have a return statement, when you call it, the function processes the inner code but the returned value is undefined.

          
  let sum = 0;

  function addSum(num) {
    sum = sum + num;
  }

  addSum(3);

  console.log(sum); // displays 3
  console.log(addSum()) // displays undefined
          
        

addSum is a function without a return statement. The function will change the global sum variable but the returned value of the function is undefined.

Assignment with a Returned Value

If you'll recall from our discussion of Storing Values with the Assignment Operator, everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.

          
  let ourSum;
  let newSum;

  function sum(a, b) {
    return a + b;
  }

  ourSum = sum(5, 12);
  newSum = sum(3, 20);

  console.log(ourSum);
  console.log(newSum);
          
        

This will print to the dev console respectively as;

17

23

we call the sum function, which returns a value of 17 and assigns it to the ourSum variable.

we then call the sum function again with new arguments, which returns a value of 23 and assigns it to the newSum variable.


Booleans

Understanding Boolean Values

Another data type is the Boolean. Booleans may only be one of two values: true or false. They are basically little on-off switches, where true is on and false is off. These two states are mutually exclusive.

Note:

Boolean values are never written with quotes. The strings "true" and "false" are not Boolean and have no special meaning in JavaScript.

        
  function welcomeToBooleans() {
    return true;
  }
        
      

Conditionals

Use Conditional Logic with If Statements

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.


Pseudocode:

        
  if (condition is true) {
    statement is executed
  }
        
      

Example:

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

test(true) returns the string It was true, and test(false) returns the string It was false.

When test is called with a value of true, the if statement evaluates myCondition to see if it is true or not. Since it is true, the function returns It was true. When we call test with a value of false, myCondition is not true and the statement in the curly braces is not executed and the function returns It was false.


Comparison with the Equality Operator

There are many comparison operators in JavaScript. All of these operators return a boolean true or false value.

The most basic operator is the equality operator ==. The equality operator compares two values and returns true if they're equivalent or false if they are not. Note that equality is different from assignment (=), which assigns the value on the right of the operator to a variable on the left.

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

If myVal is equal to 10, the equality operator returns true, so the code in the curly braces will execute, and the function will return Equal. Otherwise, the function will return Not Equal. In order for JavaScript to compare two different data types (for example, numbers and strings), it must convert one type to another. This is known as Type Coercion. Once it does, however, it can compare terms as follows:

        
  1   ==  1
  1   ==  2
  1   == '1'
  "3" ==  3
           
        
      

In order, these expressions would evaluate to true, false, true, and true.


Basic JavaScript Comparison with the Strict Equality Operator

Strict equality (===) is the counterpart to the equality operator (==). However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.

If the values being compared have different data types, they are considered unequal, and the strict equality operator will return false.

Example:

        
  3 === 3
  3 === "3"
        
      

These conditions would return true and false respectively.

In the second example, 3 is a Number data type and '3' is a String data type.


Comparing different values with typeof

If the values being compared are not of the same type, the equality operator will perform a type conversion, and then evaluate the values. However, the strict equality operator will compare both the data type and value as-is, without converting one type to the other.

Example:

        
  3 == "3"
  3 === "3"
        
      

3 == "3" returns true because JavaScript performs type conversion from string to number. 3 === "3" returns false because the types are different and type conversion is not performed.

Note:

In JavaScript, you can determine the type of a variable or a value with the typeof operator, as follows:

        
  typeof 3
  typeof "3"
        
      

typeof 3 returns the string number, and typeof '3' returns the string string.


Comparison with the 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. Like the equality operator, the inequality operator will convert data types of values while comparing.

Example:

        
  1 != 2
  1 != "1"
  1 != '1'
  1 != true
  1 != false
        
      

In order, these expressions would evaluate to true, false, false, false, and false.


Comparison with the Strict Inequality Operator

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. The strict inequality operator will not convert data types.

Example:

        
  3 !== 3
  3 !== '3'
  4 !== 3
        
      

In order, these expressions would evaluate to false, true, and true.


Comparison with the 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.

Like the equality operator, the greater than operator will convert data types of values while comparing.

Example:

        
  5 > 3
  7 > '3'
  2 > 3
  '1' > 9
        
      

In order, these expressions would evaluate to true, true, false, and false.


Comparison with the Greater Than Or Equal To Operator

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.

Like the equality operator, the greater than or equal to operator will convert data types while comparing.

        
  6  >=  6
  7  >= '3'
  2  >=  3
  '7' >=  9
        
      

In order, these expressions would evaluate to true, true, false, and false.


Comparison with the 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.

Example:

        
  2  < 5
  '3' < 7
  5  < 5
  3  < 2
  '8' < 4
        
      

In order, these expressions would evaluate to true, true, false, false, and false.


Comparison with the Less Than Or Equal To Operator

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.

Example:

          
  4  <= 5
  '7' <= 7
  5  <= 5
  3  <= 2
  '8' <= 4
          
        

In order, these expressions would evaluate to true, true, true, false, and false.


Comparisons with the 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.

The same effect could be achieved by nesting an if statement inside another if:

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

will only return Yes if num is greater than 5 and less than 10. The same logic can be written as:

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

Comparisons with the 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.

The pattern below should look familiar from prior waypoints:

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

will return Yes only if num is between 5 and 10 (5 and 10 included). The same logic can be written as:

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

Else and If Else Statements

When a condition for an if statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an else statement, an alternate block of code can be executed.

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

Else If Statements

If you have multiple conditions that need to be addressed, you can chain if statements together with else if statements.

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

Chaining If Else Statements

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

Pseudocode

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

Example:

        
  function testSize(num) {
    if (num < 5) {
      return "Tiny";
    } else if (num < 10) {
      return "Small";
    } else if (num < 15) {
      return "Medium";
    } else if (num < 20) {
      return "Large";
    } else if (num >= 20) {
      return "Huge";
    }
  }

  testSize(0);
  testSize(4);
  testSize(5);
  testSize(8);
  testSize(10);
  testSize(14);
  testSize(15);
  testSize(17);
  testSize(20);
  testSize(25);
        
      

This will return the strings respectively: Tiny, Tiny, Small, Small, Medium, Medium, Large, Large, Huge, Huge.


Switch Statements

Selecting from Many Options with Switch Statements

If you have many options to choose from, use a switch statement. 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.

Example:

        
  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.


Default Option in Switch Statement

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. Think of it like the final else statement in an if/else chain.

A default statement should be the last case.

Example:

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

Multiple Identical Options in Switch Statements

If the break statement is omitted from a switch statement's case, the following case statement(s) are executed until a break is encountered. If you have multiple inputs with the same output, you can represent them in a switch statement like this:

Example:

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

Cases for 1, 2, and 3 will all produce the same result.


Replacing If Else Chains with Switch

If you have many options to choose from, a switch statement can be easier to write than many chained if/else if statements. The following:

        
  if (val === 1) {
    answer = "a";
  } else if (val === 2) {
    answer = "b";
  } else {
    answer = "c";
  }   
        
      

can be replaced with:

        
  switch(val) {
    case 1:
      answer = "a";
      break;
    case 2:
      answer = "b";
      break;
    default:
      answer = "c";
  } 
        
      

javaScript Objects

Build JavaScript Objects

You may have heard the term object before.

Objects are similar to arrays, except that instead of using indexes to access and modify their data, you access the data in objects through what are called properties.

Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.

Here's a sample cat object:

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

In this example, all the properties are stored as strings, such as name, legs, and tails. However, you can also use numbers as properties. You can even omit the quotes for single-word string properties.

Here's another object:

      
  const anotherObject = {
    make: "Ford",
    5: "five",
    "model": "focus"
  };
      
    

However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.


Accessing Object Properties with Dot Notation

There are two ways to access the properties of an object: dot notation (.) and bracket notation ([]), similar to an array.

Dot notation is what you use when you know the name of the property you're trying to access ahead of time.

Here is a sample of using dot notation (.) to read an object's property:

      
  const myObj = {
    prop1: "val1",
    prop2: "val2"
  };
        
  const prop1val = myObj.prop1;
  const prop2val = myObj.prop2;
      
    

prop1val would have a value of the string val1, and prop2val would have a value of the string val2.


Accessing Object Properties with Bracket Notation

The second way to access the properties of an object is bracket notation ([]). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.

However, you can still use bracket notation on object properties without spaces.

Here is a sample of using bracket notation to read an object's property:

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

myObj["Space Name"] would be the string Kirk, myObj['More Space'] would be the string Spock, and myObj["NoSpace"] would be the string USS Enterprise.

Note:

Property names with spaces in them must be in quotes (single or double).


Accessing Object Properties with Variables

Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object's properties or when accessing a lookup table.

Here is an example of using a variable to access a property:

      
  const dogs = {
    Fido: "Mutt",
    Hunter: "Doberman",
    Snoopie: "Beagle"
  };
        
  const myDog = "Hunter";
  const myBreed = dogs[myDog];
  console.log(myBreed);
        
      
    

The string Doberman would be displayed in the console.

Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:

      
  const someObj = {
    propName: "John"
  };
        
  function propPrefix(str) {
    const s = "prop";
    return s + str;
  }
        
  const someProp = propPrefix("Name");
  console.log(someObj[someProp]);
      
    

someProp would have a value of the string propName, and the string John would be displayed in the console.

Note:

we do not use quotes around the variable name when using it to access the property because we are using the value of the variable, not the name.


Updating 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.

For example, let's look at ourDog:

Since he's a particularly happy dog, let's change his name to the string Happy Camper. Here's how we update his object's name property: ourDog.name = "Happy Camper"; or ourDog["name"] = "Happy Camper"; Now when we evaluate ourDog.name, instead of getting Camper, we'll get his new name, Happy Camper.

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

  ourDog["name"] = "Happy Camper";

  console.log(ourDog.name) // or
  console.log(ourDog['name'])
      
    

Add New Properties to a JavaScript Object

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

Here's how we would add a bark property to ourDog:

      
  ourDog.bark = "bow-wow";

  or

  ourDog["bark"] = "bow-wow";
      
    

Now when we evaluate ourDog.bark, we'll get his bark, bow-wow.

Example:

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

Delete Properties from a JavaScript Object

We can also delete properties from objects like this:

      
  delete ourDog.bark;
      
    

Example:

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

After the last line shown above, ourDog looks like:

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

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 rather than a switch statement or an if/else chain. This is most useful when you know that your input data is limited to a certain range.

Here is an example of a simple reverse alphabet lookup:

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

  const value = 2;
  alpha[value];
      
    

alpha[2] is the string Y, alpha[24] is the string C, and alpha[value] is the string Y.


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.

Example:

      
  const myObj = {
    top: "hat",
    bottom: "pants"
  };
        
  myObj.hasOwnProperty("top");
  myObj.hasOwnProperty("middle");        
      
    

The first hasOwnProperty returns true, while the second returns false.


Manipulating Complex Objects

Sometimes you may want to store data in a flexible Data Structure. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of strings, numbers, booleans, arrays, functions, and objects.

Here's an example of a complex data structure:

      
  const ourMusic = [
    {
      "artist": "Daft Punk",
      "title": "Homework",
      "release_year": 1997,
      "formats": [ 
        "CD", 
        "Cassette", 
        "LP"
      ],
      "gold": true
    }
  ];
      
    

This is an array which contains one object inside. The object has various pieces of metadata about an album. It also has a nested formats array. If you want to add more album records, you can do this by adding records to the top level array. Objects hold data in a property, which has a key-value format. In the example above, "artist": "Daft Punk" is a property that has a key of artist and a value of Daft Punk. JavaScript Object Notation or JSON is a related data interchange format used to store data.

JSON Example:

      
  {
    "artist": "Daft Punk",
    "title": "Homework",
    "release_year": 1997,
    "formats": [ 
      "CD",
      "Cassette",
      "LP"
    ],
    "gold": true
  }
      
    

Note:

You will need to place a comma after every object in the array, unless it is the last object in the array.


Accessing Nested Objects

The sub-properties of objects can be accessed by chaining together the dot or bracket notation.

Here is a nested object:

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

ourStorage.cabinet["top drawer"].folder2 would be the string secrets, and ourStorage.desk.drawer would be the string stapler.


Accessing Nested Arrays

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.

Here is an example of how to access a nested array:

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

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

ourPets[0].names[1] would be the string Fluffy, and ourPets[1].names[0] would be the string Spot.


javaScript Loops

Iterate with JavaScript While Loops

You can run the same code multiple times by using a loop.

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++;
  }
        
      

In the code example above, the while loop will execute 5 times and append the numbers 0 through 4 to ourArray.


Iterate with JavaScript 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), where a is the initialization statement, b is the condition statement, and c is the final expression.

The initialization statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.

The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true. When the condition is false at the start of the iteration, the loop will stop executing. This means if the condition starts as false, your loop will never execute.

The final expression is executed at the end of each loop iteration, prior to the next condition check and is usually used to increment or decrement your loop counter.

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);
  }
        
      

ourArray will now have the value [0, 1, 2, 3, 4].


Iterate Odd or Even Numbers With a For Loop

For loops don't have to iterate one at a time. By changing our final-expression, we can count by even numbers.

We'll start at i = 0 and loop while i < 10. We'll increment i by 2 each loop with i += 2.

        
  const ourArray = [];

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

ourArray will now contain [0, 2, 4, 6, 8].

Let's change our initialization so we can count by odd numbers.

        
  const myArray = [];

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

myArray will now contain [1, 3, 5, 7, 9].


Count Backwards with a For Loop

A for loop can also count backwards, so long as we can define the right conditions.

In order to decrement by two each iteration, we'll need to change our initialization, condition, and final expression.

We'll start at i = 10 and loop while i > 0. We'll decrement i by 2 each loop with i -= 2.

        
  const ourArray = [];

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

ourArray will now contain [10, 8, 6, 4, 2].

Let's change our initialization and final expression so we can count backwards by twos to create an array of descending odd numbers.

        
  const myArray = [];

  for (let i = 9; i > 0; i -= 2) {
    myArray.push(i);
  }
        
      

Iterate Through an Array with a For Loop

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]);
  }
        
      

Remember that arrays have zero-based indexing, which means the last index of the array is length - 1. Our condition for this loop is i < arr.length, which stops the loop when i is equal to length. In this case the last iteration is i === 4 i.e. when i becomes equal to arr.length - 1 and outputs 6 to the console. Then i increases to 5, and the loop terminates because i < arr.length is false.

Example:

This will declare and initialize a variable total to 0. It will use a for loop to add the value of each element of the myArr array to the let variable total.

        
  const myArr = [2, 3, 4, 5, 6];

  let total = 0;
  for (let i = 0; i < myArr.length; i++) {
    total += myArr[i];
  }
        
      

total should equal 20


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]);
    }
  }
        
      

This outputs each sub-element in arr one at a time. Note that for the inner loop, we are checking the .length of arr[i], since arr[i] is itself an array.


The function multiplyAll will return the product of all the numbers in the sub-arrays of arr.

        
  function multiplyAll(arr) {
    let product = 1; // if you set the multipy variable to 0 it will always equal zero.
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr[i].length; j++) {
        product = product * arr[i][j];
      }
    }
        
      

Iterate with JavaScript 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);
        
      

The example above behaves similar to other types of loops, and the resulting array will look like [0, 1, 2, 3, 4]. However, what makes the do...while different from other loops is how it behaves when the condition fails on the first check. Let's see this in action: Here is a regular while loop that will run the code in the loop as long as i < 5:

        
  const ourArray = []; 
  let i = 5;

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

In this example, we initialize the value of ourArray to an empty array and the value of i to 5. When we execute the while loop, the condition evaluates to false because i is not less than 5, so we do not execute the code inside the loop. The result is that ourArray will end up with no values added to it, and it will still look like [] when all of the code in the example above has completed running. Now, take a look at a do...while loop:

        
  const ourArray = [];
  let i = 0;

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

In this case, we initialize the value of i to 5, just like we did with the while loop. When we get to the next line, there is no condition to evaluate, so we go to the code inside the curly braces and execute it. We will add a single element to the array and then increment i before we get to the condition check. When we finally evaluate the condition i < 5 on the last line, we see that i is now 6, which fails the conditional check, so we exit the loop and are done. At the end of the above example, the value of ourArray is [5]. Essentially, a do...while loop ensures that the code inside the loop will run at least once.

Example:

        
  const myArray = [];
  let i = 10;

  do {
    myArray.push(i);
    i++;
  } while (i < 10);
        
      

Replace Loops using 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.

Note:

Recursive functions must have a base case when they return without calling the function again (in this example, when n <= 0), otherwise they can never finish executing.

Example:

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

What loop do I use for an Arrays?

Array:

The most common loop to use with an Array is a for loop

          
  var myArray = [];
            
  for(let i = 0, i < 5; i++) {
    myArray.push(i);
  }
  console.log(myArray);
          
        

What loop do I use for an Object?

Object:

The most common loop to use with an Object is a for..in loop

          
  var myObjects = {
    'Canada': 'Sasquatch',
    'Nepal': 'Yeti',
    'Scotland': 'Loch Ness Monster'
  };

  for (let property in myObjects) {
    // displays the property name
    console.log(property);

    // displays the property value
    console.log(myObjects[property]);

    // displays both key/value pair
    console.log("In", property, "we have the", myObjects[property]);
  }
          
        

javaScript Math

Generate Random Fractions with JavaScript

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.

Note

Like Storing Values with the Assignment Operator, all function calls will be resolved before the return executes, so we can return the value of the Math.random() function.

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

Generate Random Whole Numbers with JavaScript

It's great that we can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.

  1. Use Math.random() to generate a random decimal.
  2. Multiply that random decimal by 20.
  3. Use another function, Math.floor() to round the number down to its nearest whole number.

Remember that Math.random() can never quite return a 1 and, because we're rounding down, it's impossible to actually get 20. This technique will give us a whole number between 0 and 19.

Putting everything together, this is what our code looks like:

        
  Math.floor(Math.random() * 20);
        
      

In the next example we use this technique to generate and return a random whole number between 0 and 9.

        
  function randomWholeNum() {
    return Math.floor(Math.random() * 10);
  }
        
      

Generate Random Whole Numbers within a Range

Instead of generating a random whole number between zero and a given number like we did before, we can generate a random whole number that falls within a range of two specific numbers.

To do this, we'll define a minimum number min and a maximum number max.

Here's the formula we'll use. Take a moment to read it and try to understand what this code is doing:

        
  Math.floor(Math.random() * (max - min + 1)) + min
        
      

The function called randomRange takes a range myMin and myMax and returns a random whole number that's greater than or equal to myMin, and is less than or equal to myMax, inclusive.

        
  function randomRange(myMin, myMax) {
    return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin
  }
        
      

Use the parseInt Function

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

        
  const a = parseInt("007");
        
      

The above function converts the string 007 to the integer 7. If the first character in the string can't be converted into a number, then it returns NaN.

        
  function convertToInteger(str) {
    return parseInt(str)
  }
          
  convertToInteger("56");
        
      

Use the parseInt Function with a Radix

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.

The function call looks like:

        
  parseInt(string, radix);
        
      

And here's an example:

        
  const a = parseInt("11", 2);
        
      

Usin a Function to turn a binary number to an integer

        
  function convertToInteger(str) {
    return parseInt(str, 2)
  }
            
    convertToInteger("10011");
        
      

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

The syntax is a ? b : c, where a is the condition, b is the code to run when the condition returns true, and c is the code to run when the condition returns false.

The following function uses an if/else statement to check a condition:

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

This can be re-written using the conditional operator:

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

Use Multiple Conditional (Ternary) Operators

In the previous challenge, you used a single conditional operator. You can also chain them together to check for multiple conditions.

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";
    }
  }
        
      

The above function can be re-written using multiple conditional operators:

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

It is considered best practice to format multiple conditional operators such that each condition is on a separate line, as shown above. Using multiple conditional operators without proper indentation may make your code hard to read.

Example:

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

In a previous challenge, you learned how to use recursion to replace a for loop. Now, let's look at a more complex function that returns an array of consecutive integers starting with 1 through the number passed to the function.

As mentioned in the previous challenge, there will be a base case. The base case tells the recursive function when it no longer needs to call itself. It is a simple case where the return value is already known. There will also be a recursive call which executes the original function with different arguments. If the function is written correctly, eventually the base case will be reached.

For example, say you want to write a recursive function that returns an array containing the numbers 1 through n. This function will need to accept an argument, n, representing the final number. Then it will need to call itself with progressively smaller values of n until it reaches 1. You could write the function as follows:

        
  function countup(n) {
    if (n < 1) {
      return [];
    } else {
      const countArray = countup(n - 1);
      countArray.push(n);
      return countArray;
    }
  }
  console.log(countup(5));
        
      

The value [1, 2, 3, 4, 5] will be displayed in the console.

At first, this seems counterintuitive since the value of n decreases, but the values in the final array are increasing. This happens because the push happens last, after the recursive call has returned. At the point where n is pushed into the array, countup(n - 1) has already been evaluated and returned [1, 2, ..., n - 1].

We have defined a function called countdown with one parameter (n). The function will use recursion to return an array containing the integers n through 1 based on the n parameter. If the function is called with a number less than 1, the function should return an empty array. For example, calling this function with n = 5 should return the array [5, 4, 3, 2, 1]. Your function must use recursion by calling itself and must not use loops of any kind.

        
  function countdown(n){
    if(n < 1) {
      return [];
    } else {
      const countDownArray = countdown(n - 1);
      countDownArray.unshift(n)
      return countDownArray;
    }
  }
        
      

Continuing from the previous challenge, we provide you another opportunity to create a recursive function to solve a problem.

We have defined a function named rangeOfNumbers with two parameters. The function will return an array of integers which begins with a number represented by the startNum parameter and ends with a number represented by the endNum parameter. The starting number will always be less than or equal to the ending number. The function will use recursion by calling itself and not use loops of any kind. It will also work for cases where both startNum and endNum are the same.

More Function Stuff!

Returning Boolean Values from Functions

You may recall from Comparison with the Equality Operator that all comparison operators return a boolean true or false value.

Sometimes people use an if/else statement to do a comparison, like this:

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

But there's a better way to do this. Since === returns true or false, we can return the result of the comparison:

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

Return Early Pattern for Functions

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

Example:

        
  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.


FCC Basic JS Code Challenges

Word Blanks

Shopping List

Stand in Line

Golf Code

Counting Cards

Record Collection

Profile Lookup