JavaScript if, else, and else if

JavaScript if, else, and else if are conditional statements that allow you to execute different blocks of code based on different conditions.

if

The if statement is used to execute a block of code if a specified condition is true. The syntax is as follows:

if (condition) {
// code to execute if condition is true
}

The condition can be any expression that evaluates to a boolean value. If the condition is true, the code block inside the if statement is executed. Otherwise, the code block is skipped.

else

The else statement is used to execute a block of code if the condition in the if statement is false. The syntax is as follows:

if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}

else if

The else if statement is used to test a new condition if the condition in the if statement is false. The syntax is as follows:

if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition1 is false and condition2 is true
} else {
// code to execute if both condition1 and condition2 are false
}

You can have as many else if statements as you need. The code blocks in the else if statements are executed in order, until one of the conditions evaluates to true. If none of the conditions evaluate to true, the code block in the else statement is executed.

Examples

The following examples show how to use if, else, and else if statements:

// Check if a number is even or odd
const number = 10;

if (number % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}


// Output: “The number is even.”

// Check if a user is above or below the legal drinking age
const age = 21;

if (age >= 21) {
console.log("You are of legal drinking age.");
} else {
console.log("You are not of legal drinking age.");
}


// Output: “You are of legal drinking age.”

// Determine the grade a student received based on their exam score
const examScore = 85;

if (examScore >= 90) {
console.log("A");
} else if (examScore >= 80) {
console.log("B");
} else if (examScore >= 70) {
console.log("C");
} else if (examScore >= 60) {
console.log("D");
} else {
console.log("F");
}
// Output: “B”

Tips

Use curly braces ({}) to group the code blocks in your ifelse, and else if statements. This makes your code more readable and easier to maintain.

Use indentation to make your code more readable.

Test your code carefully to make sure it is working as expected.

JavaScript Comparison and Logical Operators

Comparison and logical operators are fundamental tools for writing conditional statements and controlling the flow of your code. In JavaScript, there are seven comparison operators and three logical operators.

Comparison Operators

Comparison operators are used to compare two values and return a Boolean value (true or false). The following table summarizes the JavaScript comparison operators:

OperatorDescriptionExample
==Equal to (value and type)10 == 10 evaluates to true
===Strict equal to (value and type)10 === 10 evaluates to true, but 10 === "10" evaluates to false
!=Not equal to (value or type)10 != 10 evaluates to false, but 10 != "10" evaluates to true
!==Strict not equal to (value and type)10 !== 10 evaluates to false, but 10 !== "10" evaluates to true
<Less than10 < 15 evaluates to true
>Greater than15 > 10 evaluates to true
<=Less than or equal to10 <= 15 evaluates to true
>=Greater than or equal to15 >= 10 evaluates to true

Logical Operators

Logical operators are used to combine two or more Boolean expressions and return a single Boolean value. The following table summarizes the JavaScript logical operators:

OperatorDescriptionExample
&&Logical ANDtrue && true evaluates to true, but true && false and false && true evaluate to false
``Logical OR
!Logical NOT!true evaluates to false, and !false evaluates to true

Combining Comparison and Logical Operators

You can combine comparison and logical operators to create more complex conditional expressions. For example, the following expression evaluates to true only if the value of age is greater than or equal to 18 and the value of isCitizen is true:

(age >= 18) && isCitizen;

You can also use parentheses to group expressions and control the order in which they are evaluated. For example, the following expression evaluates to true only if the value of age is greater than 18 or the value of isCitizen is true:

(age >= 18) || isCitizen;

Examples

Here are some examples of how to use comparison and logical operators in JavaScript:

// Check if the value of `age` is greater than or equal to 18.
if (age >= 18) {
console.log("You are old enough to vote.");
} else {
console.log("You are not old enough to vote.");
}


// Check if the value of `age` is greater than or equal to 18 and the value of `isCitizen` is `true`.
if ((age >= 18) && isCitizen) {
console.log("You are eligible to vote.");
} else {
console.log("You are not eligible to vote.");
}


