JavaScript
Basic Topics
[Hide]node
.
var
keyword is used to declare a global variable, which you can mutate.
var myThing = "Hello World"
const
keyword is used to declare a variable that is immutable.
let
keyword is used to declare a local variable that is limited to the scope of a block statement (e.g. within functions, loop statements, etc.).
var myThing; // Variable instantiated, but not assigned to any value // ... // Lines of code // ... myThing = 4.5 // Assign valueThe equivalent of a print statement is
console.log()
.
> console.log("Hello World") Hello WorldNow we list some data types:
\
to write multiple-line strings.
> var str1 = "Hello " > var str2 = "World" > var combined = str1 + str2 // String concatenation > console.log(combined) Hello World > combined.length // String length 11 > combined.substring(3, 7) // Substring 'lo W' > combined.charAt(combined.length-1) // Character 'd' > combined.indexOf("W") // Find index of first "W" 6 > const multLineText = "Here is, \ a multiple line \ string. "
Number
type is in a 64-bit binary format and does not partition into int and float values. You can use the constants Number.MAX_VALUE
and Number.MIN_VALUE
for the largest and smallest available values. Furthermore, the number type has three symbolic values: +Infinity
, -Infinity
, and NaN
(Not-A-Number).
> num1 = 3 3 > num2 = 4.56 4.56 > num3 = 452e2 45200 > Number.MAX_VALUE 1.7976931348623157e+308 > Number.MIN_VALUE 5e-324 > num4 = Infinity Infinity > num5 = -Infinity -Infinity > 0 * num4 NaNJavaScript can store numbers with limited accuracy (16 digits?). The
BigInt
type can be used to represent integers with arbitrary precision. You can safely store and operate on large integers even beyond the safe integer limit. It is created by appending n
to the end of an integer literal.
> const myBigInt = 9769812589124905871239n; > const myBigInt2 = BigInt(9320487589023467589023);
false
when converted into a Boolean: 0
, -0
, null
, false
, NaN
, undefined
, empty string ""
.
new Array
keyword, or by initializing an empty array and assigning values.
> const cars = ["Saab", "Volvo", "BMW"]; > const Tech = new Array("AAPL", "MSFT", "META"); > const pens = []; undefined > pens[0] = "Lamy"; 'Lamy' > pens[1] = "Twisbi"; 'Twisbi' > pens[2] = "Mont Blanc"; 'Mont Blanc' > pens [ 'Lamy', 'Twisbi', 'Mont Blanc' ]However, there is no
array
type; arrays are of type object
.
> typeof(pens) 'object'
null
is not a type; it is a value that represents the intentional absense of any object value. The undefined
type is used when a variable has been called but not assigned to a value. A function returns undefined in a value was not returned. The difference between these two is that a null
variable is explicitly declared as empty but undefined
has just not been assigned a value an is implicitly empty.
> nVal = null null > typeof(nVal) 'object' > var idk undefined > typeof(idk) 'undefined' > idk = 4.5 4.5 > typeof(idk) 'number'
object
type is basically a type that can hold a lot of values (of possibly different types). We can think of it as an object in Python, with its own attributes and methods. They are declared using curly braces (conventionally with const
), which hold name-value (aka key-value) pairs that can be accessed using the dot or square bracket syntax.
> const person = {firstName: "Muchang", lastName: "Bahng", age: 20, eyeColor: "Brown"}; > person.firstName 'Muchang' > person["lastName"] 'Bahng'This is similar to a dictionary in Python. We can also store functions as the values, allowing the object to have methods. The
this
keyword refers to the object, similar to the self
keyword in Python.
> const myself = { ... fullName: "Muchang Bahng", ... age: 20, ... grow: function() { ..... this.age = this.age + 1; ..... return this.age; ..... } ... }; undefined > myself.age 20 > myself.grow() 21 > myself.age 21
if
, else if
, and else
statements are used with the curly-braces syntax.
var hour = 12; var greeting; if (hour < 10) { greeting = "Good morning"; } else if (hour < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }Ternary operators are conditionary operators that take three operands: a condition followed by a question mark
?
, then an expression to execute if the condition is truthy, followed by a colon :
, and finally the expression to execute if the condition is falsy. It is a more compact alternative to an if else statement. The syntax is:
condition ? exprIfTrue : exprIfFalseA simple example:
var age = 26; var beverage = (age >=21) ? "Beer" : "Juice"; cosole.log(beverage); // BeerJavascript has slightly different variations of loops.
for (statement 1; statement 2; statement 3) { // code block to be executed }Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed.
const pens = ["Lamy Safari", "Lamy 2000", "Platinum Century 3776"]; for (let i = 0; i < pens.length; i++) { console.log("I have a " + pens[i]); }Note that it is conventional to set the index
i
of the loop using let
since the scope of this variable is usually only relevant to the loop block. It will not affect global variables of the same name.
var i = 5; for (let i = 0; i < 10; i++) { console.log(i); } console.log(i) // 5In JS, we have the flexibility to store
i
as a global variable.
var i = 5; for (var i = 0; i < 10; i++) { console.log(i); } console.log(i) // 10
for (key in object) { // stuff }We show two examples, with an object and array.
const person = {fname: "Muchang", lname: "Bahng", age: 20}; for (let x in person) { // x represents the properties console.log(person[x]); } // Muchang // Bahng // 20 const numbers = [1, 2, 3, 4, 5]; for (let x in numbers) { // x represents indices 0~4 console.log(numbers[x]) }Do not use a for-in loop for iterating over an array if index order is important. Rather, use a for loop or a for-of loop.
for (let x of iterable) { // stuff }The
x
can also be declared with const
or var
. Here are some examples over an array and a string.
const pens = ["Lamy Safari", "Lamy 2000", "Platinum Century 3776"]; for (let x of pens) { console.log(x); } const greeting = "Hello World"; for (let char of greeting) { console.log(char); }
while (condition) { // stuff }Here is an example:
var i = 4; while (i < 10) { console.log(i) i++; }
do { // whatever } while (condition);Here is an example:
var i = 4; do { console.log(i); i++; } while (i < 10);
break
statement jumps out of a loop, and the continue
statement jumps over one iteration in the loop.
new Date()
just creates a new date object with the current date and time. Date objects are static, meaning that they are just snapshots and do not change.
> const d = new Date(); > console.log(d) 2022-06-20T03:19:07.509Z > typeof(d) 'object'We can instantiate a date object at a certain datetime with the following constructors. Note that JS counts months from 0 (January) to 11 (December).
new Date(Y, M, D, H, M, S, MS) new Date(Y, M, D, H, M, S) new Date(Y, M, D, H, M) new Date(Y, M, D, H) new Date(Y, M, D) new Date(Y, M) new Date(MS)If the parameters go beyond the max value (i.e. 42nd day), then they will overflow into the next biggest unit, e.g. the 14th month of 1992 is interpreted as the 2nd month of 1993.
function funcName() { // without arguments // Function body return value; } function funcName(param1, param2, param3 = 2) { // Function body return value; }The syntax for anonymous functions is quite similar to that of regular ones. Its syntax is
function() { // without arguments // Function body } function(args) { // Function body }As an example, we store it in a variable:
var greet = function() { console.log("Hello World"); }; greet(); // Hello WorldThis is useful when passing anonymous functions as arguments to other functions.
function Evaluate(func, param) { return func(param); }; const square = function(x) { return x * x; }; Evaluate(square, 5); // 25A shorter way of declaring anonymous functions are Arrow Functions, which has syntax:
// One-line Anonymous Function var greet_person = (name) => console.log("Hello, " + name); // Multiple-line Anonymous Function var greet = () => { console.log("Hello World"); return "Done Greeting"; }
class
keyword to create a class, with a constructor method that gets called upon object instantiation followed by any number of methods. Objects are created with the new
keyword.
class Car { constructor(name, year) { this.name = name; // attribute 1 this.year = year; // attribute 2 } age() { // Get age of car let date = new Date() // Get current datetime return date.getFullYear() - this.year; } method2() { ... } method3() { ... } } let myCar1 = new Car("Ford", 2014); let myCar2 = new Car("Audi", 2019);
Intermediate Topics
[Hide]