Week 2 - Programming basics

JavaScript

Basic Syntax

Variables

Data types

Numbers

Basic IO

Conditionals

Nested conditions

Git branches

GUI Tools for Git

Code style: Basics

Introduction to AI

Practice

Assignment

Back to core program

Input and Output (IO)

IO is how an application communicates with other applications or with the person using it. There are many ways for an application to request user input and to produce an output. Let’s cover some basics.

Output

Output is the information or result that a program produces and displays to the user or sends to another system, such as text shown on the screen, data written to a file, or sounds played through speakers. Output is important: it lets the user know whether an operation was successful or not.

Console.log

In JavaScript, we can use the popular console.log() function to print output to the console:

console.log('Hello, world!');
// -> Hello, world!

If you would like to print a newline, use the special character combination \\n

console.log('Hello \\n World!');
// --> Hello,
//      World!

You can also print multiple values with one command by separating them with commas (,):

console.log('Apple','Banana','Orange');
// -> Apple Banana Orange

Input

Asking users for input makes applications interactive and enables many different types of applications.

In JavaScript, there are many ways to ask for user input. Many of these methods are too advanced to use at this stage. We will focus on one method that uses an external package - extra code that is not included in the standard Node.js environment.

To install the external package, run the following two commands in the same folder where your JavaScript files:

npm install prompt-sync

npm pkg set type=module

The npm install command downloads the external code from the internet and places it on your computer. The second command, npm pkg set type=..., enables modern JavaScript syntax.

prompt-sync is an external npm package. After installation, we can import and use this external code in our application:

import promptSync from 'prompt-sync';
const prompt = promptSync();

const name = prompt('What is your name? ');
console.log('Hello, ', name);

Explanation:

  1. The import line tells JavaScript to add the external code to your application
  2. const prompt = promptSync(); sets up the prompt command for use
  3. prompt('...') waits for user input and saves it to the name constant

<aside> ⌨️

Hands on: Create a new folder, install prompt-sync with npm, create a new JavaScript file with the code above and run it.

</aside>

After installing the package, you will notice it also created a few extra files and folders:

image.png

Don't worry about those items for now. You can ignore them, but do not delete them.

We will learn more about npm packages in Week 4.

Extra reading


The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 **

CC BY-NC-SA 4.0 Icons

*https://hackyourfuture.net/*