// Check if the value of `age` is greater than 18 or the value of `isCitizen` is `true`.
if ((age >= 18) || isCitizen) {
console.log("You are eligible to vote or to become a citizen.");
} else {
console.log("You are not eligible to vote or to become a citizen.");
}

JavaScript Booleans

Booleans in JavaScript are one of the most important data types, as they allow us to represent true or false values. Booleans are used in a variety of ways, such as in conditional statements, loops, and functions.

Creating Booleans

There are two ways to create Booleans in JavaScript:

Using the keywords true and false:

const isLoggedIn = true;
const hasErrors = false;

Using the Boolean() constructor:

const isLoggedIn = Boolean(1); // true
const hasErrors = Boolean(0); // false

The Boolean() constructor will convert any value to a Boolean value. If the value is non-zero, the Boolean() constructor will return true. Otherwise, it will return false.

Boolean Operators

JavaScript provides a number of Boolean operators that can be used to combine and compare Boolean values. These operators include:

Logical AND (&&): Returns true if both operands are true, otherwise returns false.

Logical OR (||): Returns true if either operand is true, otherwise returns false.

Logical NOT (!): Reverses the Boolean value of the operand.

For example:

const isLoggedIn = true;
const hasErrors = false;

console.log(isLoggedIn && !hasErrors);
// true
console.log(isLoggedIn || hasErrors); // true
console.log(!isLoggedIn); // false

Boolean Comparisons

JavaScript also provides a number of comparison operators that can be used to compare Boolean values. These operators include:

Equal to (==): Returns true if both operands are equal, otherwise returns false.

Not equal to (!=): Returns true if both operands are not equal, otherwise returns false.

For example:

const isLoggedIn = true;

console.log(isLoggedIn == true);
// true
console.log(isLoggedIn != false); // true

Using Booleans in Conditional Statements

Booleans are often used in conditional statements to control the flow of a program. For example, the following code uses an if statement to check if the user is logged in. If the user is logged in, the code displays a welcome message:

const isLoggedIn = true;

if (isLoggedIn) {
console.log('Welcome!');
}

Using Booleans in Loops

Booleans can also be used in loops to control how many times a loop iterates. For example, the following code uses a while loop to print the numbers from 1 to 10:

let i = 1;

while (i <= 10) {
console.log(i);
i++;
}

The loop will continue to iterate as long as the condition i <= 10 is evaluated to true.

Using Booleans in Functions

Booleans can also be used as parameters and return values for functions. For example, the following function takes a Boolean parameter and returns a Boolean value:

function isEven(number) {
return number % 2 === 0;
}

const isTenEven = isEven(10);
// true

The isEven() function returns true if the number is even, and false otherwise.

Conclusion

Booleans are an essential data type in JavaScript. They are used in a variety of ways, such as in conditional statements, loops, and functions. By understanding how to use Booleans, you can write more powerful and efficient JavaScript code.

JavaScript Random

In JavaScript, the Math.random() function is used to generate a random number between 0 (inclusive) and 1 (exclusive). This means that the function can return any number between 0 and 0.999999…, but it will never return 1.

To use the Math.random() function, simply call it without any arguments:

const randomNumber = Math.random();

This will generate a new random number each time the function is called.

Generating random integers

If you want to generate a random integer, you can use the Math.floor() function to round down the result of the Math.random() function.

For example, to generate a random integer between 1 and 10, you would use the following code:

const randomNumber = Math.floor(Math.random() * 10) + 1;

This will generate a number between 1 and 10, inclusive.

Generating random numbers within a range

To generate a random number within a specific range, you can use the following formula:

const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;

where min is the minimum value in the range and max is the maximum value in the range.

For example, to generate a random number between 10 and 20, you would use the following code:

const randomNumber = Math.floor(Math.random() * (20 - 10 + 1)) + 10;

This will generate a number between 10 and 20, inclusive.

Generating random strings

To generate a random string, you can use the following code:

function generateRandomString(length) {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let randomString = '';
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
randomString += characters[randomIndex];
}
return randomString;
}

This function will generate a random string of the specified length. For example, to generate a random string of 10 characters, you would use the following code:

