Hello coders... It's a very nice feeling to type something daily about Techs. I always felt special to give some time to write an article or blog. So let's start friends...
Today I am going to write about different Operators, Maths and Dates in Javascript. I will try to make it explaitive.
What is an Operator?
In JavaScript, an operator is a special symbol used to perform operations on operands (values and variables). For example,
2 + 3; // 5
Here +
is an operator that performs addition, and 2
and 3
are operands. 2 is the left operand and 3 is called the right operand.
JavaScript Operator Types
Here is a list of different operators you will learn in this article.
Assignment Operator
Assignment operators are used to assign values to variables. For example,
const x = 5;
Here, the =
operator is used to assign value 5
to variable x
.
Here's a list of commonly used assignment operators
Operator | Name | Example |
= | Assignment operator | a = 7; // 7 |
+= | Addition assignment | a += 5; // a = a + 5 |
-= | Subtraction Assignment | a -= 2; // a = a - 2 |
*= | Multiplication Assignment | a *= 3; // a = a * 3 |
/= | Division Assignment | a /= 2; // a = a / 2 |
%= | Remainder Assignment | a %= 2; // a = a % 2 |
**= | Exponentiation Assignment | a **= 2; // a = a**2 |
Arithmetic Operator
Arithmetic operators are used to perform arithmetic calculations. For example,
const number = 3 + 5; // 8
Here, the +
operator is used to add two operands.
Operator | Name | Example |
+ | Addition | x + y |
- | Subtraction | x - y |
* | Multiplication | x * y |
/ | Division | x / y |
% | Remainder | x % y |
++ | Increment (increments by 1) | ++x or x++ |
-- | Decrement (decrements by 1) | --x or x-- |
** | Exponentiation (Power) | x ** y |
Comparison Operator
Comparison operators compare two values and return a boolean value, either true
or false
. For example,
const a = 3, b = 2;
console.log(a > b); // true
Here, the comparison operator >
is used to compare whether a is greater than b.
Operator | Description | Example |
== | Equal to: returns true if the operands are equal | x == y |
!= | Not equal to: returns true if the operands are not equal | x != y |
=== | Strict equal to: true if the operands are equal and of the same type | x === y |
!== | Strict not equal to: true if the operands are equal but of different type or not equal at all | x !== y |
> | Greater than: true if left operand is greater than the right operand | x > y |
>= | Greater than or equal to: true if left operand is greater than or equal to the right operand | x >= y |
< | Less than: true if the left operand is less than the right operand | x < y |
<= | Less than or equal to: true if the left operand is less than or equal to the right operand | x <= y |
Logical Operator
Logical operators perform logical operations and return a boolean value, either true
or false
. For example,
const x = 5, y = 3;
(x < 6) && (y < 5); // true
Here, &&
is the logical operator AND. Since both x < 6
and y < 5
are true
, the result is true
.
Operator | Description | Example | ||||
&& | Logical AND: true if both the operands are true , else returns false | x && y | ||||
` | ` | Logical OR: true if either of the operands is true ; returns false if both are false | `x | y` | ||
! | Logical NOT: true if the operand is false and vice-versa. | !x |
Bitwise Operator
Bitwise operators perform operations on binary representations of numbers.
Operator | Description | |
& | Bitwise AND | |
` | ` | Bitwise OR |
^ | Bitwise XOR | |
~ | Bitwise NOT | |
<< | Left shift | |
>> | Sign-propagating right shift | |
>>> | Zero-fill right shift |
Bitwise operators are rarely used in everyday programming.
String Operator
In JavaScript, you can also use the +
operator to concatenate (join) two or more strings.
Example of String Operator
// concatenation operator
console.log('hello' + 'world');
let a = 'JavaScript';
a += ' tutorial'; // a = a + ' tutorial';
console.log(a);
Output
helloworld
JavaScript tutorial
Other Javascript Operator
Here's a list of other operators available in JavaScript. You will learn about these operators in later tutorials.
Operator | Description | Example |
, | evaluates multiple operands and returns the value of the last operand. | let a = (1, 3 , 4); // 4 |
?: | returns value based on the condition | (5 > 3) ? 'success' : 'error'; // "success" |
delete | deletes an object's property, or an element of an array | delete x |
typeof | returns a string indicating the data type | typeof 3; // "number" |
void | discards the expression's return value | void(x) |
in | returns true if the specified property is in the object | prop in object |
instanceof | returns true if the specified object is of of the specified object type | object instanceof object_type |
Math in Javascript
Like other Operators, there are Math Operators in Javascript. It is very useful. We will understand them with examples.
Math.random()
It will return a number between 0 to 1. (Not equal to 1)
let randomNumber = Math.random()
console.log(randomNumber)
// Output: 0.16668531572829082
Math.round()
It will return us a value of a number rounded to the nearest integer.
let number = 3.87;
// round the number to nearest integer
let roundedNumber = Math.round(number);
console.log(roundedNumber);
// Output: 4
Math.pow()
The Math.pow()
static method returns the value of a base raised to a power. That is
πΌπππ.πππ ( π‘ , π’ ) = x y
// computes 52
let power = Math.pow(5, 2);
console.log(power);
// Output: 25
Math.max()
The Math.max()
static method returns the largest of the numbers given as input parameters, or -Infinity
if there are no parameters.
let numbers = Math.max(12, 4, 5, 9, 0, -3);
console.log(numbers);
// Output: 12
Math.min()
The Math.min()
static method returns the smallest of the numbers given as input parameters, or Infinity
if there are no parameters.
let numbers = Math.min(12, 4, 5, 9, 0, -3);
console.log(numbers);
// Output: -3
Math.floor()
The Math.floor()
static method always rounds down and returns the largest integer less than or equal to a given number.
let number = 38.8;
// round number to nearest smallest number
let roundedNumber = Math.floor(number);
console.log(roundedNumber);
// Output: 38
Math.ceil()
The Math.ceil()
static method always rounds up and returns the smaller integer greater than or equal to a given number.
let number = Math.ceil(4.3);
console.log(number);
// Output: 5
Math.sqrt()
The sqrt()
method computes the square root of a specified number and returns it.
// square root of 4
let number = Math.sqrt(4);
console.log(number);
// Output: 2
Math.PI
The Math.PI
property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159.
let number = Math.PI;
console.log(number);
// Output: 3.14159
There are many more Math operators also exist. You need to find yourself from MDN Docs.
Date in Javascript
In JavaScript, date and time are represented by the Date
object. The Date
object provides the date and time information and also provides various methods.
A JavaScript date defines the EcmaScript epoch that represents milliseconds since 1 January 1970 UTC. This date and time is the same as the UNIX epoch (predominant base value for computer-recorded date and time values).
There are four ways to create a date object.
New Date()
We can create a date object using the new Date()
constructor. For example,
const timeNow = new Date();
console.log(timeNow); // shows current date and time
// Mon Jul 06 2020 12:03:49 GMT+0530 (India Time)
new Date(milliseconds)
The Date
object contains a number that represents milliseconds since 1 January 1970 UTC.
new Date(milliseconds)
creates a new date object by adding the milliseconds to the zero time. For example,
const time1 = new Date(0);
// epoch time
console.log(time1); // Thu Jan 01 1970 05:30:00
// 100000000000 milliseconds after the epoch time
const time2 = new Date(100000000000)
console.log(time2); // Sat Mar 03 1973 15:16:40
new Date(date string)
new Date(date string)
creates a new date object from a date string.
In JavaScript, there are generally three date input formats.
ISO Date Format:
You can create a date object by passing ISO date formats. For example,
// ISO Date(International Standard)
const date = new Date("2020-07-01");
// the result date will be according to UTC
console.log(date); // Wed Jul 01 2020 05:45:00 GMT+0545
You can also pass only the year and month or only the year. For example,
const date = new Date("2020-07");
console.log(date); // Wed Jul 01 2020 05:45:00 GMT+0545
const date1 = new Date("2020");
console.log(date1); // Wed Jul 01 2020 05:45:00 GMT+0545
You can also pass specific time to ISO dates.
const date = new Date("2020-07-01T12:00:00Z");
console.log(date); // Wed Jul 01 2020 17:45:00 GMT+0545
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(year, month,...)
creates a new date object by passing specific date and time. For example,
const time1 = new Date(2020, 1, 20, 4, 12, 11, 0);
console.log(time1); // Thu Feb 20 2020 04:12:11
The passed argument has a specific order.
If four numbers are passed, it represents year, month, day and hours. For example,
const time1 = new Date(2020, 1, 20, 4);
console.log(time1); // Thu Feb 20 2020 04:00:00
Similarly, if two arguments are passed, it represents year and month. For example,
const time1 = new Date(2020, 1);
console.log(time1); // Sat Feb 01 2020 00:00:00
JavaScript Date Methods
There are various methods available in JavaScript Date object.
Method | Description |
now() | Returns the numeric value corresponding to the current time (the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC) |
getFullYear() | Gets the year according to local time |
getMonth() | Gets the month, from 0 to 11 according to local time |
getDate() | Gets the day of the month (1β31) according to local time |
getDay() | Gets the day of the week (0-6) according to local time |
getHours() | Gets the hour from 0 to 23 according to local time |
getMinutes | Gets the minute from 0 to 59 according to local time |
getUTCDate() | Gets the day of the month (1β31) according to universal time |
setFullYear() | Sets the full year according to local time |
setMonth() | Sets the month according to local time |
setDate() | Sets the day of the month according to local time |
setUTCDate() | Sets the day of the month according to universal time |
const timeInMilliseconds = Date.now();
console.log(timeInMilliseconds); // 1593765214488
const time = new Date;
// get day of the month
const date = time.getDate();
console.log(date); // 30
// get day of the week
const year = time.getFullYear();
console.log(year); // 2020
const utcDate = time.getUTCDate();
console.log(utcDate); // 30
const event = new Date('Feb 19, 2020 23:15:30');
// set the date
event.setDate(15);
console.log(event.getDate()); // 15
// Only 28 days in February!
event.setDate(35);
console.log(event.getDate()); // 7
Thanks for patiently reading...
(Reference- https://www.programiz.com/)