# Javascript

# Beginners

  • Javascript is case-sensitive and uses Unicode.
  • Instructions are called statements and seperated by ;.
  • // comments or /* Multi-line comment */

# Data Types

  • string A string of characters "Hello World".
  • numbers An integer 123 or floating point number 3.14159.
  • bigint
  • boolean true or false.
  • null A keyword denoting a null or unknown value.
  • undefined Unassigned value
  • symbol
  • object

# Variables

A variable stores data. There are 3 different:

  1. var Declares a local or global variable.
  2. let Declares a block-scoped (scoped to the immediate enclosing block { }), local variable.
  3. const Declares 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, numbers0-9, $, and _.
  • Optional camelCase for naming.

# Functions

  1. Calling Function
  2. Input (Parameter, Arguments)
  3. Output return
  • Function expressions produces a value
  • Function statements performs an action

# Conditionals

  • Use if statement to run a statement if a condition is true.
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 else clause if statement is false.
if (*condition*) {
    fuctiona();
} else {
    fuctionb();
}
  • Use else if to 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.length Returns number of values
  • arrayName[number] Returns value of the at number position, starting at 0.
  • arrayName.includes(value) Check if value in value is in array.
  • arrayName.pop() Remove last value of array.
  • arrayName.shift() Remove first value of array.
  • arrayName.push(value) Add value to end of array.
  • arrayName.length = 4 Will set arrayName.length to 4, any element whose index is greater than or equal to 4 will be removed.
  • arrayName.length = 0 Will empty array.

# Loops

-while condition is true, run functionA()

while (condition) {
    functionA();
}
  • for iterate
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.
  • this keyword 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

  1. 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})
  1. Arugment binding this with arrow function binds to context NOT to function itself

  2. Arrow functions are callable but not constructible

  3. Duplicate parameters are not allowed.

Dont use arrow functions

  1. Object methods
  2. 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.

# Search through Arrays

Methods to search through Arrays

# Array.includes

# Array.find

# Array.indexOf

# Array.filter

# Console

  1. console.log()
  2. console.error() - red
  3. console.warn() - yellow
  4. console.clear()
  5. console.time() & console.timeEnd() - Use string prameter to measure time
  6. console.table()
  7. console.count()
  8. console.group() & console.groupEnd()

# References

Last Updated: 1/7/2021, 10:38:55 AM