const randomString = generateRandomString(10);

This will generate a random string of 10 characters, such as 'jdf7823lkas'.

Using random numbers in JavaScript games

Random numbers are often used in JavaScript games to generate random events, such as the appearance of enemies or the outcome of a battle.

For example, you could use a random number to generate the chance of an enemy appearing on the screen:

const enemyAppearanceChance = 0.2; // 20% chance
const enemyAppeared = Math.random() < enemyAppearanceChance;

if (enemyAppeared) {

// Create a new enemy object
}

This code will generate a random number between 0 and 1. If the number is less than enemyAppearanceChance, then an enemy will appear on the screen. Otherwise, no enemy will appear.

You can also use random numbers to generate the outcome of a battle:

const attackPower = 10; // Player’s attack power
const enemyDefense = 5; // Enemy’s defense
const damage = attackPower - enemyDefense;
const enemyHealth = 100;
// Enemy’s health
enemyHealth -= damage;
if (enemyHealth <= 0) {

// Enemy is defeated
}

This code will generate a random number between 0 and 1. If the number is less than the player’s attack power, then the player will hit the enemy. Otherwise, the player will miss.

The amount of damage that the player deals to the enemy is calculated by subtracting the enemy’s defense from the player’s attack power. If the enemy’s health is reduced to 0 or below, then the enemy is defeated.

JavaScript Math Object

The JavaScript Math object provides a set of mathematical functions and constants that can be used to perform various mathematical operations on numbers. The Math object is not a constructor, so it cannot be used to create new Math objects. Instead, all of its properties and methods are static, meaning that they can be accessed directly from the Math object itself.

Properties

The Math object has a single property, PI, which represents the mathematical constant pi.

// Get the value of pi
const pi = Math.PI;
// Use the value of pi to calculate the area of a circle
const radius = 5;
const area = pi * radius * radius;

// Display the area of the circle
console.log(area); // 78.53981633974483

Methods

The Math object has a wide variety of methods that can be used to perform various mathematical operations, such as:

Arithmetic operations: abs()ceil()floor()max()min()pow()round()sqrt(), etc.

Trigonometric functions: sin()cos()tan()asin()acos()atan(), etc.

Hyperbolic functions: sinh()cosh()tanh()asinh()acosh()atanh(), etc.

Other mathematical functions: exp()log()random(), etc.

For a complete list of all Math object methods, please refer to the MDN documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math.

Examples

Here are a few examples of how to use the Math object to perform various mathematical operations:

// Calculate the absolute value of a number
const absoluteValue = Math.abs(-10); // 10
// Round a number to the nearest integer
const roundedNumber = Math.round(3.14); // 3
// Calculate the sine of an angle const sine = Math.sin(Math.PI / 2); // 1
// Calculate the square root of a number
const squareRoot = Math.sqrt(16); // 4
// Generate a random number between 0 and 1
const randomNumber = Math.random(); // 0.12345678901234567
// Calculate the hypotenuse of a right triangle
const hypotenuse = Math.hypot(5, 12); // 13

Conclusion

The JavaScript Math object provides a powerful set of tools for performing various mathematical operations on numbers. By understanding the different properties and methods of the Math object, you can write more efficient and concise code.

JavaScript Set Date Methods

JavaScript provides a number of methods for setting the date and time of a Date object. These methods can be used to set individual components of the date and time, such as the year, month, day, hour, minute, second, and millisecond, or to set the entire date and time at once.

setDate()

The setDate() method sets the day of the month for the Date object (1-31). The setDate() method takes a single parameter, which is the day of the month to set. If the specified day is outside of the valid range for the current month, the setDate() method will automatically adjust the month and year accordingly.

For example, the following code sets the day of the month for the current Date object to 15:

const now = new Date();
now.setDate(15);

The following code sets the day of the month for the Date object to 32, which will automatically adjust the month and year to the first day of the next month:

const nextMonth = new Date();
nextMonth.setDate(32);

setFullYear()

The setFullYear() method sets the year for the Date object. The setFullYear() method takes two parameters: the year to set and optionally the month to set. If the month parameter is omitted, the setFullYear() method will keep the current month.

