JavaScript Fundamentals, Template Literals, and Math Methods
Workplace Context
You have just joined a new project, and your team expects you to hit the ground running by building new features using JavaScript. However, you first need to refresh your understanding of JavaScript basics like variables, data types, and functions. This training and the associated activities will review the foundational concepts that are critical for building interactive applications.
Learning Objectives
By the end of this lesson, you will be able to:
- Declare and use variables to store data in JavaScript.
- Perform basic mathematical operations on variables.
- Create and call functions to organize and reuse code.
Variables and Data Types
What are Variables?
Variables are containers that store data values. In JavaScript, you can declare variables using let
, const
, or var
.
let username = "John";
const age = 25;
var isStudent = true;
let
allows you to declare variables that can be reassigned.const
declares variables that cannot be reassigned.var
is the older way of declaring variables but is generally avoided due to scope issues.
Data Types
In JavaScript, common data types include:
- Strings: Used to represent text (
"Hello, World!"
). - Numbers: Used for integers and decimals (
42
,3.14
). - Booleans: Represent true or false values (
true
,false
).
Template Literals
Template literals are a way to embed expressions into strings, making it easier to create dynamic text without complex concatenation. Template literals are enclosed in backticks (` `), and variables or expressions are embedded using ${ }
.
Example: Constructing a Dynamic String
Using the live editor below, edit the values of name
and age
and observe the output below.
This method is more readable and concise compared to traditional string concatenation using the +
operator:
let greeting = "Hello, my name is " + name + " and I am " + age + " years old.";
Basic Mathematical Operations
JavaScript supports standard mathematical operations like addition, subtraction, multiplication, and division.
let a = 10;
let b = 20;
console.log(a + b); // 30
console.log(a * b); // 200
You can also increment and decrement variables using ++
and --
.
let count = 0;
count++;
console.log(count); // 1
count--;
console.log(count); // 0
Functions and Parameters
What is a Function?
A function is a block of code designed to perform a specific task. You define a function using the function
keyword.
function greet() {
console.log("Hello, World!");
}
greet(); // Output: Hello, World!
Parameters and Arguments
Functions can take parameters, which are inputs used inside the function.
function greetUser(username) {
console.log("Hello, " + username);
}
greetUser("John"); // Output: Hello, John
Returning Values from Functions
Functions can also return values using the return
statement.
function add(a, b) {
return a + b;
}
let sum = add(5, 10);
console.log(sum); // Output: 15
Functions with Multiple Parameters
Functions can accept multiple parameters, making them more flexible and reusable. Let us look at an example where we create a function to calculate the total cost of an item, including tax and discount.
Example: Function with Multiple Parameters
In this example:
price
,taxRate
, anddiscount
are parameters passed to the function.- The function calculates the total cost by subtracting the discount, adding the tax, and returning the final amount.
The initial example uses a price
of 100, taxRate
of 0.07, and discount
of 10. Using the provided formula, this should output 96.3, but instead the console shows 96.30000000000001. Why is this?
JavaScript, like some other programming languages, is actually bad at math due to limitations on how computers handle storing numbers. If you’re interested in reading more about this peculiarity, read through this article on Why JavaScript is Bad at Math (and how to work with its limitations) .
JavaScript Math Methods
JavaScript provides several useful methods within the built-in Math
object. These methods are essential for handling mathematical operations in your applications.
Generating a Random Number
The Math.random()
method generates a random floating-point number between 0 (inclusive) and 1 (exclusive).
To generate a random integer within a specific range, you can combine Math.random()
with Math.floor()
.
Critical Thinking: Why must we add 1 to the randomInteger
calculation? What would happen if we did not?
Rounding Numbers
JavaScript provides different methods for rounding numbers, including:
Math.floor()
: Rounds down to the nearest integer.Math.ceil()
: Rounds up to the nearest integer.Math.round()
: Rounds to the nearest integer (up or down, depending on the decimal).
console.log(Math.floor(4.9)); // Output: 4
console.log(Math.ceil(4.1)); // Output: 5
console.log(Math.round(4.5)); // Output: 5
Activities
Activity 1: Practice with Variables and Functions
Time: 30 minutes
Instructions:
Write a simple program that:
- Declares two variables (e.g.,
x
andy
) and assigns them values. - Creates a function that adds those two variables and returns the result.
- Prints the result to the console.
Hint: Use the function
keyword to define your function, and remember to return the sum.
Activity 2: Group Discussion on Common Challenges
Time: 20 minutes
Instructions:
In small groups, discuss any challenges or misunderstandings you encountered during your prior experience related to variables or functions. Share solutions and best practices with your group.
Activity 3: Interactive Coding Challenge: Create a Simple Calculator
Time: 40 minutes
Instructions:
Build a basic calculator that takes two inputs from the user and performs addition, subtraction, multiplication, or division based on user input.
- Use
prompt()
to get input from the user. - Create a function for each mathematical operation.
- Return and display the result using
console.log()
or in the browser usingalert()
.
Knowledge Check
Which of the following is the correct way to declare a constant variable in JavaScript?
- Select an answer to view feedback.
let a = 10;
let b = 5;
console.log(a + b);
What will the code above output?
- Select an answer to view feedback.
Which of the following correctly calls a function with one argument?
- Select an answer to view feedback.
Summary
In this lesson, we reviewed the basics of JavaScript, focusing on variables, data types, mathematical operations, and functions. You practiced declaring variables, writing functions, and working with basic math operations in JavaScript. These concepts are foundational and will be used in every JavaScript program you write.
References
- JavaScript Variables on MDN
- JavaScript Functions on MDN
- Why JavaScript is Bad at Math (and how to work with its limitations)