JS template literals: not defined - javascript

As I'm writing this function which holds a parameter 'day', I'de like to log the chosen day to the console.
I'm getting the output 'day is not defined' and I cannot figure out why (I'm new to JS).
I believe 'day' is defined because I call the function with an argument.
const getSleepHours = day => {
if (day === 'monday'){
return 8;
} else if (day === 'tuesday'){
return 7;
} else if (day === 'wednesday'){
return 8;
} else if (day === 'thursday'){
return 9;
} else if (day === 'friday'){
return 8;
} else if (day === 'saturday'){
return 9;
} else if (day === 'sunday'){
return 9;
} else {
return 'Please enter a valid day';
}
};
console.log('You have slept for: ' + getSleepHours('sunday') + ' hours');
console.log(`${day}`);

In the function definition syntax, "day" has to be wrapped in paranthesis () as (day). Below is how i would implement it
const getSleepHours = (day) => {
var hours = 0;
switch(day){
case "sunday":
hours=1;
break;
case "monday":
hours=2;
break;
default:
hours=0;
}
return hours;
}
const daysCount = getSleepHours('sunday');
console.log('You have slept for: '+ getSleepHours("sunday") +' hours');
console.log(daysCount);

const getSleepHours = day => { // this day variable will be considered as argument
if (day === 'monday'){
return 8;
} else if (day === 'tuesday'){
return 7;
} else if (day === 'wednesday'){
return 8;
} else if (day === 'thursday'){
return 9;
} else if (day === 'friday'){
return 8;
} else if (day === 'saturday'){
return 9;
} else if (day === 'sunday'){
return 9;
} else {
return 'Please enter a valid day';
}
};
const day = getSleepHours('sunday'); // define day variable so value will be stored which is returned from function.
console.log('You have slept for: ' + getSleepHours('sunday') + ' hours');
console.log(`${day}`);

Related

Javascript IF/ELSE - Shorten function