For example, the following code sets the year for the current Date object to 2024:

const now = new Date();
now.setFullYear(2024);

The following code sets the year for the Date object to 2024 and the month to March:

const march2024 = new Date();
march2024.setFullYear(2024, 2);
// (March is the 3rd month)

setHours()

The setHours() method sets the hour of the day for the Date object (0-23). The setHours() method takes one parameter, which is the hour to set. If the specified hour is outside of the valid range, the setHours() method will automatically adjust the day accordingly.

For example, the following code sets the hour of the day for the current Date object to 15:

const now = new Date();
now.setHours(15);

setMinutes()

The setMinutes() method sets the minute of the hour for the Date object (0-59). The setMinutes() method takes one parameter, which is the minute to set. If the specified minute is outside of the valid range, the setMinutes() method will automatically adjust the hour accordingly.

For example, the following code sets the minute of the hour for the current Date object to 30:

const now = new Date();
now.setMinutes(30);

setSeconds()

The setSeconds() method sets the second of the minute for the Date object (0-59). The setSeconds() method takes one parameter, which is the second to set. If the specified second is outside of the valid range, the setSeconds() method will automatically adjust the minute accordingly.

For example, the following code sets the second of the minute for the current Date object to 45:

const now = new Date();
now.setSeconds(45);

setMilliseconds()

The setMilliseconds() method sets the millisecond of the second for the Date object (0-999). The setMilliseconds() method takes one parameter, which is the millisecond to set. If the specified millisecond is outside of the valid range, the setMilliseconds() method will automatically adjust the second accordingly.

For example, the following code sets the millisecond of the second for the current Date object to 500:

const now = new Date(); now.setMilliseconds(500);

setTime()

The setTime() method sets the time for the Date object in milliseconds since the Unix epoch (January 1, 1970 at 00:00:00 UTC). The setTime() method takes one parameter, which is the time in milliseconds to set.

For example, the following code sets the time for the current Date object to 12:00:00 UTC on January 1, 2024:

const now = new Date();
now.setTime(1672531200000);
// (milliseconds since the Unix epoch for January 1, 2024 at 12:00:00 UTC

JavaScript Get Date Methods

JavaScript provides a number of methods for getting information about a date object. These methods can be used to get the day of the week, month, year, hours, minutes, seconds, and milliseconds.

Creating a Date Object

Before you can use any of the JavaScript get date methods, you need to create a Date object. There are two ways to do this:

Use the new Date() constructor. This will create a Date object with the current date and time.

Pass a string representation of a date to the Date() constructor. This can be useful for creating Date objects from dates that were stored in a database or read from a file.

Get Date Methods

The following table lists the most common JavaScript get date methods:

| getDate() | Returns the day of the month (1-31). |

| getDay() | Returns the day of the week (0-6, where 0 is Sunday). |

| getMonth() | Returns the month (0-11, where 0 is January). |

| getFullYear() | Returns the year. |

| getHours() | Returns the hours (0-23). |

| getMinutes() | Returns the minutes (0-59). |

| getSeconds() | Returns the seconds (0-59). |

| getMilliseconds() | Returns the milliseconds (0-999). |

Examples

The following examples show how to use the JavaScript get date methods:

// Create a Date object with the current date and time.
const now = new Date();
// Get the day of the month.
const day = now.getDate();
// Get the day of the week.
const dayOfWeek = now.getDay();
// Get the month.
const month = now.getMonth();
// Get the year.
const year = now.getFullYear();
// Get the hours.
const hours = now.getHours();
// Get the minutes.
const minutes = now.getMinutes();
// Get the seconds.
const seconds = now.getSeconds();
// Get the milliseconds.
const milliseconds = now.getMilliseconds();
// Log the results to the console.
console.log(`Today is ${day}.`);
console.log(`The day of the week is ${dayOfWeek}.`);
console.log(`The month is ${month}.`);
console.log(`The year is ${year}.`);
console.log(`The time is ${hours}:${minutes}:${seconds}.${milliseconds}.`);

