Day 35 - 10/10

Plan: Learning Js

  • Array

  • Date

  • Random

  • Booleans

  • Comparison

  • If else

Progress:

Number object methods

  • Number.isInteger(x); : return true if x is an integer

  • Number.isSafeInteger(x); : check if a number safe

Safe integer are all integers from (2^53 - 1) to -(2^53 - 1).

  • Number.parseFloat("x"); : parse a string and return the first number

  • Number.parseInt("x"); : parses a string and returns a whole number

Number Properties

  • let var = Number.EPSILON; : the difference between the smallest floating point number greater than 1 and 1

  • let var = Number.MAX_VALUE; : the largest possible number in JavaScript

  • let var = Number.MIN_VALUE; : the lowest possible number in JavaScript

  • let var = Number.MAX_SAFE_INTEGER; : is (2^53 - 1)

  • let var = Number.MIN_SAFE_INTEGER; : is -(2^53 - 1)

  • let var = Number.POSITIVE_INFINITY; : is infinity

  • let var = Number.NEGATIVE_INFINITY; : is -infinity

  • let var = Number.NaN; : check if a var is a number or not

Arrays

const array_name = [item1, item2, ...];

or

const array_name = [];

array_name[0]= "item1";

array_name[1]= "item2";

array_name[2]= "item3";

  • can use array_name[n] = "itemN"; to change the value in specified position

  • .toString() : convert array to string (comma separated)

  • array is object

  • array elements can be objects: can have variables of different types in the same Array (have objects in array; have functions in array; have arrays in array

Array properties

  • array.length : number of elements

  • loop

for (let i = 0; i < length; i++) { }

or

array.forEach(function);

  • adding: array.push(" ");

  • in Js, arrays always use number index

  • Create an array with one element: const points = [40];

  • Create an array with 40 undefined elements: const points = new Array(40);

  • Array.isArray(x) : check if a var is an array or not

  • object instanceof Array; check if an object is created by a given constructor

Array methods

  • .length

  • .toString() : array to string with comma seperated

  • .pop() : remove the last item

  • .push() : add an item to tail

  • shift() : remove the first item and shift the rest to a lower index

  • unshift() : add an item to head and un-shift the rest

  • join()

  • delete ; : delete the item and leave undefined hole

  • .concat(); : merge existing arrays

  • .flat(); : reduce the dimension of an array

  • .splice(x, y, "item"); : add item to position x, with y items removed from that position toward.

  • .slice(x, y); : remove y items from position x without leaving undefined holes; if y is omitted, it will remove every item before x

Array sort

  • .sort(); : sort an array alphabetically (work well on string, not number)

  • .reverse(); : reverse an array

Numeric sort

array.sort(function(a, b){return a - b});

compare function function(a, b)

When comparing 40 and 100, the sort() method calls the compare function(40, 100)

  • if return negative, 40 is sorted before 100

  • if return positive, 40 is sorted after 100

  • if return 0, no change

Random sort

array.sort(function(){return 0.5 - Math.random()});

Fisher Yates Method - random sort

for (let i = array.length -1; i > 0; i--) {

let j = Math.floor(Math.random() * (i+1));

let k = array[i];

array[i] = array[j];

array[j] = k; }

Math.max() / Math.min()

Find max/min number in an array

function myArrayMax(arr) {

return Math.max.apply(null, arr);

}

function myArrayMin(arr) {

return Math.min.apply(null, arr);

}

Find Min/Max Js method

function myArrayMax(arr) {

let len = arr.length;

let max = -Infinity;

while (len--) {

if (arr[len] > max) {

max = arr[len];

}

}

return max;

}

Sort Object array

const cars = [

{type:"Volvo", year:2016},

{type:"Saab", year:2001},

{type:"BMW", year:2010} ];

  • Sort with number:

cars.sort(function(a, b){return a.year - b.year});

  • Sort with string

cars.sort(function(a, b){

let x = a.type.toLowerCase();

let y = b.type.toLowerCase();

if (x < y) {return -1;}

if (x > y) {return 1;}

return 0; });

Array Iteration

  • .forEach(function) : call function once for each item

  • .map(function) : create a new array by execute the old one with function

  • .flatmap(function) ?

  • .filter(function) : create an array with elements passed some conditions

  • .reduce() : create an array by running a function on each array element from left to right to produce (reduce it to) a single value.

  • .reduceRight() : create an array by running a function on each array element from right to left to produce (reduce it to) a single value.

  • .every() : check if every elements pass the conditions

  • .some() : check if some elements pass the conditions

  • .indexOf(item, start) : search for an element and return its first position

  • .lastIndexOf(item, start) : search for an element and return its last position

  • .find(function) : return the first number that passes conditions

  • .findIndex() : returns the index of the first array element that passes a test function

  • Array.from() : returns an Array object from any object with a length property or any iterable object

  • .keys() : returns an Array Iterator object with the keys of an array

  • .entries() : Create an Array Iterator, and then iterate over the key/value pairs

  • .includes() : check if an element is present in an array

  • Spread (...) : expands an iterable (like an array) into more elements

Array Const

  • An array declared with const cannot be reassigned

  • Element can be reasssigned

  • An array declared with const must be initialized when it is declared;

const cars;

cars = ["Saab", "Volvo", "BMW"];

  • Arrays declared with var can be initialized at any time

cars = ["Saab", "Volvo", "BMW"];

var cars;

  • Const : Block Scope - Redeclaring

  • Var : Block Scope - Redeclaring

Date Object

Create date object with current date and time

  • new Date()

Creates a date object from a date string

  • new Date(date string)

Create date object with a specified date and time

  • new Date(year,month)

  • new Date(year,month,day)

  • new Date(year,month,day,hours)

  • new Date(year,month,day,hours,minutes)

  • new Date(year,month,day,hours,minutes,seconds)

  • new Date(year,month,day,hours,minutes,seconds,ms)

  • new Date(milliseconds)

Month count from 0 - 11

Day / month overflow will add to the next month / year

One and two digit years will be interpreted as 19xx

Dates are saved as number of milliseconds since January 01, 1970.

Displaying date

const d = new Date();

Default: date.toString();

More readable: date.toDateString();

UTC standard: date.toUTCString();

ISO standard: date.toISOString();

Date Format

Output format

ISO:

  • Date: (YYYY-MM-DD)

  • Date - Time: (YYYY-MM-DDTHH:MM:SSZ)

Short Date: (MM/DD/YYYY)

Long Date: (MM DD YYYY)

Input format

Get the number of milliseconds between the date and Jan 1, 1970 and convert to a date object:

let msec = Date.parse("March 21, 2012");

const d = new Date(msec);

Get Date Methods

  • d.getFullYear(); : return just the year as 4 digit number

  • d.getMonth(); : return just the month as number (0-11)

  • d.getDate(); : return just the day as number (1-31)

  • d.getHours(); : (0-23)

  • d.getMinutes(); : (0-59)

  • d.getSeconds(); : (0-59)

  • d.getMilliseconds(); : (0-999)

  • d.getDay(); : (0-6)

  • d.getTime(); : return the number of milliseconds since January 1, 1970

  • Date.now(); : returns the number of milliseconds since January 1, 1970

  • .getTimezoneOffset() : returns the difference (in minutes) between local time an UTC time

Set Date Methods

  • d.setFullYear(x);

  • d.setMonth(0-11);

  • d.setDate(1-31);

  • d.setHours(0-23);

  • d.setMinutes(0-59);

  • d.setSeconds(0-59);

Random

  • Math.random(); : returns a random number between 0 and 1

  • Math.floor(Math.random() * 10^n); : returns a random number

Boolean

Everything without a value is False

Last updated