JavaScript Fundamentals | Part 1
By Chi Kit Yeung in Notes
October 5, 2024
Values and Variables
A value is the smallest unit of information in JavaScript.
Defining a variable
let firstName = 'Kit';
Naming Conventions
-
Use camelCase naming
-
Make sure variables are descriptive Make it easy for readers to understand exactly what kind of value a variable holds by using descriptive names.
Bad
let job1 = 'Programmer'
Good
let currentJob = 'Programmer'
-
Use all CAPs for constants
-
Variables can’t begin with a number
-
Variables can’t contain special characters (except for some like ‘$’, ‘_’)
-
Variables can’t be the same as special reserved JavaScript keywords
Data Types
1. Number
JavaScript does not distinguish between a Float or Integer type like other languages.
let age = 31;
let weight = 71.4;
2. String
Used for text. A sequence of characters defined by placing them within '
or "
.
let currentMood = 'Determined';
3. Boolean
True or false
4. Undefined
A variable declared with an empty value is ‘undefined’
let herAge;
5. Null
6. Symbol (ES2015)
7. BigInt (ES2020)
JavaScript has dynamic typing: What this means is the variable itself does not have a type but the value does. Data types are determined automatically so it does not need to be declared.
The operator typeof
can be used to find the type of a given value or variable.
console.log(typeof currentMood)
// Output
// > string
Note that there is a weird behaviour with null
type variables where when we use the typeof
operator, the type is incorrectly returned as ‘object’ instead of ’null’
let nullVar = null;
console.log(typeof nullVar)
// Output
// >object
let, const, var
let
Use the let
keyword to declare variables where it’s value will get reassigned.
const
const
is used to declare a variable where it’s value is not intended to be mutated. It creates a variable where it’s value cannot be reassigned. Because of this, an initial value must be assigned when const
is used. const
should be used by default when declaring new variables unless it’s value is intended to change.
var
var
is the old way to declare variables prior to ES6. TBA
Basic Operators
Mathematical Operators
These are the usual mathematical operations (+, -, *, /).
Examples:
const age = 31;
x = age + 10;
console.log(x) // 41
Extras:
x += 10 // x = x + 10 | 51
x *= 4 // x = x * 4 | 204
2 ** 3 // 2 to the power of 3
x++ // x = x + 1
x-- // x = x - 1
Assignment Operators
These are the value assignments we’ve been using (=).
Comparison Operators
These operators (>, <, ===, !=, <=, >=) return a Boolean value type of true
or false
.
Operator Precendence (order of operations)
JavaScript has a well defined set of rules for operator precedence. Ref: link
Strings and Template Literals
A JavaScript template literal is like Python f strings.
const myName = 'Kit';
const age = 31;
const introduction = `I'm ${myName} and I'm ${age} years old!`
console.log(introduction)
// Output:
// I'm Kit and I'm 31 years old!
We can also use \n
to start a new line.
if / else Statements
if/else Control Structure:
if (condition) {
// Code to run if condition is `true`
} else {
// Code to run if condition is `false`
}
Type Conversion and Coercion
Type conversions are cases where we explicitly convert a value from one type to another. Coercion on the other hand happens whenever JavaScript automatically convert types to perform operations.
Conversion examples:
const price = '699' // A string
console.log(price + 51) // Addition involving a String would result in concatenation
console.log(Number(price) + 51) // We use the function `Number()` to convert the variable's value type from String to Number.
Coercion examples:
console.log('The Seiko costs ' + 150 + ' dollars') // Here JavaScript automatically converts the Number 150 to a String to concatenate the output as expected
'23' - '10' - 3 // 10
'10' - '4' - 3 + '5' // '35'
Plus (+) operators involving a string and number will always treat the number as a string and concatenate it. But if a number is stored as a string and used with operators that can only be evaluated with numbers (-, *, /, etc.) then JavaScript will try to evaluate those values as a number.
Truthy and Falsy Values
‘Falsy’ values are values that are not exactly false
but will be treated as false
.
There are 5 different values in JavaScript that are ‘Falsy’:
- 0
- '’
- undefined
- null
- NaN
Everything else is considered as ‘Truthy’ and will be evaluated as true
console.log(Boolean(0)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean('a random string')); // true
console.log(Boolean('')); // false
Equality Operators
In JavaScript there are two types of equality operators: strict (===
) and loose (==
). A strict equal operator will not perform type coercion while the loose one does. The following example clarifies this distinction:
> 18 === 18
> true
> 19 === 18
> false
> '18' === 18
> false
> '18' == 18
> true
As a general rule, use a strict (===
) as a default for equality comparison.
Conversely, for the not equal operator we have the strict (!==
) and loose (!=
) versions as well.
Boolean Logic
AND
AND | TRUE | FALSE |
---|---|---|
TRUE | TRUE | FALSE |
FALSE | FALSE | FALSE |
OR
OR | TRUE | FALSE |
---|---|---|
TRUE | TRUE | TRUE |
FALSE | TRUE | FALSE |
NOT
Inverts the boolean value
Logical Operators
const ageOver30 = true;
const isFemale = false;
> (ageOver30 && isFemale); // AND
> false
> (ageOver30 || isFemale); // OR
> true
> (!ageOver30); // NOT
> false
The Switch Statement
const day = 'monday';
switch(day) {
case 'monday':
console.log('Aww, it's Monday');
break;
case 'friday':
console.log('TGIF');
break;
case 'tuesday':
case 'wednesday':
console.log('Trudging along the week);
break;
default:
console.log('Not a valid day!');
}
Statements and Expressions
Expression produces a value. Some examples:
1 + 2
1989
true && false
Statements perform some actions but does not produce a value.
if () {
// do something
}
The Conditional (Ternary) Operator
In progress