Comp 110 print (vs return)

print

The print function from the introcs library lets us print things to the screen.

But before we can use it, we must import it from the library:

import { print } from "introcs";

To print something, we call the print function and provide the value or variable we want printed as an argument:

print(<valueToBePrinted>);

Examples:

print("Hello!"); // prints: Hello!
print(110); // prints: 110

When we use variables as arguments within a print statement, the value stored in the variable will be printed. When we use expressions in the print statement, we're printing whatever the expression evaluates to.

Examples:

let x: boolean = true;
print(x); // prints: true
print(2 > 1); // 2 is greater than 1, so this evaluates to true. prints: true

Print vs Return

A print statement is NOT the same as a return statement.

  • When we print, we are using the function from the introcs library to show an expression within the browser!
  • When we return, we must be inside a function
    • When a return statement executes, it means that the function call will now evaluate to be whatever is returned - returning a value does not necessarily display the value.

For example:

let sipThatTea = (isPetty: boolean): string => {
     if (isPetty){
          return "Sip that tea boo";
     } else {
          return "Sit down. We good";
     }
}

export let main = async () => {\
//1
     print("Let's see who's petty!");
//2
     let pettyString: string = sipThatTea(true);
//3
     print(pettyString);
}

main();

When main is called:

At //1, a string is printed: Let's see who's petty!

At //2)sipThatTea(true) is called, and the string that is returned is assigned to pettyString...

  • ...but this all happens behind the scenes! In the browser, we can't see any of this because nothing has been printed! Executing a return line in sipThatTea does not mean that anything is printed!

At //3, the string that we assigned in //2 is now printed! 

Printing does not change the values of any of our variables, it just makes things visible within the browser!