PH:S\Computer Science\>

JavaScript Reference

Variables

Declaring

Declare or create a variable before you use it and give a descriptive, camelCase name and appropriate intial value.

let num = 25;
const myList = [];
var userName = "";

Often, it is good to use the zero/empty value for the data type: 0 for numbers, "" for strings, [] for arrays, {} for objects.

Variables declared with let or const cannot be re-declared (which is normal in most languages). Additionally, declaring with const is technically declaring a constant and not a variable and it must be declared with an initial value. The value of a constant cannot be changed after is has been declared.

Variables declared with var can be re-declared. This is not normal in most languages and is best to be avoided as a beginner. Use let instead.

You can declare multiple variables in one statement.

let x = 0, y = 250, width = 300, height = 400;

More [+]

Assigning values

Assigning a value means to store some data into a variable or constant. Values are assigned using a single = sign and the variable being assigned to should be on the left side of the =.

Variables can be "reused" by assigning new values.

let userName = "unspecified";
userName = "Rick";
userName = "Morty";

Constants can only be assigned to once when first declared.

const pi = 3.14159;

Accessing values

To access a value means to retrieve the value stored in a variable. To access a value, just use the variable in place of a hard-coded value.

The value stored in num is accessed and stored into the variable numTwo.

let num = 25;
let numTwo = num;

Scope

The scope of a variable is where it exists.
There are three levels of scope,

  • Global - exists everywhere in the script
  • Local - exist only in the function where declared
  • Block - exist only in the block where declared. (block is current set of {})

Variables declared with var or const will have either global or local scope.
Variables declared with let have block level scope (which could be equivalent to global or local)

/* Global variables declared at root level (not inside a set of {}) */
let id = 100;
var name = "Throckmorton";
const emptyName = "Unspecified";

function myFunction() {
  /* Local variables are declared inside a function */
  let speed = 0;
  var day = "Monday";
  const monday = "Monday";

  /* Block variables exist only inside the {} where declared */
  for (let i = 0; i < 10; i++){
    // i exists in here
  }
  // i doesn't exist here
}
More [+]

Datatypes

Strings

In JavaScript, as in most languages, a string is any characters inside double or single quotes. Best practice is to use double quotes."This is a string". This can be confusing at first when a string "looks like" another datatype.

  • 0 is an integer, "0" is a string.
  • 0.0 is a float, "0.0" is a string.
  • true is a boolean, "true" is a string.
  • "Anything in quotes is a string"

Data is often stored in databases and HTML elements as strings, so JavaScript has some built-in functions to convert strings containing integers and floats to actual integer and float datatypes.

let myInt = parseInt("10");
let myFloat = parseFloat("3.14");

There is no pre-made "parseBool" function, but it's simple enough to write one.

function parseBool(value) {
  return value == "true";
}
More [+]

Numbers

The two most common datatypes for numbers are integers and floats (floating point numbers)

Integers are positive and negative whole numbers and zero. Same as in math class. Integers have no decimal point, also like math class. 10, 0, -1, 255 are all integers.

Floats are any number with a decimal point including whole numbers with a decimal point. 2.73, 0.0, 12.0 are all floats.

If your numbers are in strings you can use the functions below to convert them.

let myInt = parseInt("10");
let myFloat = parseFloat("3.14");

In JavaScript, if the division of two integers would result in a fractional part (a decimal number), it is automatically converted to a float.

let num = 2 / 3;
// num contains the float value 0.6666666666666666
More [+]

Math and Logic

Basic math operations

JavaScript follows the same order of operations as math class: PEMDAS.

  1. Parentheses ()
  2. Exponents **
  3. Multiplication * , Division / , Modulus % from left to right
  4. Addition + , Subtraction - from left to right
let ans = 100 - 5 ** 2 * (1 + 2) + 50 / 2 % 3;
/* ans = 26 */
  1. 100 - 5 ** 2 * (1 + 2) + 50 / 2 % 3
  2. 100 - 5 ** 2 * 3 + 50 / 2 % 3
  3. 100 - 25 * 3 + 50 / 2 % 3
  4. 100 - 75 + 50 / 2 % 3
  5. 100 - 75 + 25 % 3
  6. 100 - 75 + 1
  7. 25 + 1
  8. 26

Modulus calculates the remainder after division which is surprisingly useful in programming.

/* Check if a number is even (or divisible by any number) */
if (num % 2 == 0) {
 // Do something 
}

/* Have a value "loop" within a range */ 
red = (red + 1) % 256;
/* The above increments red by 1. When it goes past 255, the max value for rgb colors, it begins again at 0 */
More [+]

Comparison Operators

Comparison operators result in a boolean value which is can then be used as conditions for control structures such as if blocks, for loops, and while loops.
Make sure the values being compared are both the same datatype i.e. string with string, int with int, etc.

  • == equal to: true when the values are equal
  • != not equal to: true when the values are NOT equal
  • < less than: true when the value on the left is less than the value on the right, otherwise false
  • > greater than: true when the value on the left is greater than the value on the right, otherwise false
  • <= less than or equal to: true when the value on the left is less than or equal to the value on the right, otherwise false (when greater)
  • >= greater than or equal to: true when the value on the left is greater than or equal to the value on the right, otherwise false (when less)
let response = "";
let code = "7727";
do {
  response = prompt("Enter the 4-digit code");
} while (response != code);
  
More [+]

Logical operators

Logical operators are statements about truth (Boolean values). To start, it's best to think about them intuitively - && means and, || means or, and ! means not.

  • a && b is a true statement if both a is true and b is true. Otherwise it's false. Intuitively: I'm happy if I'm healthy and financially stable. If either one isn't true, I'm not happy.
  • a || b is a true statement if either a is true or b is true or both. It is only false if both are false. Intuitively: I'm happy if I have ice cream or I have cake for my birthday. Either way I'm happy, both is all the better. I'm only unhappy if I don't get either.
  • !a not a is a true statement if a is false. It's a false statement if a is true. Intuitively: (Not good) is bad, (not true) is false, (not false) is true
let age = prompt("Enter your age");
if (age >= 13 && age < 20) {
  alert("You are a teenager");
}           
More [+]

Control Structures

If, else if, and else blocks

if, else if, and else blocks are the basic elements of logic that decide which blocks of code run depending of whether a Boolean value is true or false.

if (condition) { 
  // Do this when true
} /* skip when false */

If the condition is true, the code in the {} will run. Otherwise, it will be skipped.

if (condition) { 
  // Do this when true
} 
else {
  // Do this when false 
}

Run one set of statements when the condition is true or another set when it is false.

if (conditionOne) { 
  // Do this when one condition is true
} 
else if (conditionTwo) {
  // Do this when another condition is true 
} 
else if (conditionThree) {
  // Do this when yet another condition is true 
}
else {
  // Do this when all other conditions are false
}

Run different sets of code based on different conditions. You can have any number of else if () sections, but must start with if (), and if there is an else , it must be last.

More [+]

While loops

Repeat a set of statements while a condition is true.

let myString = "Hello there";
let count = 1;
let index = myString.indexOf(" ");
while (index >= 0) {
  count++;
  index++;
  index = myString.indexOf(" ", index);
}

The code above counts words by searching for space " " characters. When the character isn't found, the .indexOf() function returns -1 making the condition false.

More [+]

For loops

A for loop is short-hand for declaring a counter, checking a condition, and updating the counter to use with a block of code.

let myString = "Once upon a time";
let count = 0;
for (let i = 0; i < myString.length; i++){
  if (myString.charAt(i) == "a"){
    count++;
  }
}

The code above counts the number of "a" characters in the string by accessing each char in order by index.
let i = 0 declares and initializes a new counter variable to zero which is used to increment through each index in the string in order, starting with the first character
i < myString.length continues the loop while the counter is less than the length of the string, which will end after the last index
i++ increments the counter by one each iteration

For loops are frequently used with operations on strings and arrays

