You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
///////////////////////////////////////// Converting and Checking Numbersconsole.log(23===23.0);// Base 10 - 0 to 9. 1/10 = 0.1. 3/10 = 3.3333333// Binary base 2 - 0 1console.log(0.1+0.2);console.log(0.1+0.2===0.3);// Conversionconsole.log(Number('23'));console.log(+'23');// Parsingconsole.log(Number.parseInt('30px',10));console.log(Number.parseInt('e23',10));console.log(Number.parseInt(' 2.5rem '));console.log(Number.parseFloat(' 2.5rem '));// console.log(parseFloat(' 2.5rem '));// Check if value is NaNconsole.log(Number.isNaN(20));console.log(Number.isNaN('20'));console.log(Number.isNaN(+'20X'));console.log(Number.isNaN(23/0));// Checking if value is numberconsole.log(Number.isFinite(20));console.log(Number.isFinite('20'));console.log(Number.isFinite(+'20X'));console.log(Number.isFinite(23/0));console.log(Number.isInteger(23));console.log(Number.isInteger(23.0));console.log(Number.isInteger(23/0));
Number.parseInt() Number here provides something called "Namespace".
Math and Rounding
///////////////////////////////////////// Math and Roundingconsole.log(Math.sqrt(25));console.log(25**(1/2));console.log(8**(1/3));console.log(Math.max(5,18,23,11,2));console.log(Math.max(5,18,'23',11,2));console.log(Math.max(5,18,'23px',11,2));console.log(Math.min(5,18,23,11,2));console.log(Math.PI*Number.parseFloat('10px')**2);console.log(Math.trunc(Math.random()*6)+1);constrandomInt=(min,max)=>Math.floor(Math.random()*(max-min)+1)+min;// 0...1 -> 0...(max - min) -> min...max// console.log(randomInt(10, 20));// Rounding integersconsole.log(Math.round(23.3));console.log(Math.round(23.9));console.log(Math.ceil(23.3));console.log(Math.ceil(23.9));console.log(Math.floor(23.3));console.log(Math.floor('23.9'));console.log(Math.trunc(23.3));console.log(Math.trunc(-23.3));// -23console.log(Math.floor(-23.3));// -24// Rounding decimalsconsole.log((2.7).toFixed(0));console.log((2.7).toFixed(3));console.log((2.345).toFixed(2));console.log(+(2.345).toFixed(2));
max function here actually does type coercion.
floor() is little bit better than trunc() because it works in all cases no matter if we are dealing with positive or negative numbers.
Primitives actually don't have methods. And so behind the scenes, JavaScript will do boxing. Boxing is to basically transform this to a number object, then call the method on that object. And then once the operation is finished it will convert it back to a primitive.
The BigInt is a new primitive type that can represent whole numbers bigger than 253 - 1, which is the largest number Javascript can reliably represent with the number type.
Append n to a literal integer or use BigInt() function to create a bigint.
///////////////////////////////////////// Working with BigIntconsole.log(2**53-1);console.log(Number.MAX_SAFE_INTEGER);console.log(2**53+1);console.log(2**53+2);console.log(2**53+3);console.log(2**53+4);console.log(4838430248342043823408394839483204n);console.log(BigInt(48384302));// Operationsconsole.log(10000n+10000n);console.log(36286372637263726376237263726372632n*10000000n);// console.log(Math.sqrt(16n));consthuge=20289830237283728378237n;constnum=23;console.log(huge*BigInt(num));// Exceptionsconsole.log(20n>15);console.log(20n===20);console.log(typeof20n);console.log(20n=='20');console.log(huge+' is REALLY big!!!');// Divisionsconsole.log(11n/3n);console.log(10/3);
Creating Dates
///////////////////////////////////////// Creating Dates// Create a dateconstnow=newDate();console.log(now);console.log(newDate('Aug 02 2020 18:05:41'));console.log(newDate('December 24, 2015'));console.log(newDate(account1.movementsDates[0]));console.log(newDate(2037,10,19,15,23,5));console.log(newDate(2037,10,31));console.log(newDate(0));console.log(newDate(3*24*60*60*1000));// Working with datesconstfuture=newDate(2037,10,19,15,23);console.log(future);console.log(future.getFullYear());console.log(future.getMonth());console.log(future.getDate());console.log(future.getDay());console.log(future.getHours());console.log(future.getMinutes());console.log(future.getSeconds());console.log(future.toISOString());console.log(future.getTime());console.log(newDate(2142256980000));console.log(Date.now());future.setFullYear(2040);console.log(future);
///////////////////////////////////////// Timers// setTimeoutconstingredients=['olives','spinach'];constpizzaTimer=setTimeout((ing1,ing2)=>console.log(`Here is your pizza with ${ing1} and ${ing2} 🍕`),3000,
...ingredients);console.log('Waiting...');if(ingredients.includes('spinach'))clearTimeout(pizzaTimer);// setIntervalsetInterval(function(){constnow=newDate();console.log(now);},1000);
Project Bankist Code
'use strict';//////////////////////////////////////////////////////////////////////////////////////////////////// BANKIST APP/////////////////////////////////////////////////// Data// DIFFERENT DATA! Contains movement dates, currency and localeconstaccount1={owner: 'Jonas Schmedtmann',movements: [200,455.23,-306.5,25000,-642.21,-133.9,79.97,1300],interestRate: 1.2,// %pin: 1111,movementsDates: ['2019-11-18T21:31:17.178Z','2019-12-23T07:42:02.383Z','2020-01-28T09:15:04.904Z','2020-04-01T10:17:24.185Z','2020-05-08T14:11:59.604Z','2020-07-26T17:01:17.194Z','2020-07-28T23:36:17.929Z','2020-08-01T10:51:36.790Z',],currency: 'EUR',locale: 'pt-PT',// de-DE};constaccount2={owner: 'Jessica Davis',movements: [5000,3400,-150,-790,-3210,-1000,8500,-30],interestRate: 1.5,pin: 2222,movementsDates: ['2019-11-01T13:15:33.035Z','2019-11-30T09:48:16.867Z','2019-12-25T06:04:23.907Z','2020-01-25T14:18:46.235Z','2020-02-05T16:33:06.386Z','2020-04-10T14:43:26.374Z','2020-06-25T18:49:59.371Z','2020-07-26T12:01:20.894Z',],currency: 'USD',locale: 'en-US',};constaccounts=[account1,account2];/////////////////////////////////////////////////// ElementsconstlabelWelcome=document.querySelector('.welcome');constlabelDate=document.querySelector('.date');constlabelBalance=document.querySelector('.balance__value');constlabelSumIn=document.querySelector('.summary__value--in');constlabelSumOut=document.querySelector('.summary__value--out');constlabelSumInterest=document.querySelector('.summary__value--interest');constlabelTimer=document.querySelector('.timer');constcontainerApp=document.querySelector('.app');constcontainerMovements=document.querySelector('.movements');constbtnLogin=document.querySelector('.login__btn');constbtnTransfer=document.querySelector('.form__btn--transfer');constbtnLoan=document.querySelector('.form__btn--loan');constbtnClose=document.querySelector('.form__btn--close');constbtnSort=document.querySelector('.btn--sort');constinputLoginUsername=document.querySelector('.login__input--user');constinputLoginPin=document.querySelector('.login__input--pin');constinputTransferTo=document.querySelector('.form__input--to');constinputTransferAmount=document.querySelector('.form__input--amount');constinputLoanAmount=document.querySelector('.form__input--loan-amount');constinputCloseUsername=document.querySelector('.form__input--user');constinputClosePin=document.querySelector('.form__input--pin');/////////////////////////////////////////////////// FunctionsconstformatMovementDate=function(date,locale){constcalcDaysPassed=(date1,date2)=>Math.round(Math.abs(date2-date1)/(1000*60*60*24));constdaysPassed=calcDaysPassed(newDate(),date);console.log(daysPassed);if(daysPassed===0)return'Today';if(daysPassed===1)return'Yesterday';if(daysPassed<=7)return`${daysPassed} days ago`;// const day = `${date.getDate()}`.padStart(2, 0);// const month = `${date.getMonth() + 1}`.padStart(2, 0);// const year = date.getFullYear();// return `${day}/${month}/${year}`;returnnewIntl.DateTimeFormat(locale).format(date);};constformatCur=function(value,locale,currency){returnnewIntl.NumberFormat(locale,{style: 'currency',currency: currency,}).format(value);};constdisplayMovements=function(acc,sort=false){containerMovements.innerHTML='';constmovs=sort
? acc.movements.slice().sort((a,b)=>a-b)
: acc.movements;movs.forEach(function(mov,i){consttype=mov>0 ? 'deposit' : 'withdrawal';constdate=newDate(acc.movementsDates[i]);constdisplayDate=formatMovementDate(date,acc.locale);constformattedMov=formatCur(mov,acc.locale,acc.currency);consthtml=` <div class="movements__row"> <div class="movements__type movements__type--${type}">${i+1}${type}</div> <div class="movements__date">${displayDate}</div> <div class="movements__value">${formattedMov}</div> </div> `;containerMovements.insertAdjacentHTML('afterbegin',html);});};constcalcDisplayBalance=function(acc){acc.balance=acc.movements.reduce((acc,mov)=>acc+mov,0);labelBalance.textContent=formatCur(acc.balance,acc.locale,acc.currency);};constcalcDisplaySummary=function(acc){constincomes=acc.movements.filter(mov=>mov>0).reduce((acc,mov)=>acc+mov,0);labelSumIn.textContent=formatCur(incomes,acc.locale,acc.currency);constout=acc.movements.filter(mov=>mov<0).reduce((acc,mov)=>acc+mov,0);labelSumOut.textContent=formatCur(Math.abs(out),acc.locale,acc.currency);constinterest=acc.movements.filter(mov=>mov>0).map(deposit=>(deposit*acc.interestRate)/100).filter((int,i,arr)=>{// console.log(arr);returnint>=1;}).reduce((acc,int)=>acc+int,0);labelSumInterest.textContent=formatCur(interest,acc.locale,acc.currency);};constcreateUsernames=function(accs){accs.forEach(function(acc){acc.username=acc.owner.toLowerCase().split(' ').map(name=>name[0]).join('');});};createUsernames(accounts);constupdateUI=function(acc){// Display movementsdisplayMovements(acc);// Display balancecalcDisplayBalance(acc);// Display summarycalcDisplaySummary(acc);};conststartLogOutTimer=function(){consttick=function(){constmin=String(Math.trunc(time/60)).padStart(2,0);constsec=String(time%60).padStart(2,0);// In each call, print the remaining time to UIlabelTimer.textContent=`${min}:${sec}`;// When 0 seconds, stop timer and log out userif(time===0){clearInterval(timer);labelWelcome.textContent='Log in to get started';containerApp.style.opacity=0;}// Decrease 1stime--;};// Set time to 5 minuteslettime=120;// Call the timer every secondtick();consttimer=setInterval(tick,1000);returntimer;};///////////////////////////////////////// Event handlersletcurrentAccount,timer;// FAKE ALWAYS LOGGED IN// currentAccount = account1;// updateUI(currentAccount);// containerApp.style.opacity = 100;btnLogin.addEventListener('click',function(e){// Prevent form from submittinge.preventDefault();currentAccount=accounts.find(acc=>acc.username===inputLoginUsername.value);console.log(currentAccount);if(currentAccount?.pin===+inputLoginPin.value){// Display UI and messagelabelWelcome.textContent=`Welcome back, ${currentAccount.owner.split(' ')[0]}`;containerApp.style.opacity=100;// Create current date and timeconstnow=newDate();constoptions={hour: 'numeric',minute: 'numeric',day: 'numeric',month: 'numeric',year: 'numeric',// weekday: 'long',};// const locale = navigator.language;// console.log(locale);labelDate.textContent=newIntl.DateTimeFormat(currentAccount.locale,options).format(now);// const day = `${now.getDate()}`.padStart(2, 0);// const month = `${now.getMonth() + 1}`.padStart(2, 0);// const year = now.getFullYear();// const hour = `${now.getHours()}`.padStart(2, 0);// const min = `${now.getMinutes()}`.padStart(2, 0);// labelDate.textContent = `${day}/${month}/${year}, ${hour}:${min}`;// Clear input fieldsinputLoginUsername.value=inputLoginPin.value='';inputLoginPin.blur();// Timerif(timer)clearInterval(timer);timer=startLogOutTimer();// Update UIupdateUI(currentAccount);}});btnTransfer.addEventListener('click',function(e){e.preventDefault();constamount=+inputTransferAmount.value;constreceiverAcc=accounts.find(acc=>acc.username===inputTransferTo.value);inputTransferAmount.value=inputTransferTo.value='';if(amount>0&&receiverAcc&¤tAccount.balance>=amount&&receiverAcc?.username!==currentAccount.username){// Doing the transfercurrentAccount.movements.push(-amount);receiverAcc.movements.push(amount);// Add transfer datecurrentAccount.movementsDates.push(newDate().toISOString());receiverAcc.movementsDates.push(newDate().toISOString());// Update UIupdateUI(currentAccount);// Reset timerclearInterval(timer);timer=startLogOutTimer();}});btnLoan.addEventListener('click',function(e){e.preventDefault();constamount=Math.floor(inputLoanAmount.value);if(amount>0&¤tAccount.movements.some(mov=>mov>=amount*0.1)){setTimeout(function(){// Add movementcurrentAccount.movements.push(amount);// Add loan datecurrentAccount.movementsDates.push(newDate().toISOString());// Update UIupdateUI(currentAccount);// Reset timerclearInterval(timer);timer=startLogOutTimer();},2500);}inputLoanAmount.value='';});btnClose.addEventListener('click',function(e){e.preventDefault();if(inputCloseUsername.value===currentAccount.username&&+inputClosePin.value===currentAccount.pin){constindex=accounts.findIndex(acc=>acc.username===currentAccount.username);console.log(index);// .indexOf(23)// Delete accountaccounts.splice(index,1);// Hide UIcontainerApp.style.opacity=0;}inputCloseUsername.value=inputClosePin.value='';});letsorted=false;btnSort.addEventListener('click',function(e){e.preventDefault();displayMovements(currentAccount.movements,!sorted);sorted=!sorted;});