Comp 110 Expressions, Operators, and Calling Functions

Expressions

Functions with non-void return types allow us to create more complex expressions.

  • can be simplified to a single value
  • can contain any functions/objects as long as the types match

Expressions are commonly used in the assignment of values to variables:

let <name>: <type> = <expression of same type>;

Singular vs Compound Expressions

Singular expressions include literal values (1, 3.14, true, "hi"), variables, (x, courseNumber, myName), and unary operators (-x)

Compound Expressions use operators and function calls to combine singular expressions of the same type together


Operators

Arithmetic

  • includes +, -, /, *, %, etc.
  • used to evaluate mathematical expressions 

Concatenation

  • the action of linking expressions together into a series

Equality

  • includes ===, !==
  • used to test whether two expressions have the same value
  • simplifies to a boolean

Relational

  • includes >, <, <=, >=
  • used to test whether a designated relationship between two expressions exists
  • simplifies to a boolean

Examples of each:

//ARITHMETIC
function findProduct(x: number, y: number): number {
     let answer: number;
     answer = x * y;
     return answer;
}
//findProduct(3, 10) declares the variable 'answer' which is declared and initialized to 3 * 10
//the expression 3 * 10 simplifies to 30

//CONCATENATION
function printBio(name: string, age: number): void {
     let greeting: string = "hello! my name is " + name + ", and I am " + age + " years old!";
     print(greeting);
}
//concatenation allows objects to be linked into a single expression
//printBio("Bob", 20) creates the variable 'greeting' which refers to the expression "hello! my name is Bob, and I am 20 years old!"

//EQUALITY AND RELATIONAL
function isLegal(age: number): void {
     if (age < 21) {
           print("too young");
     } else if (age === 21) {
           print("just made it!");
     } else {
           print("been there, done that");
}
// age < 21 is a boolean expression and tests whether the number 'age' is less than 21
// age === 21 tests whether 'age' is the same value as 21 and simplifies to a boolean expression

Calling Functions

A function call is an expression in itself!

function findSum(x: number, y: number): number {
     let sum: number;
     sum = x + y;
     return sum;
}

let answer: number = findSum(1, 3) + findSum(2, 4);

In the above example, the variable 'answer' is declared as a number and initialized as the value of the expression 'findSum(1, 3) + findSum(2, 4)'

The function findSum is called twice in succession. findSum(1, 3) is simplified to 4, and findSum(2, 4) is simplified to 6. 'answer' is assigned the value 10;

let answer: number =  findSum(1, 3) + findSum(2, 4);
let answer: number =  4 + 6;
let answer: number: 10;
//all of this happens invisibly!