JavaScript (JS)

Description

JavaScript is a scripting language that creates and controls dynamic website content. It is used along side other tools used to develop websites like HTML and CSS. Currently, nearly every website uses JavaScript to allow webpage behavior.

Examples: Anything that moves, refreshes, or anything that typically is on your screen that manually happens without the need of the user to reload the web page (webpage behavior).

JavaScript is a high-level language that is compiled JIT. Java is another language that we've extensively learned. While JavaScript may sound like Java, there are many key differences that separate the two. Here's one, in JavaScript you don't need semicolons at the end of lines like in Java. They are optional.

Datatypes JS uses:

Key things to point out about JavaScript:

History

JavaScript was first invented in 1995 by Brendan Eich. At first, JavaScript was invented for Netscape 2, but later in 1997, it became the ECMA-262 standard. Once Netscape handed JavaScript over to ECMA, it continued to be developed for Firefox browsers. The most recent version of JavaScript is 1.8.

The reason behind the creation of JavaScript was the growth of the internet and webpages lack of interactivity. They didn't have the ability to have dynamic behavior. There wasn't much you could do with webpages other than look at them.

At Netscape, they gave Eich the reigns to design a new language. One that can harness the power of webpages and give them life. Eich decided to create a language that similiarly follows Java's syntax. This is partly the reason why JS is called JavaScript. Because it's a scripting language, it would be called JavaScript which has caused plenty of confusion.

Getting Started

JavaScript has plenty of documentation and resources making it an easy language to dive in and learn. Especially with BSU CS students, it will be incredibly easy to learn as its syntax carries many similarites to the languages we are familiar with. Due to it being an interpreted language, there is no need for a compiler.

Documentation for JavaScript

Mozilla JavaScript Documentation/Manual

Some guides provided to learn JS

Simple and Clean Tutorial (javascript.info)
W3 Schools Tutorial
Geeks for Geeks Guide

Interactive Online Guide for JavaScript

Codeacademy

Translator

Online development is easy to setup. There are many resources out there that can be utlized. A couple are provided for easy access.

Phrase Online Translate (requires account)
Online Interpreter (Programiz)

Installation of JavaScript

JavaScript can easily be started in your browser, there is no need to install it, but you can do local development. To use JavaScript, please choose which web browser you will be using and follow the instructions below. Then, open the brower's console to have a spot to code

For Chrome

  1. Open Chrome on your computer
  2. Click More and then Settings
  3. Click Security and Privacy
  4. Click Site settings
  5. Click JavaScript
  6. Select what sites that can use Javascript

For Firefox

  1. If you’re running Windows OS, in the Firefox window, click Tools > Options
  2. Tip: If you’re running Mac OS, click the Firefox drop-down list > Preferences
  3. On the Content tab, click the Enable JavaScript check box

For Microsoft Edge

  1. Click the "Settings and more" icon at the top right of the Edge browser window
  2. Click Settings
  3. From the Settings menu, click Cookies and site permissions
  4. Scroll down and click on JavaScript
  5. In the JavaScript window, toggle the slider to "on" or "allowed"

For Safari

  1. On the Home screen, tap Settings
  2. In Settings, scroll down and tap Safari
  3. Under Safari settings, scroll down and tap Advanced
  4. For JavaScript, tap the slider to enable JavaScript

Local Development

While it's possible to develop and test javascript applications locally. If developing for the web you'll often be utilizing external compute or storage resources. Via a service like AWS or Microsoft Azure. Node.js is a popular choice, allowing the developer to write server-side logic in the same language they wrote their client-side. Here is a link to help you setup on your respective machine.

Node.js Installation Guide (Compatible Systems)

Introductory Programs

Simple Build and Run Instructions

- Save the file with a .js extension
- Refer to the script in a basic html file like the following

  <!DOCTYPE html>
    <html>
    <head>
        <title>Simple JavaScript Program</title>
    </head>
    <body>
        <script src="HelloWorld.js"></script>
    </body>
    </html>

Hello World

// hello world program
console.log("Hello, World!") // hello world program to new alert window
alert("Hello, World!") // hello world program to html site
document.write("Hello, World!")

Is a number even or odd done 3 ways

//Input
let number = 5;

//Using Two Functions
function isEven(number) {
    return number % 2 === 0;
}

function isOdd(number) {
    return number % 2 !== 0;
}

console.log(`The number ${number} is even: ${isEven(number)}`);
console.log(`The number ${number} is odd: ${isOdd(number)}`);

/*
The number 5 is even: false
The number 5 is odd: true
*/