Using Get Date Methods in Real-World Applications

JavaScript get date methods can be used in a variety of real-world applications. For example, you could use them to:

Create a calendar application.

Calculate the number of days between two dates.

Calculate the age of a person.

Convert a date from one format to another.

Display the current date and time on a website.

Conclusion

JavaScript get date methods are a powerful tool for working with dates and times. By understanding how to use these methods, you can write more complex and sophisticated JavaScript applications.

JavaScript Date Formats

JavaScript stores dates as milliseconds since January 01, 1970. Zero time is January 01, 1970 00:00:00 UTC. One day (24 hours) is 86 400 000 milliseconds.

To create a new Date object, you can use the new Date() constructor. For example, the following code creates a new Date object for the current date and time:

const now = new Date();

You can also pass a string representation of a date to the Date() constructor. For example, the following code creates a new Date object for the date “2023-10-14 00:44:06 PST”:

const date = new Date("2023-10-14 00:44:06 PST");

Once you have a Date object, you can use its methods to get and set the year, month, day, hour, minute, second, and millisecond of the date. You can also use its methods to format the date in a variety of ways.

Formatting dates in JavaScript

There are two main ways to format dates in JavaScript:

Using the toLocaleDateString() method

Using the toLocaleTimeString() method

The toLocaleDateString() method formats a date according to the user’s locale. The toLocaleTimeString() method formats a time according to the user’s locale.

For example, the following code formats the current date in the user’s locale:

const formattedDate = now.toLocaleDateString();

The following code formats the current time in the user’s locale:

const formattedTime = now.toLocaleTimeString();

You can also pass arguments to the toLocaleDateString() and toLocaleTimeString() methods to specify additional formatting options. For example, the following code formats the current date in the MM/DD/YYYY format:

const formattedDate = now.toLocaleDateString("en-US", {
year: "numeric",
month: "numeric",
day: "numeric",
});

The following code formats the current time in the HH:mm:ss format:

const formattedTime = now.toLocaleTimeString("en-US", {
hour: "numeric",
minute: "numeric",
second: "numeric",
});

Custom date formats

In addition to using the toLocaleDateString() and toLocaleTimeString() methods, you can also use custom date formats in JavaScript.

To create a custom date format, you can use the following steps:

Create a new object and assign it to the options variable.

Set the format property of the options object to your desired date format.

Pass the options object to the toLocaleDateString() or toLocaleTimeString() method.

For example, the following code creates a custom date format that displays the date in the MM/DD/YYYY format:

const options = {
format: "MM/DD/YYYY",
};
const formattedDate = now.toLocaleDateString("en-US", options);

The following code creates a custom date format that displays the time in the HH:mm:ss format:

const options = {
format: "HH:mm:ss",
};
const formattedTime = now.toLocaleTimeString("en-US", options);

Conclusion

JavaScript provides a variety of ways to format dates. You can use the toLocaleDateString() and toLocaleTimeString() methods to format dates according to the user’s locale. You can also use custom date formats to format dates in any way you want.

JavaScript Date Objects

JavaScript Date Objects are used to represent and manipulate dates and times. They are created using the new Date() constructor, which takes a variety of arguments to specify the date and time.

Creating a Date Object

There are four ways to create a Date Object:

With no arguments: This will create a Date Object representing the current date and time.

With a single number argument: This will create a Date Object representing the specified number of milliseconds since the Unix epoch (January 1, 1970 at midnight UTC).

With a date string argument: This will create a Date Object representing the date and time specified in the string. The string must be in a format that JavaScript can understand, such as YYYY-MM-DD or MM/DD/YYYY.

With seven number arguments: This will create a Date Object representing the date and time specified by the seven arguments, which are the year, month, day, hour, minute, second, and millisecond.

Examples:

// Create a Date Object representing the current date and time.
const now = new Date();
// Create a Date Object representing the number of milliseconds since the Unix epoch.
const epoch = new Date(0);
// Create a Date Object representing the date and time specified in the string.
const christmas = new Date('2023-12-25');
// Create a Date Object representing the date and time specified by the seven arguments.
const birthday = new Date(1995, 11, 17, 12, 0, 0, 0);

