Better to use declarations or self to modify variables - javascript

This is probably a stupid question, but im wondering which is better practice for JS
var expireDefault = new Date();
expireDefault.setYear(expireDefault.getFullYear() + 1);
This is how i am getting next years date at run time.
I have been told however to use a seperate Date() decleration.
var today = new Date();
var expireDefault = new Date();
expireDefault.setYear(today.getFullYear() + 1);
Is this necsecary ? Or does it even matter ?
In my opinion from this example i dont circular reference.
But the principles remain the same.

The two are equivalent.
The second one is just uselessly verbose and heavy. Don't use it : it hides the simplicity of what is done.

The second one is only necessary if you want to use later today's date. If not, you are unnecessarily using memory to store a Date object and so, first option is better.

I would prefer the first approach, it reads better, but that's just an oppinion. Take a look at momentjs, which is an amazing lib dealing with dates.

Related

Is the IF function removing the date object in javascript?

I've spent an hour looking for answers and trying different things so I appreciate any help here.
The following code works great for finding someone's part B effective date. However, when someone's birthday is really on the 1st of a month the 'if' function get's used, and I'm no longer able to format and write the date. It's almost like 'partB_eff' is no longer a date object. (I'm a newbie, so I might just be making this part up.)
I'm getting the error "TypeError: partB_eff.toLocaleDateString is not a function at AutoFill_6_Step_Checklist(Code:24:27)"
How can I resolve this?
let birthday = new Date(e.values[2]);
//this is a date entered from a google form
let bdayCopy = new Date(birthday);
//I created this since I'll be using .setMonth(), and I don't want to change the original date of the birhtday
let bday65 = new Date(bdayCopy.setMonth(bdayCopy.getMonth()+780));
//finds the 65th birthday
let partB_eff = new Date(bdayCopy.setDate(01));
//find's the Medicare part B effective date (the 1st of the month someone turns 65)
if(birthday.getDate()==1){
partB_eff = partB_eff.getMonth-1;
//if the person's birthday is really on the 1st of the month, the part b effective date is the 1st of the month prior. partB_eff must be converted
}
partB_eff = partB_eff.toLocaleDateString('en-us',{year:"numeric",month: "short",day:"numeric"});
//format partB_eff so that it looks nice on paper
partB_eff = partB_eff.getMonth-1;
Doesn't do what you think it does. What it does is get the vound function getDate from your date object, and attempt to subtract one from it. In any other language trying to do subtraction on a function would be a type error, but Javascript is Javascript and allows numeric operations on almost any type. A function minus a number in JS is NaN. NaN doesn't have a method called toLocaleString, hence the error.
What's interesting is that you did the same operation correctly above with bdayCopy.setMonth(bdayCopy.getMonth()+780)
Just do the same thing here
bdayCopy = new Date(bdayCopy.setMonth(bdayCopy.getMonth()-1));
Also some important concepts. if in Javascript is not a function. if is a keyword that starts a conditional statement. You can't do any of the things you can do with a function with if. You can't call it or assign it to a variable or pass ot as a function argument. Clearly understanding what a function is is something you need to do to be able to work in JS, or frankly any other language.
Finally if you are doing date math in JS I strongly recommend you use a date library like DateFns or Moment. Javascript native date APIs are possibly the worst designed date API of any language ever.

Efficient way to run code based on time

I want to run come specific code after specific timing but with a efficient technique, Not with SetTimeout/SetInterval.
Like request to Database to check data on a after specific time dialy.
I want to query database at after 5:00 pm. So i write this code.
function checkVotingQuestionTime{
var currentDate = new Date();
if(currentDate .getHours =>5){
//go to database
}
}
But I have to write this code in setInterval(checkVotingQuestionTime, 60000);
Is there any better way to do this job? I guess current code is performance killer. register event etc
I would recommend using a 3rd party solution like
http://bunkat.github.io/later/
or
http://bunkat.github.io/schedule/
The first will overwrite setInterval() for you, so that you can use later schedules instead of providing a timeoffset in milliseconds:
https://bunkat.github.io/later/execute.html#set-interval

How to detect changes with Date objects in Angular2?

Date objects that are modified using setDate method arent getting updated in template.
In template:
<p>{{date | date:'mediumDate'}}</p>
In component:
nextDay(){
this.date.setDate(this.date.getDate()+1);
}
But when I call nextDay function, the template isnt updated with the new value.
The only way I could get the change detection working was doing this:
nextDay(){
var tomorrow = new Date();
tomorrow.setDate(this.date.getDate()+1);
this.date = tomorrow;
}
Are there a better way to accomplish this same task?
I think that is the right way, to change the reference of the date variable. From the docs here we have:
The default change detection algorithm looks for differences by comparing bound-property values by reference across change detection runs.
So if the date reference remains the same, nothing will happen. You need a new Date reference and that's why the second version of nextDay() works.
If you remove the formatting pipe you will see that still only the second version of nextDay() works.

How do i use a for loop to loop every argument into newDate?

I have a timeMachine function that takes in 5 parameters and tells you what day it is after the time you entered. But instead of writing newDate.setDate(dateObject.getDate()+daysLater); i want to use a for loop that loops over the arguments' length and logs the inputs into newDate.
var timeMachine=function(yearsLater,monthsLater,daysLater,hoursLater,minutesLater) {
var dateObject=new Date();
var newDate=new Date();
newDate.setDate(dateObject.getDate()+daysLater);
newDate.setMonth(dateObject.getMonth()+monthsLater);
newDate.setYear(dateObject.getFullYear()+yearsLater);
newDate.setHours(dateObject.getHours()+hoursLater);
newDate.setMinutes(dateObject.getMinutes()+minutesLater);
console.log(newDate);
}
timeMachine()
This isn't using a for loop, but I'd suggest using MomentJS for any date-based manipulation. Speaking from personal experience, time manipulation is easy to mess up.
Moment already has this sort of "timeMachine()" functionality built in. For instance:
var futureMoment = moment()
.add(yearsLater, 'years')
.add(monthsLater, 'months')
.add(daysLater, 'days')
.add(hoursLater, 'hours')
.add(minutesLater, 'minutes');
console.log(futureMoment.format()); // <<== get a formatted string
console.log(futureMoment.toDate()); // <<== 'toDate' gets the native Date object
It also has copious documentation, and good plugins for added functionality. If you add moment-parseformat, you can easily parse most real-world Date strings (i.e. "November 20th, 2015" or "11/20/15" or "2015/11/20", etc) into Moment objects.
Basically, don't do this yourself unless you really need the bare bones functionality. Standing on the shoulders of giants is much easier.

Generating a unique ID in javascript. Understanding this code

Here is a code snippet i've come across for creating uniqueIDs in a script.
var now = (new Date()).valueOf();
var future = (new Date()).valueOf();
while(future == now){
future = (new Date()).valueOf();
}
return future;
My question is, why use .valueOf() instead of .getTime() and is the purpose of two date objects and a while loop to avoid the change of returning the same values if called multiple times. Surely the chances of returning the same millisecond representation of the date are slim to none? Any thoughts?
As you stated, the chance of getting back the same uuid is small - but not impossible. There is no real need to use valueOf instead of getTime. Also there are way better algorithms for generating UUIDS see https://github.com/pnegri/uuid-js for well tested implementations which are also time based.
I would personally use .getTime() method adding some kind of basic operation, such a pseudo-aleatory number generation added to the returned quantity in milliseconds. Simply because a millisecond is not 100% a reliable output, as Dan Pichelman said, "You'd be surprised how much you can do in a millisecond these days".

Categories

Resources