JavaScript Core I - 1
- Hello World
- Variables
- String concatenation
- Strings
- Numbers as integers
- Numbers as decimals
- Functions
- Calling functions inside functions
Learning Objectives
By the end of this class, you should be able to answer these questions:
- What is
console.log()
? - What are the different primitive data types in JS?
- What is
typeof
and how do you use it? - How do you assign data to variables using
let
andconst
? - How do you define, call and evaluate functions?
- How do you manipulate strings with concatenation and interpolation techniques?
- How do you manipulate numbers with mathematical operators and the
Math
library? - What is the difference between
console.log()
andreturn
? - How do you call functions from within functions?
- How do you search and read documentation if you're stuck?
- How can you debug and step through code?
Please make sure you've forked the js-exercises repo at the start of the class. This is the repo we will use during the class, and for homework.
Prerequisites
- Access to a Linux console (either on Mac, Ubuntu or by using Ubuntu WSL for Windows 10)
- VS Code running a default Linux terminal
- NodeJS must be installed
To test, you can write node -v
in your terminal and you should see something like v11.10.0
. If you don't see this please talk to a teacher!
Hello World
It is programming tradition that the first thing you do in any language is make it output 'Hello world!'.
We'll do this in JavaScript, using a command called console.log()
. The console.log()
method writes a message to the console.
The console is a tool which is mainly used to log information - it's useful for testing purposes.
Exercise (10 minutes)
(This exercise will help you understand how to run a basic JS script and explore the different ways you can run JS code)
- Create your first
js1-week1.js
script - Type
console.log("Hello World!")
- There are 2 ways you can run this script - one way is by pressing F5 in your VS Code application. Can you find out what the second way is? Pair up and use a search engine to find out! Choose your favourite method and use that from now on.
BONUS: there is a third way of running JS code (notice how I haven't said scipt) - do you know what that is?
Exercise (5 minutes)
(This exercise will help you expand your understanding of console.log)
Write 10 statements like these, but in different languages.
For example:
Halo, dunia! // Indonesian
Ciao, mondo! // Italian
Hola, mundo! // Spanish
Variables
When you write code, you'll want to create shortcuts to data values so you don't have to write out the same value every time.
We can use a variable to create a reference to a value. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with let and const keywords as follows.
let greeting = "Hello world";
console.log(greeting);
const name = "Irina";
console.log(name);
The program above will print "Hello world" to the console. Notice how it uses the value assigned to the variable greeting
.
Exercise (5 minutes)
- Add a variable
greeting
to js1-week1.js and assign a greeting of your choice to the variable - Print your
greeting
to the console 3 times. You should see your greeting 3 times on the console, one on each line.
Strings
In programming there are different types of data. You've used one data type already: string.
Computers recognise strings as a sequence of characters but to humans, strings are simply lines of text.
const message = "This is a string";
Notice that strings are always wrapped inside of quote marks. We do this so that the computer knows when the string starts and ends.
You can check that the data is a string by using the typeof
operator:
const message = "This is a string";
const messageType = typeof message;
console.log(messageType); // logs 'string'
Exercise (5 minutes)
Write a program that:
creates a variable called
colors
- assigns colors "blue" and "yellow" as a comma separate string to
colors
logs the type
colors
usingtypeof
.What is the
typeof
a number?
String concatenation
You can add two strings together using the plus operator (+
) or string interpolation.
String interpolation is a useful JavaScript feature that allows you to put variables directly into a string:
// Here is an example using the plus operator to concat strings
const greetingStart = "Hello, my name is ";
const name = "Daniel";
const greeting = greetingStart + name;
console.log(greeting); // Logs "Hello, my name is Daniel"
// Here is example using the String interpolation to concat strings
const greetingStart = "Hello";
const name = "Daniel";
const greeting = `${greetingStart}, my name is ${name}`;
console.log(greeting); // Logs "Hello, my name is Daniel"
Exercise (5 mins)
- Write a program that logs a message with a greeting and your name using the two concatenation methods we used
Numbers as integers
The next data type we will learn is number.
Unlike strings, numbers do not need to be wrapped in quotes.
const age = 30;
You can use mathematical operators to calculate numbers:
const sum = 10 + 2; // 12
const product = 10 * 2; // 20
const quotient = 10 / 2; // 5
const difference = 10 - 2; // 8
Exercise (10 mins)
- Create two variables
numberOfStudents
andnumberOfMentors
- Log a message that displays the total number of students and mentors
Expected result
Number of students: 15
Number of mentors: 8
Total number of students and mentors: 23
Numbers as decimals
Numbers can be integers (whole numbers) or floats (numbers with a decimal).
const preciseAge = 30.612437;
Numbers with decimals can be rounded to the nearest whole number using the Math.round
function:
const preciseAge = 30.612437;
const roughAge = Math.round(preciseAge); // 31
Exercise (15 mins)
- Using the variables provided in the exercise calculate the percentage of mentors and students in the group (percentages must be a rounded to the nearest integer)
- Using online documentation, what other things can you do with the
Math
library? Pick one thing on your table that you can do other thanMath.round
and prepare an explanation for the rest of the class
Expected result
Percentage students: 65%
Percentage mentors: 35%
Functions
Functions are blocks of code that can do a task as many times as you ask them to. They take an input and return an output.
Here's a function that doubles a number:
function double(number) {
return number * 2;
}
To use the function we need to: a) call it with an input and b) assign the returned value to a variable
const result = double(2);
console.log(result); // 4
The input given to a function is called a parameter.
A function can take more than one parameter:
function add(a, b) {
return a + b;
}
When you write a function (sometimes called declaring a function) you assign names to the parameters inside of the parentheses (()
). Parameters can be called anything.
This function is exactly the same as the on above:
function add(num1, num2) {
return num1 + num2;
}
Exercise (20 minutes)
In pairs, design and create a function that:
takes in more than one input
- uses string concatenation
- this means adding two strings together
- performs some form of operation on a number
uses
return
to return a stringAdd a comment above your function to explain what it does
- Call your function and run your script
- What's the difference between a
return
andconsole.log
? - When would you choose to use functions over the way we have been scripting so far?
Exercise (10 minutes)
- Swap your laptop with your neighbouring pair and review each other's code - what can be improved? Is the code readable?
Calling functions inside functions
Functions are very powerful.
- You can write more than one line of code inside of functions.
- You can use variables inside of functions.
- You can call other functions inside of functions!
function getAgeInDays(age) {
return age * 365;
}
function createGreeting(name, age) {
const ageInDays = getAgeInDays(age);
const message =
"My Name is " + name + " and I was born over " + ageInDays + " days ago!";
return message;
}
Exercise (20 mins)
- Write a function that returns the year someone is born given their age as input
- Using the answer from step 1, write a function that takes someone's name and age as input and returns a string that states the person's name and year they were born in a sentence
Glossary
- Console: a place on your computer to run scripts or commands from
- Command: something that you type on your computer which performs an operation that your computer does
- Directory: another word for "folder" on your computer
- Parameter: a placeholder for values you can pass into functions
- Primitive type: a built-in type in JavaScript (e.g. strings and numbers are primitive types in JavaScript)
- Script: a file that contains a program
- Terminal: another word for "console"
Homework
- Fork the js-exercises repo repo and solve all exercises in the
week-1/Homework/mandatory
. You can complete the optional exercises inweek-1/Homework/extra
for more of a challenge!