Getting and Setting Date and Time Components

Date Objects have a number of built-in methods for getting and setting the different components of a date and time, such as the year, month, day, hour, minute, second, and millisecond.

For example, to get the current year, you would use the getFullYear() method. To set the current year to 2024, you would use the setFullYear() method.

Examples:

// Get the current year.
const year = now.getFullYear();
// Set the current year to 2024.
now.setFullYear(2024);
// Get the current month.
const month = now.getMonth();
// Set the current month to December.
now.setMonth(11);
// Get the current day of the month.
const day = now.getDate();
// Set the current day of the month to 25.
now.setDate(25);
// Get the current hour.
const hour = now.getHours();
// Set the current hour to 12.
now.setHours(12);
// Get the current minute.
const minute = now.getMinutes();
// Set the current minute to 0.
now.setMinutes(0);
// Get the current second.
const second = now.getSeconds();
// Set the current second to 0.
now.setSeconds(0);
// Get the current milliseconds.
const milliseconds = now.getMilliseconds();
// Set the current milliseconds to 0.
now.setMilliseconds(0);

Formatting Dates and Times

Date Objects also have a number of built-in methods for formatting dates and times in different ways. For example, you can use the toLocaleDateString() method to format a date in the user’s locale. You can use the toLocaleTimeString() method to format a time in the user’s locale.

Examples:

// Format the current date in the user’s locale.
const dateString = now.toLocaleDateString();
// Format the current time in the user’s locale.
const timeString = now.toLocaleTimeString();

Date Arithmetic

Date Objects can also be used to perform date arithmetic. For example, you can use the setDate() method to add or subtract days from a date. You can use the setHours() method to add or subtract hours from a time.

Examples:

// Add 1 day to the current date.
now.setDate(now.getDate() + 1);
// Subtract 1 hour from the current time.
now.setHours(now.getHours() - 1);

Conclusion

JavaScript Date Objects are a powerful tool for working with dates and times. They can be used to create, format, and manipulate dates and times in a variety of ways.

JavaScript Array Const Tutorial

What is const?

The const keyword in JavaScript is used to declare a constant variable. A constant variable is a variable that cannot be reassigned.

What is an array?

An array in JavaScript is a data structure that can store multiple values of any type. Arrays are objects, and the values stored in an array are the properties of that object.

How to create a constant array

To create a constant array, you can use the const keyword followed by the [] operator. For example:

const myArray = [1, 2, 3, 4, 5];

This code will create a constant array called myArray that contains the values 1, 2, 3, 4, and 5.

Can you modify the elements of a constant array?

Yes, you can modify the elements of a constant array. However, you cannot reassign the variable itself. For example:

const myArray = [1, 2, 3, 4, 5];
myArray[0] = 10;
// This is allowed
myArray = [6, 7, 8, 9, 10]; // This is not allowed

The first line of code is allowed because it is modifying the value of the first element of the myArray array. However, the second line of code is not allowed because it is trying to reassign the myArray variable itself.

When to use a constant array

You should use a constant array when you need to ensure that the array cannot be reassigned. This is useful for situations where you need to prevent accidental changes to the array. For example, you might use a constant array to store the values of a configuration file or the results of a calculation.

Benefits of using constant arrays

There are several benefits to using constant arrays:

They prevent accidental changes to the array. This can help to improve the accuracy and reliability of your code.

They make your code more readable and maintainable. It is clear to other developers that a constant array should not be changed.

They can help to improve the performance of your code. The JavaScript engine can optimize code that uses constant arrays.

Example of using a constant array

Here is an example of how to use a constant array to store the values of a configuration file:

const config = {
database: {
host: "localhost",
port: 3306,
username: "root",
password: "password",
},
};
//
… // Use the config object to connect to the database

In this example, the config object is a constant object. This ensures that the values of the database configuration cannot be accidentally changed.

Conclusion

Constant arrays are a useful feature of JavaScript. They can help to improve the accuracy, readability, maintainability, and performance of your code.