Web Programming Studio Notes

Week 4 - Day 1 - Class Day 9

9.1: Syntax and Variables

This section onwards is for making your website more interactive and dynamic using JavaScript, if you are just looking to make a basic website, try searching W3Schools or MDN if there is a simpler solution to your problem. If you are here to learn JavaScript keep reading.

Background

In 1995, Brendan Eich created JavaScript so the Netscape Navigator browser could dynamically respond to user events. Ex: The web page's content could change when the user clicked a button or hovered over an image.

JavaScript was standardized by Ecma International in 1997 and called ECMAScript. Ecma International continues to improve ECMAScript, releasing a new version each year. JavaScript is an implementation of the ECMAScript specification.

Today, JavaScript is one of the most popular programming languages. JavaScript is supported by every major web browser and makes web applications like Gmail and Google Maps possible. JavaScript is also popular outside the web browser. Ex: Node.js, which runs JavaScript, is a popular technology for creating server-side web applications.

JavaScript is executed by an interpreter. An interpreter executes programming statements without first compiling the statements into machine language. Modern JavaScript interpreters (also called JavaScript engines) use just-in-time (JIT) compilation to compile the JavaScript code at execution time into another format that can be executed quickly.

ECMAScript Name

The name "ECMAScript" was a compromise between Netscape, Microsoft, and other organizations involved in the standardization of JavaScript. Brendan Eich once commented that "ECMAScript was always an unwanted trade name that sounds like a skin disease." Despite ECMAScript's similarity to eczema (a group of related skin diseases), the name has stuck.

Variables

A variable is a named container that stores a value in memory. A variable declaration is a statement that declares a new variable with the keyword let followed by the variable name. Ex: let score declares a variable named score.

A variable may be assigned a value after being declared. An assignment assigns a variable with a value, like score = 2. A variable may also be assigned a value on the same line when the variable is declared, which is called initializing the variable. Ex: let maxValue = 5; initializes maxValue to 5.

A variable may be assigned a value without first declaring the variable, but good practice is to always declare a variable before assigning a value to the variable.

var can also be used but it has some differences when compared to using 'let'

A name created for an item like a variable is called an identifier. JavaScript imposes the following rules for identifiers:

  • An identifier can be any combination of letters, digits, underscores, or $.

  • An identifier may not start with a digit.

  • An identifier may not be a reserved word like let, function, or while.

A JavaScript coding convention is to name JavaScript variables with camel casing, where the identifier starts with a lowercase letter, and subsequent words begin with a capital letter. Ex: lastPrice is preferred over LastPrice or last_price.

A constant is an initialized variable whose value cannot change. A JavaScript constant is declared with the const keyword. Ex: const slicesPerPizza = 8; creates a constant slicesPerPizza that is always 8.

Data Types

Variables are not explicitly assigned a data type. JavaScript uses dynamic typing, which determines a variable's type at run-time. A variable can be assigned a value of one type and re-assigned a value of another type. Ex: x = 5; x = "test"; assigns x with a number type, then a string type.

Comments and Semicolons

A comment is any text intended for humans that is ignored by the JavaScript interpreter. JavaScript uses the // and /* */ operators to produce comments in code.

JavaScript does not require that statements be terminated with a semicolon. Only when two statements reside on the same line must a semicolon separate the two statements. Good practice is to avoid placing two statements on the same line. Some developers prefer to use semicolons at the end of statements, and others do not. Good practice is to consistently use semicolons or not throughout the code.

Input and Output

In a web browser, a JavaScript program may obtain text input from the user with the prompt() function. The prompt() function prompts the user with a dialog box that allows the user to type a single line of text and press OK or Cancel. The prompt() function returns the string the user typed or null if the user pressed Cancel.