I am playing around with the JavaScript IF/ELSE to understand better how it works. As an exercise I took the following working hours of a shop:
6AM to 6PM = Open
6PM to 6AM = Closed
then I created a function that returns the word 'Open' or 'Closed' based on the 2 values "time" and "period".
function shopHours(time,period) {
if (time === 6 && period === 'AM') {
return 'Open';
} else if (time === 6 && period === 'AM') {
return 'Open';
} else if (time === 7 && period === 'AM') {
return 'Open';
} else if (time === 8 && period === 'AM') {
return 'Open';
} else if (time === 9 && period === 'AM') {
return 'Open';
} else if (time === 10 && period === 'AM') {
return 'Open';
} else if (time === 11 && period === 'AM') {
return 'Open';
} else if (time === 12 && period === 'PM') {
return 'Open';
} else if (time === 1 && period === 'PM') {
return 'Open';
} else if (time === 2 && period === 'PM') {
return 'Open';
} else if (time === 3 && period === 'PM') {
return 'Open';
} else if (time === 4 && period === 'PM') {
return 'Open';
} else if (time === 5 && period === 'PM') {
return 'Open';
} else {
return 'Closed';}
}
Everything works fine. However, I would like to be able to shorten the code as it looks too confusing.
I then tried the following:
function shopHours(time,period) {
if(time <= 6 && period === 'AM') {
return 'Closed';
} else if (time >= 6 && period === 'PM') {
return 'Closed';
} else if (time === 12 && period === 'PM') {
return 'Open';
} else {
return 'Open';}
}
The second code works fine too and is much shorter however there is a problem that I am not sure how to solve. When the time and period are set to 12 and PM, the result should be 'closed' but I am not sure how to implement this.
I have tried to add the following code but it seems that would not solve this problem.
else if (time === 12 && period === 'AM') {
return 'Closed';
}
I will be very grateful to anyone that will spend a bit of his time to take a look at this question.
Thank you!
You can break it down into two initial scenarios, either AM or PM. Then check the hour to see if it should be open or closed.
if (period == "AM") {
if (time < 6 || time == 12)
return "Closed";
return "Open";
}
else {
if (time >= 6 && time != 12)
return "Closed";
return "Open";
}
It's easier to work with 24-hour format, in my opinion.
One has to take 12PM = 12:00 and 12AM = 00:00 into account however.
After conversion the comparision is fairly easy.
function shopHours(time, period) {
let hour = time;
if (period === 'PM' && hour < 12) hour = hour + 12;
if (period === 'AM' && hour === 12) hour = hour - 12;
if (hour >= 6 && hour < 18) {
return 'Open';
}
return 'Closed';
}
console.log('12 AM is ' + shopHours(12, 'AM') + '. Expected it to be: Closed');
console.log('3 AM is ' + shopHours(3, 'AM') + '. Expected it to be: Closed');
console.log('6 AM is ' + shopHours(6, 'AM') + '. Expected it to be: Open');
console.log('9 AM is ' + shopHours(9, 'AM') + '. Expected it to be: Open');
console.log('12 PM is ' + shopHours(12, 'PM') + '. Expected it to be: Open');
console.log('3 PM is ' + shopHours(3, 'PM') + '. Expected it to be: Open');
console.log('6 PM is ' + shopHours(6, 'PM') + '. Expected it to be: Closed');
console.log('9 PM is ' + shopHours(9, 'PM') + '. Expected it to be: Closed');
My version.if goal is to just shorten the code, then those am() and pm() functions can be omitted and the code inside can be added where am calling them. That would be 3 lines of code.
function shopHours(time, period){
var result;
function am () {
Number(time) < 12 && Number(time) >= 6 ? result = "open" : result = "closed";
}
function pm() {
Number(time) <= 5 || Number(time) === 12 ? result = "open" : result = "closed";
}
period === 'AM' ? am() : pm();
return result;
}
console.log("12 AM is: ", shopHours(12, 'AM'), '; expected: closed');
console.log("3 AM is: ", shopHours(3, 'AM'), '; expected: closed');
console.log("6 AM is: ", shopHours(6, 'AM'), '; expected: open');
console.log("9 AM is: ", shopHours(9, 'AM'), '; expected: open');
console.log("12 PM is: ", shopHours(12, 'PM'), '; expected: open');
console.log("3 PM is: ", shopHours(3, 'PM'), '; expected: open');
console.log("6 PM is: ", shopHours(6, 'PM'), '; expected: closed');
console.log("9 PM is: ", shopHours(9, 'PM'), '; expected: closed');
This can be easily handled using date instead. Instead of using if else, You can define the openHours and closeHours. And pass the current time. You can easily compare then.
Sample:
function shopHours(time, period) {
let openHour = new Date();
let closeHour = new Date();
openHour.setHours(6);
closeHour.setHours(12 + 6);
let curreTime = new Date();
curreTime.setHours(period === "PM" ? 12 + time : time);
if (curreTime > openHour && curreTime < closeHour) return "Open";
return "Close";
}
console.log(shopHours(11, "PM"));
console.log(shopHours(12, "AM"));
console.log(shopHours(11, "AM"));
console.log(shopHours(7, "AM"));
console.log(shopHours(5, "AM"));
You can also just pass the currentTime and validate.
function shopHours(curreTime) {
let openHour = new Date();
let closeHour = new Date();
openHour.setHours(6);
closeHour.setHours(12 + 6);
if (curreTime > openHour && curreTime < closeHour) return "Open";
return "Close";
}
console.log(shopHours(new Date()));
My suggestion:
function shopHours(time, period) {
var status = "Open";
if ((period == "AM" && (time < 6 || time == 12)) || (time >= 6 && time != 12)) status = "Closed";
return status;
}
console.log(shopHours(5, "AM"));
console.log(shopHours(5, "PM"));

someone help me how to use if if else in java script using get current date