More [+]

Functions

Basics

Functions are a way to break programs and algorithms into logical pieces, re-use common algorithms with out re-writing them, and make your program more understandable by grouping sets of statements together and giving them a name

/* Declare global variables first */
let secretWord = "";
let wrongGuesses = 0;

/* Initializes/resets the game */
function init() {
  secretWord = getSecretWord();
  wrongGuesses = 0;
  // TODO: clearHangMan();
}

/* Check what letter the player picks */ 
function checkGuess(event) { // Called from click event
  let char = event.target.value;
  if (secretWord.indexOf(char) >= 0){
    // TODO: revealLetters();
  }
  else {
    wrongGuesses++;
    // TODO: addNextPart();
  }
}

Using comments and pseudo-code and following the top-down design process and decomposition can help you determine what functions to create and what to name them which will greatly enhance your ability to create complex programs

More [+]

Function definitions

Before a function can be used, it must be defined somewhere. Define your own functions using the syntax below

function myFunction() {
  // Statements 
}

The function below logs that there was an error and shows a popup alert

function errorAlert() {
  console.log("Error");
  alert("Error, please refresh the page");
}
More [+]

Arrays and Collections

Array basics

An array is a datatype that represents an ordered collection of items. Each item is referred to as an element and has an ordered position or index in the array. Array indices start at zero. Array elements can be of any datatype, including arrays, and unlike many programming languages, JavaScript arrays can contain more than one datatype.

Create an array with some initial string values.

let weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];

The index of the first element, "Monday" is the integer value 0, "Tuesday" is 1 and so forth

Often it can be useful to declare an initially empty array, and then use the .push() method to add elements at another point in the script.

let arr = [];
More [+]

Accessing array values (getting and setting)

An array is a list of values stored in one variable. Each element in the array has an ordered position or index. To access individual elements in the array, use square bracket or subscript notation with the index of the element you want to access arr[index]. To access elements by index, the array must already contain elements. You cannot add more elements to array this way, only change elements at positions that already exist.

let colors = ["red", "blue", "yellow", "orange", "green"];
/* Print the first element, red, to the console */ 
console.log(colors[0]);

/* Store the 4th element in another variable */ 
let color = colors[3];

Change values in the array

/* Change the second element (index = 1) from blue to purple */ 
colors[1] = "purple";
More [+]

Adding elements to an array

Add elements to the end of an array using the arr.push(element) method.

let foods = [];
foods.push("Ice cream");
foods.push("Hamburger");
/* Now, foods = ["Ice cream", "Hamburger"] */ 

Document Object Model (DOM)

Finding elements by id

Give the element you want to find in JS an id in HTML.
<p id="my-paragraph"></p>
In JavaScript, you can use document.getElementById() to find and access the element.

let p = document.getElementById("my-paragraph");
p.innerHTML = "Hello world!";
p.style.color = "red";

Creating elements

To create a new HTML element in JS, use the document.createElement(tag) method where tag is a string containing the name of an HTML tag. Then, use element.appendChild() to add the new element as a child of another container element.

let a = document.createElement("a");
a.innerHTML = "Pueblo CS Website";
a.href = "https://www.pueblocs.org";
let body = document.getElementById("body");
body.appendChild(a);

CSS styles

CSS properties can be read and assigned to using element.style.propertyName. Where propertyName is the camelCase equivalent of a CSS property with the hypen removed. The value of the property is a string datatype.

let div = document.getElementById("my-div");
div.style.width = "200px";
div.style.color = "blue";

HTML attributes

element.attributName
All HTML attributes can be read and assigned to using the corresponding property. The value is a string data type.

let img = document.createElement("img");
img.src = "goose.png";
img.id = "goose-pic";

.innerHTML

element.innerHTML
The inner HTML is what would be between the opening and closing tags of the element. If you're new, it's probably best to only use this when the only content of the element will be plaintext.

let button = document.createElement("button");
button.innerHTML = "Cancel";

You can use this to create HTML elements by assigning a string containing HTML code too.