//Using One Function if else
function checkEvenOdd(number) {
    if (number % 2 === 0) {
        return 'even';
    } else {
        return 'odd';
    }
}

console.log(`The number ${number} is ${checkEvenOdd(number)}.`);

/* The number 5 is odd. */


//Using a Ternary Operator
function checkEvenOdd2(number) {
    return number % 2 === 0 ? 'even' : 'odd';
}

console.log(`The number ${number} is ${checkEvenOdd2(number)}.`);

/* The number 5 is odd. */

Vowel Counter with For Loop

function countVowels(str) {
  let count = 0;
  const vowels = "aeiouAEIOU";

  for (let char of str) {
      if (vowels.includes(char)) {
          count++;
      }
  }

  return count;
}

let inputString = "Hello, World!";
console.log(`Number of vowels in "${inputString}":`, countVowels(inputString));

/* Number of vowels in "Hello, World!": 3 */

Magic 8 Ball

// Magic 8 Ball
let userName = 'Brian'; // Can also be var

/* vvvv Line below is testing conditional on String? vvvv */
userName ? console.log(`Hello, ${userName}!`) : console.log('Hello!');
/* ^^^^ If string is empty, would return false ^^^^ */

let userQuestion = 'Is this school year almost done?'; 
console.log(`Question asked: ${userQuestion}`); // String interpolation
let randomNumber = Math.floor(Math.random() * 8); // Math library
let eightBall = '';

switch (randomNumber) {
  case 0:
    eightBall = 'It is certain';
    break;
  case 1:
    eightBall = 'It is decidedly so';
    break;
  case 2:
    eightBall = 'Reply hazy try again';
    break;
  case 3:
    eightBall = 'Cannot predict now';
    break;
  case 4:
    eightBall = 'Do not count on it';
    break;
  case 5:
    eightBall = 'My sources say no';
    break;
  case 6:
    eightBall = 'Outlook not so good';
    break;
  case 7:
    eightBall = 'Signs point to yes';
    break;
  default:
    eightBall = 'DEMON HOURS';
    break;
}

console.log(eightBall);

Guessing Number



//Colton Gordon 

//program where the user has to guess a number generated by a program

//function for guessing a number
function guessNumber() {

    //generating a random integer from 1 to 10
    const random = Math.floor(Math.random() * 10) + 1;

    //take input from the user
    let number = parseInt(prompt('Guess a number from 1 to 10: '));

    //take the input until the guess is correct
    while(number !== random) {
        //lets the user guess again
        number = parseInt(prompt('Guess a number from 1 to 10: '));
    }

    //check if the guess is correct
    if(number == random) {
        //prints this if guessed right
        console.log('You guessed the correct number.');
    }

  }

//call the function
guessNumber();

Complex Programs

Rock Paper Scissors


// Rock Paper Scissors
const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  switch (userInput) {
    case 'rock':
      return 'rock';
    case 'paper':
      return 'paper';
    case 'scissors':
      return 'scissors';
    case 'bomb':
      return 'bomb';
    default:
      console.log('ERROR: INVALID INPUT');
      break;
  }
}

function getComputerChoice() {
  let num = Math.floor(Math.random() * 3); //Math Library is built in
  if (num === 2) {
    return 'scissors';
  } else if (num === 1) {
    return 'paper';
  } else {
    return 'rock';
  }
}

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === 'bomb') {
    return 'win. total annihilation';
  }
  if (userChoice === computerChoice) {
    return 'tie';
  }
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'loss';
    } else {
      return 'win';
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'loss';
    } else {
      return 'win';
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'scissors') {
      return 'loss';
    } else {
      return 'win';
    }
  }
}

playGame(); // Function call is 'hoisted'

function playGame() {
  let userChoice = getUserChoice('Rock');
  let computerChoice = getComputerChoice();
  console.log(`Player Choice: ${userChoice} and Computer Choice: ${computerChoice}`);
  console.log(determineWinner(userChoice, computerChoice));
}

Prime Number Checker



//Colton Gordon

// make a program to check if a number is prime or not

// take input from the user
const number = parseInt(prompt("Enter a positive number: "));

//set isPrime to true
let isPrime = true;

// check if number is equal to 1
if (number === 1) {
    //prints to console if it is 1
    console.log("1 is neither prime nor composite number.");
}

// check if number is greater than 1
else if (number > 1) {

    // looping through 2 to number-1
    for (let i = 2; i < number; i++) {
        //checks if the number is only dividable by 0
        if (number % i == 0) {
            //makes isPrime false
            isPrime = false;
            break;
        }
    }
    //checks if it isPrime
    if (isPrime) {
        //prints to console that the number is a prime number
        console.log(`${number} is a prime number`);
        //else tells us its not
    } else {
        //prints not a prime number with the number
        console.log(`${number} is a not prime number`);
    }
}