this is my code someone can help me i cant use if else on get current date i try all google tutorial no one work for me please good help for me if someone help me thank you in advance the only problem if else if i run this code if else wont read it
<script type="text/javascript">
function calc() {
var today = new Date();
var month = today.getMonth(); // Returns 9
console.log(month); // Output: 9
var textValue3 = document.getElementById('input3').value;
var textValue2 = document.getElementById('input2').value
var textValue1 = document.getElementById('input1').value;
var basic = 5;
if (month = '1') {
var rate_interest = 0;
}
else if (month = '2') {
var rate_interest = 0;
}
else if (month = '3') {
var rate_interest = 0.06;
}
else if (month = '4') {
var rate_interest = 0.08;
}
else if (month = '5') {
var rate_interest = 0.10;
}
else if (month = '6') {
var rate_interest = 0.12;
}
else if (month = '7') {
var rate_interest = 0.14;
}
else if (month = '8') {
var rate_interest = 0.16;
}
else if (month = '9') {
var rate_interest = 0.18;
}
else if (month = '10') {
var rate_interest = 0.20;
}
else if (month = '11') {
var rate_interest = 0.22;
}
else if (month = '12') {
var rate_interest = 0.24;
}
document.getElementById('output').value = (basic) + (textValue1 / 1000) + (textValue2 / 1000) + (textValue3 / 1000) + (basic * rate_interest);
}
</script>
In the 'if condition' you need to write == instead of =
date.getMonth() return the month in 0 to 11 so you need to plus one in a month.
function calc() {
var today = new Date();
var month = today.getMonth(); // Returns 9
month = month + 1;
console.log(month); // Output: 9
var textValue3 = document.getElementById('input3').value;
var textValue2 = document.getElementById('input2').value
var textValue1 = document.getElementById('input1').value;
var basic = 5;
var rate_interest;
if (month == 1) {
rate_interest = 0;
}
else if (month == 2) {
rate_interest = 0;
}
else if (month == 3) {
rate_interest = 0.06;
}
else if (month == 4) {
rate_interest = 0.08;
}
else if (month == 5) {
rate_interest = 0.10;
}
else if (month == 6) {
rate_interest = 0.12;
}
else if (month == 7) {
rate_interest = 0.14;
}
else if (month == 8) {
rate_interest = 0.16;
}
else if (month == 9) {
rate_interest = 0.18;
}
else if (month == 10) {
rate_interest = 0.20;
}
else if (month == 11) {
rate_interest = 0.22;
}
else if (month == 12) {
rate_interest = 0.24;
}
document.getElementById('output').value = (basic) + (textValue1 / 1000) + (textValue2 / 1000) + (textValue3 / 1000) + (basic * rate_interest);
}

Equivalent of arrow functions for IE

