Sept 13, 2022
Programs allow us to store pieces of data in memory and then retrieve them when we need them. We store these data in variables, which are identifiers for pieces of memory. We can then use the values of those variables in our programs. For instance, say we are trying to calculate the value of a paycheck. We would need to know how many hours were worked and what the hourly rate is.
const rate = 12.25;
let hours = 25;
var pay = rate * hours;
Before we can use a variable, we have to declare it.
This is done with the const
,
let
, or var
keywords.
After the keyword, we give the variable a name, also referred to as an identifer.
Rules for JavaScript identifiers:
Legal identifiers: variable, _variable, $variable, variable$2
Illegal identifiers: 5variable, var-iable, #variable
Variables are assigned values with the assignment operator =
let rate = 12.25;
There are different types of data that can be placed inside of a variable, and JavaScript distinguishes between them.
There are a few other data types that we’ll get to later.
Note that JavaScript is a dynamically-typed language, which is likely different than the static typing you learned in your pre-req course. While values have types (numeric, string, boolean, etc.), a variable does not, so you can change the data type that is stored in a variable during runtime.
let a = 52;
a = 'CSE 252';
a = true;
We’ve already seen some operators that work with our
variables like =
and *
, but
there are many more, which are classified in several
categories:
=
Assignment - assigns a value
+=
Addition assignment - takes the value
in the right side and adds it to the le side, and
assigns it to the left side
-=
Subtraction assignment - takes the
value in the right side and subtracts it from the left
side, and assigns it to the le side
// Start with 10 apples
let apples = 10;
// Add 5 apples
apples += 5;
// Subtract 5 apples
apples -= 5;
// Back to 10 apples!
+
Addition - adds one value to
another
-
Subtraction - subtracts one value from
another
*
Multiplication - multiplies two
values; note that we don’t use x to multiply
/
Division - divides two values
%
Modulus - divides two values, but
returns the remainder
const a = 3;
const b = 4;
const c = a + b; // c = 7
const d = c - 2; // d = 5
const e = d * 2; // e = 10
const f = e / 2; // f = 5
const g = f % 2; // g = 1 (the remainder of 5 / 2)
+
Concatenation - concatenates two
strings together
+=
Concatenation assignment -
concatenates the right side to the le side, assigning
the value to the left side
const greeting = 'Hello,';
const name = 'Fred';
console.log(greeting + name + "!"); //outputs "Hello, Fred!"
Template literals use the backtick character `
instead of quotes. Template literals can contain
expression placeholders ${}
, allowing for
string interpolation:
console.log(`${greeting}${name}!`);
console.log(`The answer is ${num1 + num2}`);