// check if number is less than 1
else {
    //prints to the console that it is not a prime number if anything else is printed
    console.log("The number is not a prime number.");
}

The Big One

Banking Application


******* Main.js: *******

// imports Bank.js
const Bank = require('./Bank.js');

// calls Bank.js main method
Bank.main();


******* Bank.js: *******

// Import required classes
const Customer = require('./Customer.js');
const CheckingAccount = require('./CheckingAccount.js');

const SavingAccount = require('./SavingAccount.js');

// Bank manages a collection of accounts
class Bank { 
    constructor() {
        this.accounts = new Set();
    }

    // includes an account to the bank's account list.
    add(account) {
        this.accounts.add(account);
    }

    // calculates changes in all accounts using goroutines (implementation required).
    accrue(rate) {
        for (let account of this.accounts) {
            account.accrue(rate);
        }
    }

    // returns a string representation of all accounts in the bank.
    toString() {
        let result = "";
        for (let account of this.accounts) {
            result += account.toString() + "\n";
        }
        return result;
    }

    static main() {
        let bank = new Bank();
        let c = new Customer("Ann");
        bank.add(new CheckingAccount("01001", c, 100.00));
        bank.add(new SavingAccount("01002", c, 200.00));
        bank.accrue(0.02);
        console.log(bank.toString());
	bank.accrue(0.02);
        console.log(bank.toString());
    }
}

module.exports = Bank;


******* Account.js: ******* 

// represents an interface for various types of accounts
class Account {
    constructor(number, customer, balance) {
        this.number = number;
        this.customer = customer;
        this.balance = balance;
    }

    accrue(rate) {
        // To be implemented in child classes
    }

    // returns the current balance of the account
    getBalance() {
        return this.balance;
    }

    // adds the given amount to the account balance
    deposit(amount) {
        this.balance += amount;
    }

    // deducts the given amount from the account balance
    withdraw(amount) {
        this.balance -= amount;
    }

    // returns a string representation of the account details
    toString() {
        return `${this.number}:${this.customer}:${this.balance}`;
    }
}

module.exports = Account;


******* CheckingAccount.js: *******

// imports Account.js
const Account = require('./Account.js');

class CheckingAccount extends Account {
    constructor(number, customer, balance) {
        // super is used to access properties from super class (Account)
        super(number, customer, balance);  
    }

    accrue(rate) {
        // No accrual for Checking Account
    }
}

module.exports = CheckingAccount;


******* SavingAccount.js: *******

const Account = require('./Account.js');

// represents a savings account as an account
class SavingAccount extends Account {
    constructor(number, customer, balance) {
        super(number, customer, balance);
        this.interest = 0;
    }

    // calculates interest and updates the balance for a SavingAccount
    accrue(rate) {
        this.interest += this.balance * rate;
        this.balance += this.balance * rate;
    }
}

module.exports = SavingAccount;


******* Customer.js: *******

// represents person who is a customer of the bank
class Customer {
    constructor(name) {
        this.name = name;
    }

    // returns the string representation of the customer's name
    toString() {
        return this.name;
    }
}

module.exports = Customer;




Output:
--> node Main.js
01001:Ann:100
01002:Ann:204

01001:Ann:100
01002:Ann:208.08

Comparison to Other "Competitive" Languages

Familiar Languages

Compared to C

Compared to Java

Competitor Languages

Compared to Ruby

Compared to Python

Code Examples JavaScript Python Ruby Java C                                       
Single-line Comment // comment # comment # comment // comment // comment
Multi-line comment /* comment */ ''' comment ''' =begin comment =end /* comment */ /* comment */
Variable Declaration var variable = "hi" variable = "hi" variable = "hi" String variable = "hi"; char variable[] = "hi";
Hello World Example console.log("Hello, World!") print("Hello, World!") puts "Hello, World!" public static void main(String[] args) { System.out.println("Hello, World!"); } #include stdio.h
int main() { printf("Hello world");
return 0; }
Function Declaration function foo(){} def foo(): def foo static void foo(){} void foo(){}
Logic/Relational Operators <, >, <=, >=, ==, !=, ==, ===, !== (The extra ones check type aswell)

&&, ||, !
<, >, <=, >=, ==, !=


not , and, or
<, >, <=, >=, ==, !=, <=>, ===


&&, ||, !
<, >, <=, >=, ==, !=


&& || !
<, >, <=, >=, ==, !=


&& || !