I wrote a program that works well in Google Chrome, but I just realized that it is having problems in IE. IE states that this is due to a syntax error given by the use of arrow functions since they are not supported in the latest IE. Can anyone tell me how to change my code to be able to run it on IE?
function removeRow(a, ref, plt, pcs, loc, trk, din) {
var pro;
swal("Enter the shipment's tracking information:", {
content: "input",
buttons: {
cancel: true,
roll: {
text: "Don't have it",
value: " ",
},
confirm: {
text: "Submit",
}
}
})
.then((value) => {
pro = value;
//console.log(pro);
if (pro !== null || pro === ' ') {
b = '#' + a;
c = '#H' + a;
var d = new Date();
var n = Math.round(d.getTime() / 1000);
var table = $('#mytable')
.DataTable();
// Remove a row by Id:
table.row(b)
.remove()
.draw();
var url = "delete.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: {
id: a,
track: pro,
dateout: n
},
success: function(data) {
//alert(data); // show response from the php script.
//console.log('Success!');
}
});
swal("Success", "Shipment was entered successfully!", "success");
if (ref == '') {
}
var t = $('#myhistory').DataTable();
t.row(c)
.remove()
.draw();
var reference = ref;
var pallets = plt;
var pieces = pcs;
var location = loc;
var carrier = trk;
var datein = din;
var dateout = n;
var rowid = 'H' + a;
if (datein.length < 12) {
var month = datein.toString().substring(0, 1);
if (month == '01') {
month = 'Jan';
} else if (month == '02') {
month = 'Feb';
} else if (month == '03') {
month = 'Mar';
} else if (month == '04') {
month = 'Apr';
} else if (month == '05') {
month = 'May';
} else if (month == '06') {
month = 'Jun';
} else if (month == '07') {
month = 'Jul';
} else if (month == '08') {
month = 'Aug';
} else if (month == '09') {
month = 'Sep';
} else if (month == '10') {
month = 'Oct';
} else if (month == '11') {
month = 'Nov';
} else if (month == '12') {
month = 'Dec';
}
var day = datein.toString().substring(1, 3);
var year = datein.toString().substring(3, 7);
var hour = datein.toString().substring(7, 9);
var second = datein.toString().substring(9, 11);
} else {
var month = datein.toString()
.substring(0, 2);
if (month == '01') {
month = 'Jan';
} else if (month == '02') {
month = 'Feb';
} else if (month == '03') {
month = 'Mar';
} else if (month == '04') {
month = 'Apr';
} else if (month == '05') {
month = 'May';
} else if (month == '06') {
month = 'Jun';
} else if (month == '07') {
month = 'Jul';
} else if (month == '08') {
month = 'Aug';
} else if (month == '09') {
month = 'Sep';
} else if (month == '10') {
month = 'Oct';
} else if (month == '11') {
month = 'Nov';
} else if (month == '12') {
month = 'Dec';
}
var day = datein.toString().substring(2, 4);
var year = datein.toString().substring(4, 8);
var hour = datein.toString().substring(8, 10);
var second = datein.toString().substring(10, 12);
}
var tout = new Date();
var timeout = tout.toString();
var monthout = tout.toString().substring(4, 7);
var dayout = tout.toString().substring(8, 10);
var yearout = tout.toString().substring(11, 16);
var hourout = tout.toString().substring(16, 18);
var secondout = tout.toString().substring(19, 21);
var dateout = monthout + ', ' + dayout + ' ' + yearout + ' at ' + hourout + ':' + secondout;
var datein = month + ', ' + day + ' ' + year + ' at ' + hour + ':' + second;
t.row.add([
reference,
pallets,
pieces,
location,
carrier,
datein,
dateout,
pro
])
.node()
.id = rowid;
t.draw(false);
}
});
}
I could be missing something, but after a quick skim of your code, only this line appears to use any ES6 syntax:
.then((value) => {
Simply change it to:
.then(function(value) {
If you have much more code and don't want to remove such references by hand, #jonrsharpe's suggestion of a transpiler is a good one.

minus 7 hours from 'now' date time datepicker entry

I have 2 datepickers, start and end time.
i want the start time to be minus 7 hours from "now"
i have this:
$('#<%= txtErrorStartDate.ClientID%>').val(formatDateTime(sqlNow('HH', -7), 'dateshorttime')).validate();
and this:
function formatDateTime(d, format, rtnObj) {
var arr
, type
, arrDate
, arrTime
, str
;
if (!d) {
if (rtnObj) {
return null;
} else {
return '';
}
}
switch (format) {
case 'shortdate':
type = 1;
break;
case 'shorttime':
type = 2;
break;
case 'dateshorttime':
type = 3;
break;
case 'datelongtime':
type = 4;
break;
case 'longtime':
type = 5;
break;
default:
if (rtnObj) {
return null;
} else {
return '';
}
}
if (typeof(d) === 'string') {
if (d.indexOf('/Date(') !== -1) {
// JSON date (milliseconds)
d = new Date(Number(d.replace('/Date(', '').replace(')/', '')));
} else {
str = true;
}
} else if (typeof(d) === 'number') {
d = new Date(d);
}
if (str) {
// Format string
d = $.trim(d);
if (d.indexOf(' ') !== -1) {
// Split date and time
arr = d.split(' ');
arrDate = arr[0].split('/');
arrTime = arr[1].split(':');
if (arrTime.length === 2) {
// Add missing seconds
arrTime.push('00');
}
} else if (d.indexOf('/') !== -1) {
// Split date
arrDate = d.split('/');
arrTime = ['00', '00', '00'];
} else {
arrDate = ['30', '12', '1899'];
arrTime = d.split(':');
if (arrTime.length === 2) {
// Add missing seconds
arrTime.push('00');
}
}
} else {
// Format Javascript date object
// Build date array
arrDate = [];
arrDate.push(d.getDate());
arrDate.push(d.getMonth() + 1);
arrDate.push(d.getFullYear());
// Build time array
arrTime = [];
arrTime.push(d.getHours());
arrTime.push(d.getMinutes());
arrTime.push(d.getSeconds());
// Single digit check
if (Number(arrDate[0]) < 10) { arrDate[0] = '0' + arrDate[0]; }
if (Number(arrDate[1]) < 10) { arrDate[1] = '0' + arrDate[1]; }
if (Number(arrTime[0]) < 10) { arrTime[0] = '0' + arrTime[0]; }
if (Number(arrTime[1]) < 10) { arrTime[1] = '0' + arrTime[1]; }
if (Number(arrTime[2]) < 10) { arrTime[2] = '0' + arrTime[2]; }
}
if (rtnObj) {
// Return Javascript object
// Take 1 from month (0 - 11)
arrDate[1] = String(Number(arrDate[1]) - 1);
switch (type) {
case 1: // shortdate
return new Date(arrDate[2], arrDate[1], arrDate[0]);
break;
case 2: // shorttime
return new Date('1899', '11', '30', arrTime[0], arrTime[1]);
break;
case 3: // dateshorttime
return new Date(arrDate[2], arrDate[1], arrDate[0], arrTime[0], arrTime[1]);
break;
case 4: // datelongtime
return new Date(arrDate[2], arrDate[1], arrDate[0], arrTime[0], arrTime[1], arrTime[2]);
break;
case 5: // longtime
return new Date('1899', '11', '30', arrTime[0], arrTime[1], arrTime[2]);
break;
}
} else {
// Return date string
switch (type) {
case 1: // shortdate
return arrDate.join('/');
break;
case 2: // shorttime
arrTime.pop();
return arrTime.join(':');
break;
case 3: // dateshorttime
arrTime.pop();
return arrDate.join('/') + ' ' + arrTime.join(':');
break;
case 4: // datelongtime
return arrDate.join('/') + ' ' + arrTime.join(':');
break;
case 5: // longtime
return arrTime.join(':');
break;
}
}
}
what i have is not working, i would like to know how to subtract 7 hours from the start time
added datepicker html:
<div class="inputrow" runat="server">
<label style="margin-left: 179px" class="inputlabel">Start Date</label>
<input runat="server" type="text" id="txtErrorStartDate" name="txtErrorStartDate1" class="dateshorttime datepick required" value="" data-taborder="1" required="" style="width: 18%" />
</div>
My java knowledge isn't great, but for what its worth, what I would do in C# to accomplish this is:
string startTime = DateTime.Now; // Fire whenever the event starts
string endTime = DateTime.Now; // Fire whenever the event ends
string subtractedTime = currentTime.ToString("HH") - 7; // The time subtracted by 7 hours
var start_time = new Date();
start_time.setHours(start_time.getHours()-7);
i have resolved the issue, with the line of code below.
$('#<%= txtErrorStartDate.ClientID%>').val(formatDateTime(dateAdd('hour', -7, sqlNow()), 'dateshorttime')).validate();
Thank you for your input.

Javascript getting the Leap Year

I need help with my code. I need to call my function leapYear() to my FieldValidator() function to determine if the year given by the user is leap year or not.
Here is my code:
function FieldValidator() {
var err = "";
var valid = false;
var leap = new leapYear(year)
//year
if(document.getElementById('year').value == ""){
valid = true;
err += "Enter year \n";
document.getElementById('year').style.borderColor = "red";
}
else if(document.getElementById('year').value < 1000 || document.getElementById('year').value > 9999){
valid = true;
err += "Invalid Year \n";
document.getElementById('year').style.borderColor = "red";
}
else {
document.getElementById('year').style.borderColor = "green";
}
//month
if(document.getElementById('month').value == ""){
valid = true;
err += "Enter Month \n";
document.getElementById('month').style.borderColor = "red";
}
else if(document.getElementById('month').value < 1 || document.getElementById('month').value > 12){
valid = true;
err += "Invalid Month\n";
document.getElementById('month').style.borderColor = "red";
}
else {
document.getElementById('month').style.borderColor = "green";
}
//day
if(document.getElementById('day').value == ""){
valid = true;
err += "Enter day \n";
document.getElementById('day').style.borderColor = "red";
}
else if (document.getElementById('month').value == 2) {
if(document.getElementById('year').value == leap()) {
if(document.getElementById('day').value > 29) {
valid = true;
err += "invalid leap\n";
document.getElementById('day').style.borderColor = "red";
}
else {
document.getElementById('day').style.borderColor = "green";
}
}
else if(document.getElementById('year').value != leap()) {
if(document.getElementById('day').value > 28) {
valid = true;
err += "invalid \n";
document.getElementById('day').style.borderColor = "red";
}
else {
document.getElementById('day').style.borderColor = "green";
}
}
}
else if (document.getElementById('month').value != 2) {
if(document.getElementById('day').value < 1 || document.getElementById('day').value > 31 ) {
valid = true;
err += "Invalid day \n";
document.getElementById('day').style.borderColor = "red";
}
else {
document.getElementById('day').style.borderColor = "green";
}
}
else {
document.getElementById('day').style.borderColor = "green";
}
if(valid){
alert(err)
return false;
}
return true;
}
function leapYear(year)
{
return ((document.getElementById('year').value % 4 == 0) && (document.getElementById('year').value % 100 != 0)) || (document.getElementById('year').value % 400 == 0);
}
For anything time related, I'm using momentjs (either like you in the browser or on the server in nodejs).
It's as simple as this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js">
var year = 2015;
moment([year]).isLeapYear(); // false
</script>
The isLeapYear function itself is quit simple, too. So you can use that to determine if the year is a leap year or not.
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
Source

Categories