Javascript Intro and Variables

HTML and CSS are useful for creating the structure of webpages and making them look beautiful. If we were putting together a car, HTML would be the frame, and CSS would be the paint and detailing. But a car without an engine isn't much of a car. Javascript gives us that engine.

With Javascript we can add animations, update our web pages, let users interact with our page, and send and receive data from web servers. Not only that, but we can actually write code that runs servers by using Node.js. It's therefore possible to write an entire web app without using any other language.

Before You Start, Install Node

To follow along with this class you'll need to download and install Node.js. Node.js is a runtime for Javascript. It uses the same core as Google Chrome (the V8 interpreter) to let you run Javascript without a web browser. This will be helpful for us in learning to write Javascript without worrying about the specifics of how Javascript interacts with a webpage.

You can run Node in interactive mode to follow along with most of the examples in this course. To do so, just type node into your console after installing it and enter the code you see.

Once Node's set up we can write our first program.

Hello, World

Hello World is the first program we write in most languages. It lets us check our computer can run the code we've written and is a classic example for that reason.

Create a new script file called script.js. Inside it, write the following:

console.log("Hello, world!")

Now, open up your console (if you're using VSCode, you can use the built-in one) and run it:

node script.js
# Hello, world!

Getting Input

Normally in Javascript we take actions using elements on a webpage. But this adds a bit of complexity, so we'll avoid that for now. Instead, we'll read input directly from the console.

First, use this command in your console to install prompt-sync. This is an npm package which gives us a simple way to take user input.

npm install prompt-sync

Now add the following lines to your script.js file.

const prompt = require('prompt-sync')();

const name = prompt("What's your name?");
console.log(`Hello ${name}!`);

Try running this script again:

node script.js

Now we can get user input! We'll use this in our first few programs to make some interactive examples.

Variables

A variable is a piece of data which we give a name. It can be a number, a name, or a list of things. There are three ways of making a variable in Javascript: the let, const, and var statements. We can make variables like this:

let local = "a local variable";
var complex = "a not-so-local variable";
const constant = "an unchangeable variable";

The most common ones you'll see in modern Javascript are let and const. Variables created with let can be changed, but ones created with const can;'t. We'll go into this in more depth later.

Now, obviously a name and a number aren't the same type of thing.

let aName = "Tim Curry"; // a string
let aNumber = 3.141; // a number

There are several types of variable in Javascript. However, Javascript is a loosely-typed language. This means that it will change the type of variables based on what it thinks makes sense in a given context. In some situations this is convenient, but in others it can lead to challenges.

Here are some common types of variable. You can also find a complete list of JS types here.

Strings. These are used to store text information. They're always given quote marks when we declare them, either single or double quotes.

// these are the same
let name = "John Doe"
let name2 = 'Jane Doe'

Numbers. These are used to store numbers. In Javascript, unlike many other languages, whole numbers (integers) like 130 and decimals like 1.34 are both the same type.

let age = 24
let temperature = 30.7

Booleans. These are used to store true or false (boolean) values.

let isTrue = true
let isFalse = false

undefined. This usually happens when you forget to create a variable.

console.log(theVoid)
// prints undefined

null. This is used to indicate that something is deliberately empty or hasn't yet been created.

let theThing = null
// some time passes
// no-one else was in the room where it happened
theThing = "US FEDERAL RESERVE"

Object, used to store more complex data structures.

let myObject = new Dog("Fluffy")
let myDate = new Date("2024-02-26") // date in ISO notation

Converting Data

Javascript might not mind too much what data type a given variable is, but as developers we normally do. This is because it can cause hard-to-fix bugs when we think a variable is one type but it's actually another. Therefore we need to convert between variables pretty often.

Number("101") // outputs 101, a number
101.toString() // outputs "101", a string
Boolean(0) // outputs false

One of the most common reasons to do this is to embed other types of data in strings for output. For this you can use a template string. Template strings are indicated by backticks.

let age = 21
console.log(`I'm ${age} years old!`)

You can also get the types of variables using the typeof keyword:

let age = 21
console.log(typeof age)
// number

Questions

What do each of the following typeof statements output?

let a = "hello!"
let b
let c = null
let d = "12"

typeof "hello!"
typeof 10
typeof false
typeof 13.65
typeof b
typeof c
typeof d

b = Number(d)
typeof(b)

Exercise

Write a program which prompts a user to enter their name, age, and hometown, then sends a message repeating those details back to them:

Name: Frank
Age: 30
Hometown: Dorking, Surrey, UK

Extension 1: Convert the user's age to a number.

Extension 2: Log the types of different outputs.