# Javascript
# Beginners
- Javascript is case-sensitive and uses Unicode.
- Instructions are called statements and seperated by
;. // commentsor/* Multi-line comment */
# Data Types
- string A string of characters
"Hello World". - numbers An integer
123or floating point number3.14159. - bigint
- boolean
trueorfalse. - null A keyword denoting a
nullor unknown value. - undefined Unassigned value
- symbol
- object
# Variables
A variable stores data. There are 3 different:
varDeclares a local or global variable.letDeclares a block-scoped (scoped to the immediate enclosing block{ }), local variable.constDeclares a block-scoped, read-only named constant.
# Declaring Variables
var name = "string";
- No keywords.
- No spaces.
- Can't begin with a number.
- Case sensitive.
- Only letters, numbers
0-9,$, and_. - Optional camelCase for naming.
# Functions
- Calling Function
- Input (Parameter, Arguments)
- Output return
- Function expressions produces a value
- Function statements performs an action
# Conditionals
- Use
ifstatement to run a statement if a condition istrue.
if (variable = "value") functionA();
// or
if (*condition*) {
functionA();
}
// Example, check if there's any value
if (strValue) {
//do something
}
// Example, check for null
if (strValue === "") {
//...
}
- Optionally, add
elseclause if statement isfalse.
if (*condition*) {
fuctiona();
} else {
fuctionb();
}
- Use
else ifto add multiple conditions.
if (condition1) {
functionA();
} else if (condition2) {
statementX;
} else if (condition3) {
functionB();
} else {
lastStatment;
}
# Comparators and Equality
===Is equal to (Same type and value).==Is equal to (same value).!===Is not equal to.>Greater.<Lesser.>=Greater or equal.<=Lesser or equal.&&AND.||OR.!NOT.
# Collections/Array
var arrayName = []
arrayName.lengthReturns number of valuesarrayName[number]Returns value of the atnumberposition, starting at 0.arrayName.includes(value)Check if value invalueis in array.arrayName.pop()Remove last value of array.arrayName.shift()Remove first value of array.arrayName.push(value)Addvalueto end of array.arrayName.length = 4Will set arrayName.length to 4, any element whose index is greater than or equal to 4 will be removed.arrayName.length = 0Will empty array.
# Loops
-while condition is true, run functionA()
while (condition) {
functionA();
}
foriterate
for (start; end; change) {
//Do something
};
for (i=0; i<2; i++) {
functionA();
}
# Object
- An object is a collection of property/values and function
var object1 = {
property: value,
property2: "string2",
property3: ["arrayString1", "arrayString2"],
};
# Constructor Function
- Use to create multiple objects
- Function name first letter Capitalized.
thiskeyword refers to owner of the function.
function ConstFunction(property1, property2) {
this.property1 = property1;
this.property2 = property2;
}
// Initialize Object
var object1 = new ConstFunction("prop1", [19, 20]);
# Methods
- A function associated with an object.
- Use dot-notation and double brackets() to call method.
- If use without (), will return function definition.
// add method in constructor function
function Object(prop1, prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
this.methodName = function() {
//function
};
}
// add method to an object
object.name = function() {
return this.prop1 + this.prop2;
};
// object use method
object1.methodName();
# Callback Function
document.addEventListner(typeOfEvent, function(event) {
console.log(event);
});
function sayHi(name) {
console.log("Hi" + name);
}
# Arrow Function
- Syntax
// normal function
function sum(a, b) {
return a + b
};
function isPositive(number) {
return number >= 0
};
function randomNumber() {
let integer = Math.floor(Math.random()*10);
return integer
};
document.addEventListener("click", function() {
console.log("click")
});
// arrow function
let sum2 = (a, b) => a + b;
// parenthese optional if only one parameter
let isPositive2 = number => number >= 0;
// if no parameter, empty parentese or _
// curly brackets required for multiple expressions/statements
// if using curly brackets or function in a block, must use *return* statement
let randomNumber2 = () => {
let i = Math.floor(Math.random()*10);
return i;
};
document.addEventListener("click", () => console.log("click");
// if returning object literals, it needs to be wrapped in parentheses
x => ({x,y})
Arugment binding
thiswith arrow function binds to context NOT to function itselfArrow functions are callable but not constructible
Duplicate parameters are not allowed.
Dont use arrow functions
- Object methods
- Callback functions with dynamic context
# DOM
# Switch
switch (thingWeAreGoingToSwitchOn) {
case "expression":
// what to do;
break;
case "expression2"
// what else to do;
break;
default:
// what to do if nothing else is triggered;
}
# Template literals
Enclosed by backticks (`) instead of double quotes.
- Allow multi-line strings
`Hello
World`;
// Hello
// World
- Can contain placeholders to embed expressions ${expressions}.
const port = 3000;
app.listen(port, () => console.log(`App running on ${port}`);
let a = 5
console.log(`Ten is ${a * 2}` // Ten is 10
- To escape backticks, put backslash / before backtick `
`\`` === "`"; // --> true
# Date
let now = new Date()now = current date time.
# Spread/Rest Operator (...)
# Spread syntax
Spread out arguments (for function calls), elements (array literals), or object expression (object literals) into individual argument/element/object key-value pair.
// 1. In function calls
Math.min(45, 23, -4, 12) // -4
const temperatures1 = [45, 23, -4, 12]
Math.min(temperatures1) // NaN
Math.min(...temperatures1) // -4
Math.min.apply(null, temperatures) // -4
Math.min(-1, ...temperatures1, 4, ...temperatures2, 5, ...[3]) // can be used multiple times
// 2. In array literals
const toSun = ["Mercury", "Venus"]
const awaySun = ["Mars", "Jupiter", "Saturn", "Uranus", Neptune"]
const planets = [...toSun, "Earth", ...awaySun] // (8) ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
//3. In object literals
let productBasic = {sku: "1010", name: "charger"}
let productPrice = {price: 890, currency: "thb"}
let product = {...productBasic, ...productPrice} // {sku: "1010", name: "table", price: 980, currency: "thb"}
# Rest syntax
Opposite of spread. Collect multiple elements into single element.
# Filter/Search
# Search through Arrays
Methods to search through Arrays
# Array.includes
# Array.find
# Array.indexOf
# Array.filter
# Console
- console.log()
- console.error() - red
- console.warn() - yellow
- console.clear()
- console.time() & console.timeEnd() - Use string prameter to measure time
- console.table()
- console.count()
- console.group() & console.groupEnd()