Output may be produced using the function console.log(), which displays text or numbers in the console. The console is a location where text output is displayed. Web browsers have a console (accessible from the browser's development tools) that displays output from code the browser executes. This chapter's activities display the console output in the web page.

Exploring further:

9.2: Arithmetic

Arithmetic operation

An expression is a combination of items like variables, numbers, operators, and parentheses, that evaluates to a value like 2 * (x + 1). Expressions are commonly used on the right side of an assignment statement, as in y = 2 * (x + 1).

An arithmetic operator is used in an expression to perform an arithmetic computation. Ex: The arithmetic operator for addition is +. JavaScript arithmetic operators are summarized in the table below.

Expressions are computed using the same rules as basic arithmetic. Expressions in parentheses () have highest precedence, followed by exponentiation (**). Multiplication (*), division (/), and modulus (%) have precedence over addition (+) and subtraction (-). Ex: The expression 7 + 3 * 2 = 7 + 6 = 13 because * has precedence over +, but (7 + 3) * 2 = 10 * 2 = 20 because () has precedence over *.

Arithmetic with numbers and strings

The + operator is also the string concatenation operator. String concatenation appends one string after the end of another string, forming a single string. Ex: "back" + "pack" is "backpack".

The JavaScript interpreter determines if + means "add" or "concatenate" based on the operands on either side of the operator. An operand is the value or values that an operator works on, like the number 2 or variable x.

  • If both operands are numbers, + performs addition. Ex: 2 + 3 = 5.

  • If both operands are strings, + performs string concatenation. Ex: "2" + "3" = "23".

  • If one operand is a number and the other a string, + performs string concatenation. The number is converted into a string, and the two strings are concatenated into a single string. Ex: "2" + 3 = "2" + "3" = "23".

For all other arithmetic operators, combining a number and a string in an arithmetic expression converts the string operand to a number and then performs the arithmetic operation. Ex: "2" * 3 = 2 * 3 = 6.

This happens because JavaScript interperates the '+' symbol as either concatenate (join strings) or plus (add numbers), this causes it to try and concatenate the string and integer when being added, but when multiplied (*) it knows to multiply and will try to convert the string number to an integer.

The JavaScript functions parseInt() and parseFloat() convert strings into numbers. Ex: parseInt("5") + 2 = 5 + 2 = 7, and parseFloat("2.4") + 6 = 2.4 + 6 = 8.4.

If parseInt() or parseFloat() are given a non-number to parse, the functions return NaN. NaN is a JavaScript value that means Not a Number. Ex: parseInt("dog") is NaN.

The JavaScript function isNaN() returns true if the argument is not a number, false otherwise. When the isNaN() argument is non-numeric, the function attempts to convert the argument into a number. Ex: isNaN("dog") is true because the non-numeric value "dog" cannot be converted into a number. But isNaN("123") is false because "123" can be converted into the number 123.

Exploring further:

9.3: Conditionals

If statement

An if statement executes a group of statements if a condition is true. Braces { } surround the group of statements. Good practice is to indent statements in braces using a consistent number of spaces. This material indents 3 spaces.

If-else statement

An if-else statement executes a block of statements if the statement's condition is true, and executes another block of statements if the condition is false.

Much like standard Java, you can technically do if else statements without braces by only having a single statement within the if statement, however this sucks, dont do it, just put the braces there and it will be so much nicer.

Comparison operators

If and if-else statements commonly use comparison operators. A comparison operator compares two operands and evaluates to a Boolean value, meaning either true or false.

The is also = as a comparitor, but that basically just represents "does this pass" if it doesn't crash then it is: true; else: false;

When the equality operator == and inequality != operator compare a number and a string, the string is first converted to a number and then compared. Ex: 3 == "3" is true because "3" is converted to 3 before the comparison, and 3 and 3 are the same.

The identity operator === performs strict equality. Two operands are strictly equal if the operands' data types and values are equal. Ex: 3 === 3 is true because both operands are numbers and the same value, but "3" === 3 is false because "3" is a string, and 3 is a number. The non-identity operator !== is the opposite of the identity operator. Ex: "3" !== "3" is false because both operands are the same type and value, but "3" !== 3 is true because "3" is a string, and 3 is a number.

Other comparison operators also convert a string to a number when comparing a string with a number. Ex: 2 < "12" is true because 2 is less than the number 12. When comparing two strings, JavaScript uses Unicode values to compare characters. Ex: "cat" <= "dog" is true because "c" has a smaller Unicode value than "d".

A common error when comparing two values for equality is to use a single = instead of == or ===. Ex: if (name = "Sue") assigns name with "Sue" instead of asking if name equals "Sue".

What is Unicode?

Unicode is a computing industry standard that assigns a unique number to characters in over one hundred different languages, including multiple symbol sets and emoji. The Unicode numbers for capital A-Z range from 65 to 90, and lowercase a-z range from 97 to 122.

Nested statements and else-if statement

If and else block statements can include any valid statements, including another if or if-else statement. An if or if-else statement that appears inside another if or if-else statement is called a nested statement.

A common situation is when several nested if-else statements are needed to execute one and only one block of statements. The else-if statement is an alternative to nested if-else statements that produces an easier-to-read list of statement blocks.

In the example below, the grade variable is assigned with A, B, C, D, or F depending on the score variable. The code segment on the left uses nested if-else statements. The code segment on the right performs the same logic with else-if statements.

Logical Operators

JavaScript logical operators perform AND, OR, and NOT logic.

Multiple && and || conditions may be combined into a single complex condition. Ex: (1 < 2 && 2 < 3 || 3 < 4). Complex conditions are evaluated from left to right, but && has higher precedence than ||, so && is evaluated before ||. Good practice is to use parentheses() around conditions that use && and || to explicitly indicate the order of evaluation. Ex: (a < 0 || a > 1 && b > 2) is better expressed as: (a < 0 || (a > 1 && b > 2)).

Logic involving "not" can be difficult for humans to correctly read or understand. Ex: "Are you not hungry?" is more difficult for a human to understand than the equivalent "Are you satisfied?" Good practice is to avoid using the not operator when possible. Ex:!(score > 10) is better expressed as: score <= 10.

9.4: More Conditionals

Btw this is going to be strange unless you already have experience with languages that also try to brute force through the code.

Truthy and falsy

A truthy value is a non-Boolean value that evaluates to true in a Boolean context. Ex: if (18) evaluates to true because non-zero numbers are truthy values. A falsy value is a non-Boolean value that evaluates to false in a Boolean context. Ex: if (null) evaluates to false because null is a falsy value.

Truthy

Falsy

Conditional (ternary) operator

The conditional operator allows developers to write concise conditional statements. The conditional operator (or ternary operator) has three operands separated by a question mark (?) and colon (:). If the condition evaluates to true, then the value of expression1 is returned, otherwise the value of expression2 is returned.

Switch statement

The switch statement is an alternative to writing multiple else-if statements. A switch statement compares an expression's value to several cases using strict equality (===) and executes the first matching case's statements. If no case matches, an optional default case's statements execute.

The break statement stops executing a case's statements and causes the statement immediately following the switch statement to execute. Omitting the break statement causes the next case's statements to execute, even though the case does not match.

9.5: Loops

While loop

Three general-purpose looping constructs exist: while, do-while, and for loops. The while loop is a looping structure that checks if the loop's condition is true before executing the loop body, repeating until the condition is false. The loop body is the set of statements that a loop repeatedly executes.

Developers must be careful to avoid writing infinite loops. An infinite loop is a loop that never stops executing. Ex: while (true); is an infinite loop because the loop's condition is never false.

Do-while loop

The do-while loop executes the loop body before checking the loop's condition to determine if the loop should execute again, repeating until the condition is false.

For loop

A for loop collects three parts — the loop variable initialization, loop condition, and loop variable update — all at the top of the loop. A for loop executes the initialization expression, evaluates the loop's condition, and executes the loop body if the condition is true. After the loop body executes, the final expression is evaluated, and the loop condition is checked to determine if the loop should execute again.

break and continue statements

Two jump statements alter the normal execution of a loop. The break statement breaks out of a loop prematurely. The continue statement causes a loop to iterate again without executing the remaining statements in the loop.

Some developers use break and continue to write short and concise code, but jump statements may introduce subtle logic errors that are difficult to find. This document does not use jump statements.

9.6: Functions

Introduction to functions

A function is a named group of statements. JavaScript functions are declared with the function keyword followed by the function name and parameter list in parentheses (). A parameter is a variable that supplies the function with input. The function's statements are enclosed in braces {}.

Invoking a function's name, known as a function call, causes the function's statements to execute. An argument is a value provided to a function's parameter during a function call.

Good practice is to use function names that contain a verb and noun. Ex: display is a vague function name, but displayAverage is better because displayAverage indicates what is being displayed.

Good practice is to use camel case for JavaScript function names, where the name starts with a lowercase letter and subsequent words begin with a capital letter.

Returning a value

A function may return a single value using a return statement. A function that is missing a return statement returns undefined.

Function expressions and anonymous functions

JavaScript functions may be assigned to a variable with a function expression. A function expression is identical to a function declaration, except the function name may be omitted. A function without a name is called an anonymous function. Anonymous functions are often used with arrays and event handlers, discussed elsewhere in this material.

Unlike functions declared with a function declaration, a variable assigned with a function expression cannot be used until after the variable is assigned. Using a variable before the variable is assigned with a function expression causes an exception.

Arrow functions

An arrow function is an anonymous function that uses an arrow => to create a compact function. An arrow function's parameters are listed to the left of the arrow. The right side of the arrow may be a single expression or multiple statements in braces.

Returns one expression

Returns multiple statements

Exploring further:

9.7: Scope and the global object

The var keyword and scope

In addition to declaring variables with let, a variable can be declared with the var keyword. Ex: var x = 6; declares the variable x with an initial value of 6. When JavaScript was first created, var was the only way to declare a variable. The let keyword was added to JavaScript in 2015.

Both let and var declare variables but with differing scope. A JavaScript variable's scope is the context in which the variable can be accessed.

A variable declared inside a function has local scope, so only the function that defines the variable has access to the local variable. A variable declared outside a function has global scope, and all functions have access to a global variable.

A variable declared inside a function with var has function scope: the variable is accessible anywhere within the function, but not outside.

A variable declared inside a function with let has block scope: the variable is accessible only within the enclosing pair of braces.

A variable declared using var or let that is not inside a function creates a global variable that is accessible from anywhere in the code.

Global variables and the global object

Before developer code is run, JavaScript implementations create the global object: an object that stores certain global variables, functions, and other properties. When running JavaScript code in a web browser, global variables are usually assigned as properties to the global window object. Therefore, a global variable called test is accessible as window.test.

Developers must be careful when assigning global variables, because a global variable could replace an existing window property. Ex: window.location contains the URL the browser is displaying. Assigning location = "Texas" causes the web browser to attempt to load a web page with the URL "Texas", which likely does not exist.

Three cases exist when assigning to a global variable X:

  • X has been declared with var, in which case a property named "X" is added to the global object.

  • X has been declared with let, in which case a property named "X" is not added to the global object, but X is still accessible from anywhere in the code.

  • X has not been declared with var or let, in which case the variable becomes a property of the global object, even if assigned to inside a function.

Good practice is to always declare variables used in functions with var or let, so the variables do not become global.

Exploring further: