Intro to JavaScript#
To download the demo code for this lecture:
$ dmget wb-js-1 --demo
What is JavaScript?#
JavaScript was originally created to make things happen on websites.
Any interactivity or dynamic functionality of a website is usually done using JavaScript.

Making websites interactive is still one of the main purposes of JavaScript today.
But it’s also used for several other things, such as handling back-end logic on servers.
Variables#
Variables with let#
Variables are the primary mechanism for storing data in JavaScript.
Variables can be declared using the
letkeyword:let num = 10;
Once a variable has been declared, it can be referenced later in the file.
In this example, if we reference
numlater in our file, we will actually be referencing the value, which is 10.The value of a variable can be any data type.
Once a variable is declared, it can be reassigned later, using the assignment operator =.
let num = 10;
// other code ...
num = 15;
From here on, the value of num is 15.
console.log(num + 1); // 16
While it’s possible to reassign a variable to a value of a different data type, it’s not a good practice to do so.
It’s also possible to declare a variable without giving it a value:
let name;
This will initialize a variable for us but not provide it a value. If we attempt to reference it before providing a value, we will receive
undefined.Variable names in JavaScript should be camel case. This means that the first word is entirely lowercase, but the first letter of each subsequent word is capitalized:
let numToKeepTrackOf = 20;
Variables with const#
There is another type of variable, which is declared using the
constkeyword.constvariables cannot be reassigned.const numStates = 50;
It’s generally good practice to use
constinstead oflet, unless you know the variable will need to be reassigned.
var
Earlier versions of JavaScript did not have let and const. Instead, variables were declared with the var keyword.
var myScore = 10;
var is currently outdated syntax (although it still works for backwards compatibility reasons). The way var works leads to unexpected behavior, which can cause bugs that are difficult to fix.
All modern browsers now support let and const so you should never use var.
Data Types#
In JavaScript, data is represented using the following data types:
Number#
Positive and negative integers and decimals.
const radius = 10;
const pi = 3.14159;
You can do math with numbers:
const areaOfCircle = pi * radius * radius;
Variables which are numbers can be incremented:
let num = 10;
num += 5; // num is now 15
console.log(num); // 15
num -= 2; // shorthand for num = num - 2
console.log(num); // 13
num += 1; // shorthand for num = num + 1
console.log(num); // 14
Boolean#
The values true or false.
undefined and null#
When you declare a variable but don’t give it an initial value, its value will be set to
undefined.Another value used to represent nothingness is
null.nullis the intentional absence of value, whereasundefinedmeans no value has been assigned yet.
Array#
Can be thought of as a list. An array can contain any data type or even a mix of data types.
Arrays are created using square brackets (
[]), with each item separated by a comma.Items are organized by indexes, which start at 0:

To access the value at a certain index of an array, use square brackets:
const arrayOfColors = ['brown', 'purple', 'green', 'yellow'];
console.log(arrayOfColors[0]); // 'brown'
const index = 2;
console.log(arrayOfColors[index]); // 'green'
String#
The data type for text. Strings can be enclosed in single or double quotes (doesn’t matter).
const hello = "Hello, world!";
const stringWithSingleQuotes = 'Single quotes work too';
Individual characters in a string can be accessed using an index, just like arrays:
console.log(hello[1]); // 'e'
You can combine strings (this is called concatenation):
const ball = 'ball';
const concatenatedString = 'foot' + ball;
console.log(concatenatedString); // 'football';
Using back-ticks, variables can also be placed directly into a string. This is known as a template string.
const name = 'Steve';
console.log(`Hello, ${name}!`); // Hello, Steve!
Object#
A collection of key value pairs, with each key representing the name of a piece of data and the value being the value of that data.
const person = {
name: 'Andrew',
age: 27,
married: true,
friends: ['Jonathan', 'Josh', 'Spencer'],
};
Objects are declared using curly brackets
{}.Keys are also referred to as properties.
Values can be any data type. Keys must be strings, although they don’t need quotes around them.
Values in objects are usually referenced using dot notation, for example:
const person = {
name: 'Andrew',
age: 27,
married: true,
friends: ['Jonathan', 'Josh', 'Spencer'],
};
console.log(person.name); // 'Andrew'
New key-value pairs can also be added to an existing object using dot notation:
person.hasPets = false;
// adds new key-value pair with key='hasPets' and value=false
Primitive and complex data types
Numbers, strings, Boolean values, undefined, and null are referred to as primitive data types because they refer to a single value, and are immutable (cannot be modified, only reassigned). Objects and arrays are referred to as complex data types because they can
contain many values, and are mutable (can be modified).
If statements#
If statements#
If statements execute code based on whether a certain condition is true or false.
The condition for an if statement is contained within parentheses, while the code to be executed is contained in curly brackets.
if (2 === 2) {
console.log('Math still works');
}
Comparison operators#
If statements often use comparison operators and/or logical operators. The most common comparison operators are:
>and>=(greater than, greater than or equal to).<and<=(less than, less than or equal to).===(the equality operator). Used to check exact equality of two values. Should only be used on primitive data types.!==(the inequality operator). Used to check for inequality of two values. Should only be used on primitive data types.
Logical operators#
The most common logical operators are:
&&(theandoperator). Used to check if two separate conditions are both true.||(theoroperator). Used to check if either of two separate conditions are true.!(thenotoperator). Used to check if a condition evaluates to false.
else statements#
You can put code inside an else statement, which will run if the previous if statement fails:
if (2 === 2 && 2 === 4) {
console.log('Math is broken');
} else {
console.log('Math still works');
}
else if statements#
else if statements are useful for handling many conditions:
const num = 50;
if (num >= 0 && num < 25) {
console.log('Greater than zero, less than 25');
} else if (num >= 25 && num < 100) {
console.log('Greater than 25, less than 100');
} else {
console.log('Greater than 100');
}
Truthy and falsy values#
Sometimes you may see values inside an if statement that seem to be neither true or false:
const str = '';
if (str) {
console.log('String is not empty');
}
When a non-boolean value is placed inside an
ifstatement, it is automatically converted to a boolean.Some values are always converted to
false— these are called “falsy” values.Everything else is always converted to
true— these are called “truthy” values.
In JavaScript, there are six falsy values:
falsenullundefinedempty string0
NaN(not a number)
Everything else is truthy.
Functions#
Why Functions?#
What are some problems with this code?
const height1 = 4.5;
if (height1 < 4) {
console.log('Too short to ride the roller coaster');
} else if (height1 > 6.5) {
console.log('Too tall to ride the roller coaster');
} else {
console.log('You can ride the roller coaster!');
}
const height2 = 3.75;
if (height2 < 4) {
console.log('Too short to ride the roller coaster');
} else if (height2 > 6.5) {
console.log('Too tall to ride the roller coaster');
} else {
console.log('You can ride the roller coaster!');
}
This is less repetitive (and shorter, and more maintainable)!
function canRide(height) {
if (height < 4) {
console.log('Too short to ride the roller coaster');
} else if (height > 6.5) {
console.log('Too tall to ride the roller coaster');
} else {
console.log('You can ride the roller coaster!');
}
}
const height1 = 4.5;
canRide(height1);
const height2 = 3.75;
canRide(height2);
Functions#
Functions are:
A way to label and organize reusable blocks of code
“Boxes” that take inputs and perform computations using those inputs before outputting something
Function Syntax#
A function declaration uses the following format:
function nameOfFunction() { //Code to execute }
Functions are invoked (or called) by referencing the function name and pairing it with a pair of parentheses. Think of these parentheses as the button you are pushing to invoke the function.
nameOfFunction();
Calling the function executes any code written inside of it.
Function Inputs and Outputs#
Functions can take in one or more inputs, and they can also output a value. For example:
function addTwo(num1, num2) { return num1 + num2; }
Here, the inputs (known as parameters) are the two numbers
num1andnum2.The output (the return value) is the sum of the two numbers.
Calling Functions#
When calling a function that has parameters, you should provide values for those parameters. The values are called arguments.
In this example, 2 and 3 are the arguments. When the function is called,
num1becomes 2 andnum2becomes 3.function addTwo(num1, num2) { return num1 + num2; } const result = addTwo(2, 3);
When a function is called, the return value (the output) can be stored in a variable:
const result = addTwo(2, 3); console.log(result); // 5
You Can Only Return One Thing#
Besides returning a value, the return statement also exits the function.
So you can only return one thing — but it can be an array or an object.
function officialLanguageBroken(country) {
if (country === 'Mexico') {
return 'Spanish';
} else if (country === 'Canada') {
return 'English';
return 'French'; // Never runs!
}
}
function officialLanguageBroken(country) {
if (country === 'Mexico') {
return 'Spanish';
} else if (country === 'Canada') {
return 'English';
return 'French'; // Never runs!
}
}
Scope#
“Where is a variable name meaningful?” “Where can you use a variable?”
Functions can use variables declared outside the function (the global scope):
function calculateTotalWithTax(price) { return price + price * tax; }
But variables declared inside a function (including parameters) are not usable outside:
const total = calculateTotalWithTax(4); console.log(price); // error!
Quiz!#
What will be the values returned from the following function calls?
function greet(person, beforeNoon) {
if (beforeNoon) {
return `Good morning, ${person}!`
} else {
return `Hello, ${person}!`;
}
}
const name = 'Andrew';
const greeting1 = greet(name, false);
const greeting2 = greet('Bob', true);
Comments and Semicolons#
//makes the rest of the line a comment.// This is a commentComments will be ignored when the code runs, but they help make your code readable.
Every expression should end with a semicolon.
JavaScript doesn’t care about whitespace and newline characters. It figures out the end of each line by looking for a semicolon.
Semicolons
In modern JavaScript, semicolons aren’t strictly necessary. You won’t break your code by forgetting a semicolon. But it’s good practice to put a semicolon at the end of each line.