Blog

  • RegExp Object

    regular expression (RegExp) in JavaScript is an object that describes a pattern of characters. It can contain the alphabetical, numeric, and special characters. Also, the regular expression pattern can have single or multiple characters.

    The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text.

    The regular expression is used to search for the particular pattern in the string or replace the pattern with a new string.

    There are two ways to construct the regular expression in JavaScript.

    • Using the RegExp() constructor.
    • Using the regular expression literal.

    Syntax

    A regular expression could be defined with the RegExp () constructor, as follows −

    var pattern = new RegExp(pattern, attributes);
    or simply
    var pattern = /pattern/attributes;
    

    Parameters

    Here is the description of the parameters −

    • pattern − A string that specifies the pattern of the regular expression or another regular expression.
    • attributes − An optional string containing any of the “g”, “i”, and “m” attributes that specify global, case-insensitive, and multi-line matches, respectively.

    Before we learn examples of regular expression, let’s learn about regular expression modifiers, Quantifiers, literal characters, etc.

    Modifiers

    Several modifiers are available that can simplify the way you work with regexps, like case sensitivity, searching in multiple lines, etc.

    Sr.No.Modifier & Description
    1iPerform case-insensitive matching.
    2mSpecifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary
    3gPerforms a global matchthat is, find all matches rather than stopping after the first match.

    Brackets

    Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.

    Sr.No.Expression & Description
    1[…]Any one character between the brackets.
    2[^…]Any one character not between the brackets.
    3[0-9]It matches any decimal digit from 0 through 9.
    4[a-z]It matches any character from lowercase through lowercase z.
    5[A-Z]It matches any character from uppercase A through uppercase Z.
    6[a-Z]It matches any character from lowercase a through uppercase Z.

    The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.

    Quantifiers

    The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character sequence.

    Sr.No.Expression & Description
    1p+It matches any string containing one or more p’s.
    2p*It matches any string containing zero or more p’s.
    3p?It matches any string containing at most one p.
    4p{N}It matches any string containing a sequence of N p’s
    5p{2,3}It matches any string containing a sequence of two or three p’s.
    6p{2, }It matches any string containing a sequence of at least two p’s.
    7p$It matches any string with p at the end of it.
    8^pIt matches any string with p at the beginning of it.
    9?!pIt matches any string which is not followed by a string p.

    Examples

    Following examples explain more about matching characters.

    Sr.No.Expression & Description
    1[^a-zA-Z]It matches any string not containing any of the characters ranging from a through z and A through Z.
    2p.pIt matches any string containing p, followed by any character, in turn followed by another p.
    3^.{2}$It matches any string containing exactly two characters.
    4<b>(.*)</b>It matches any string enclosed within <b> and </b>.
    5p(hp)*It matches any string containing a p followed by zero or more instances of the sequence hp.

    Literal characters

    The literal characters can be used with a backslash (\) in the regular expression. They are used to insert special characters, such as tab, null, Unicode, etc., in the regular expression.

    Sr.No.Character & Description
    1AlphanumericItself
    2\0The NUL character (\u0000)
    3\tTab (\u0009
    4\nNewline (\u000A)
    5\vVertical tab (\u000B)
    6\fForm feed (\u000C)
    7\rCarriage return (\u000D)
    8\xnnThe Latin character specified by the hexadecimal number nn; for example, \x0A is the same as \n
    9\uxxxxThe Unicode character specified by the hexadecimal number xxxx; for example, \u0009 is the same as \t
    10\cXThe control character ^X; for example, \cJ is equivalent to the newline character \n

    Metacharacters

    A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.

    For instance, you can search for a large sum of money using the ‘\d’ metacharacter: /([\d]+)000/, Here \d will search for any string of numerical character.

    The following table lists a set of metacharacters which can be used in PERL Style Regular Expressions.

    Sr.No.Character & Description
    1.a single character
    2\sa whitespace character (space, tab, newline)
    3\Snon-whitespace character
    4\da digit (0-9)
    5\Da non-digit
    6\wa word character (a-z, A-Z, 0-9, _)
    7\Wa non-word character
    8[\b]a literal backspace (special case).
    9[aeiou]matches a single character in the given set
    10[^aeiou]matches a single character outside the given set
    11(foo|bar|baz)matches any of the alternatives specified

    Let’s learn to create regular expressions below.

    let exp =/tutorialspoint/i
    • /tutorialspoint/ It finds a match for the ‘tutorialspoint’ string.
    • i It ignores the case of the characters while matching the pattern with the string. So, it matches with ‘TutoiralsPoint’, or ‘TUTORIALSpoint’, etc.
    let exp =/\d+/
    • \d It matches 0 to 9 digits.
    • + It matches one or more numeric digits.
    let exp =/^Hi/
    • ^ – It matches the start of the text.
    • Hi It checks whether the text contains ‘Hi’ at the start.
    Let exp =/^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{2,3}$/

    The above regular expression validates the email. It looks complex, but it is very easy to understand.

    • ^ – Start of the email address.
    • [a-zA-Z0-9] It should contain the alphanumeric characters in the start.
    • + – It should contain at least one alphanumeric character.
    • @ – It must have the ‘@’ character after the alphanumeric characters.
    • [a-zA-Z]+ – After the ‘@’ character, it must contain at least 1 alphanumeric character.
    • \. It must contain a dot after that.
    • [a-zA-Z] After the dot, the email should contain alphabetical characters.
    • {2, 3} After the dot, it should contain only 2 or 3 alphabetical characters. It specifies the length.
    • $ – It represents the end of the pattern.

    Now, the question is whether we can use the search() or replace() method to search or replace text in the string by passing the string as an argument; then what is the need for the regular expression?

    The question is obvious. Let’s understand it via the example below.

    Example

    In the below example, we used the regular expression literal to define the regular expression. The pattern matches the ‘tutorialspoint’ string without comparing the case of characters.

    In the first case, the string search() method searches for the ‘tutorialspoint’ string, which performs the case-sensitive match. So, it returns -1.

    In the second case, we passed the regular expression as an argument of the search() method. It performs the case-insensitive match. So, it returns 11, the index of the required pattern.

    <html><head><title> JavaScript - Regular Expression </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let pattern =/tutorialspoint/i;let str ="Welcome to TuTorialsPoint! It is a good website!";let res = str.search('tutorialspoint');
    
      output.innerHTML +="Searching using the string : "+ res +"&lt;br&gt;";
      res = str.search(pattern);
      output.innerHTML +="Searching using the regular expression : "+ res;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Execute the program to see the desired results.

    Example

    In the example below, we used the replace() method to match the pattern and replace it with the '100' string.

    Here, the pattern matches the pair of digits. The output shows that each number is replaced with '100' in the string. You may also add alphabetical characters in the string.

    <html><head><title> JavaScript - Regular expression </title></head><body><p id ="output"></p><script>let pattern =/\d+/g;// Matches pair of digitslet str ="10, 20, 30, 40, 50";let res = str.replace(pattern,"100");
    
      document.getElementById("output").innerHTML ="String after replacement : "+ res;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Execute the program to see the desired results.

    Example (Email validation)

    In the example below, we used the RegExp() constructor function with a 'new' keyword to create a regular expression. Also, we have passed the pattern in the string format as an argument of the constructor.

    Here, we validate the email using the regular expression. In the first case, email is valid. In the second case, the email doesn't contain the @ character, so the test() method returns false.

    <html><body><p id ="output"></p><script>const pattern =newRegExp('^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{2,3}$');
    
      document.getElementById("output").innerHTML ="[email protected] is valid? : "+ pattern.test('[email protected]')+"&lt;br&gt;"+"abcdgmail.com is valid? : "+ pattern.test('abcdgmail.com');&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    So, the regular expression can be used to find a particular pattern in the text and perform operations like replace.

    RegExp Properties

    Here is a list of the properties associated with RegExp and their description.

    Sr.No.Property & Description
    1constructorSpecifies the function that creates an object's prototype.
    2globalSpecifies if the "g" modifier is set.
    3ignoreCaseSpecifies if the "i" modifier is set.
    4lastIndexThe index at which to start the next match.
    5multilineSpecifies if the "m" modifier is set.
    6sourceThe text of the pattern.

    In the following sections, we will have a few examples to demonstrate the usage of RegExp properties.

    RegExp Methods

    Here is a list of the methods associated with RegExp along with their description.

    Sr.No.Method & Description
    1exec()Executes a search for a match in its string parameter.
    2test()Tests for a match in its string parameter.
    3toSource()Returns an object literal representing the specified object; you can use this value to create a new object.
    4toString()Returns a string representing the specified object.

    In the following sections, we will have a few examples to demonstrate the usage of RegExp methods.

  • Math

    The JavaScript math object provides properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor. All the properties and methods of Math are static and can be called by using Math as an object without creating it.

    Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method’s argument.

    Syntax

    The syntax to call the properties and methods of Math are as follows −

    var pi_val = Math.PI;// Propertyvar sine_val = Math.sin(30);// Method

    Lets learn more about the Math objects properties and method via the examples below.

    JavaScript Math Properties

    Following is the list of properties of Math class in JavaScript −

    Sr.No.Name & Description
    1EEuler’s constant and the base of natural logarithms, approximately 2.718.
    2LN2Natural logarithm of 2, approximately 0.693.
    3LN10Natural logarithm of 10, approximately 2.302.
    4LOG2EBase 2 logarithm of E, approximately 1.442.
    5LOG10EBase 10 logarithm of E, approximately 0.434.
    6PIThe ratio of a circle’s circumference to its diameter is approximately 3.14159.
    7SQRT1_2The square root of 1/2, equivalently, 1 over the square root of 2, is approximately 0.707.
    8SQRT2The square root of 2, approximately 1.414.

    JavaScript Math Methods

    Following is the list of methods of Math class in JavaScript −

    Sr.No.Name & Description
    1abs()Returns the absolute value of a number.
    2acos()Returns the arccosine (in radians) of a number.
    3acosh()Returns the inverse hyperbolic consine of a number.
    4asin()Returns the arcsine (in radians) of a number.
    5asinh()Returns the inverse hyperbolic sine of a number.
    6atan()Returns the arctangent (in radians) of a number.
    7atan2()Returns the arctangent of the quotient of its arguments.
    8atanh()Returns the inverse hyperbolic tangent of a number.
    9cbrt()Finds a cube root of a given number.
    10ceil()Returns the smallest integer greater than or equal to a number.
    11clz32()Returns the number of leading zero in 32-bit binary number.
    12cos()Returns the cosine of a number.
    13cosh()It returns the hyperbolic cosine of a number.
    14exp()Returns EN, where N is the argument, and E is Euler’s constant, the base of the natural logarithm.
    15expm1()Returns EN – 1, where N is the argument, and E is Euler’s constant, the base of the natural logarithm.
    16floor()Returns the largest integer less than or equal to a number.
    17fround()Returns a nearest 32-bit single precision float representation of the number.
    18hypot()Calculates the square root of the sum of squares of arguments.
    19imul()Calculates the 32-bit multiplication of parameters.
    20log()Returns the natural logarithm (base E) of a number.
    21log10()Returns the logarithm (base 10) of a number.
    22log1p()Return the natural logarithm (base E) of 1 + N, where N is an argument.
    23log2()Returns the base 2 logrithm of a number.
    24max()Returns the largest of zero or more numbers.
    25min()Returns the smallest of zero or more numbers.
    26pow()Returns base to the exponent power that is, base exponent.
    27random()Returns a pseudo-random number between 0 and 1.
    28round()Returns the value of a number rounded to the nearest integer.
    29sign()Return -1 or 1 indicating the sign of the number.
    30sin()Returns the sine of a number.
    31sinh()Return the hyperbolic sin.
    32sqrt()Returns the square root of a number.
    33tan()Returns the tangent of a number.
    34tanh()Returns the hyperbolic tangent of the number.
    35trunc()Returns the integer part of the number.

    In the following sections, we will have a few examples to demonstrate the usage of the methods associated with Math.

    Example (Math object Properties)

    The example below demonstrates that each property of the Math object has a constant value.

    Here, we have accessed the values of the E, LN2, and PI properties.

    <html><head><title> JavaScript - Math object's properties </title></head><body><p id ="output"></p><script>
       document.getElementById("output").innerHTML ="Math.E == "+ Math.E+"<br>"+"Math.LN2 == "+ Math.LN2+"<br>"+"Math.LN10 == "+ Math.LN10+"<br>"+"Math.PI == "+ Math.PI+"<br>"+"Math.LOG2E == "+ Math.LOG2E+"<br>"+"Math.LOG10E == "+ Math.LOG10E;</script></body></html>

    Output

    After executing the above program, it returns the values of the provided Math properties.

    Example (Math ceil() method)

    Here, we are computing the JavaScript ceil() method to return the smallest larger integer value than the number passed as an argument. Here, the method returns 6 for the 5.9 value.

    <html><head><title> JavaScript - Math.ceil() method </title></head><body><p id ="output"></p><script>let ans = Math.ceil(5.9);
       document.getElementById("output").innerHTML ="Math.ceil(5.9) = "+ ans;</script></body></html>

    Output

    After executing the above program, it returns the result as 6.

    Example (Math max() method)

    The Math.max() method is used to get the maximum value among the arguments passed as an array.

    Here, we have passed six arguments to the Math.max() object, and the method returns the maximum value from them.

    <html><head><title> JavaScript - Math.max() method </title></head><body><p id ="output"></p><script>let ans = Math.max(100,10,-5,89,201,300);
       document.getElementById("output").innerHTML ="Math.max(100, 10, -5, 89, 201, 300) = "+ ans +"<br>";</script></body></html>

    Output

    After executing the above program, it returns 300 as maximum value.

    Example (Math.cos() method)

    The Math.cos() method returns the cosine value of the number passed as an argument. The cosine value of 0 is 1, which you can see in the output of the example below.

    <html><head><title> JavaScript - Math.cos() method </title></head><body><p id ="output"></p><script>let ans = Math.cos(0);
       document.getElementById("output").innerHTML ="Math.cos(0) = "+ ans;</script></body></html>

    Output

    If we execute the above program, it returns “1” as result.

  • Handler

    The JavaScript Proxy Handlers are used to define custom behavior for fundamental operations performed on objects. By defining handlers, you can override the default behavior of fundamental operations. Following are the common proxy handler methods: apply(), construct(), get(), has(), etc.

    JavaScript Handlers

    Following are the methods of JavaScript Handler −

    Sr.No.Name & Description
    1apply()Allows you call a function with particular arguments and context.
    2construct()Allows you to define custom behavior for fundamental operations on an object.
    3defineproperty()It is used to define new properties or modify existing ones on an object.
    4deleteproperty()It is used as a trap for the delete operator.
    5get()It is a trap for getting a property value.
    6getownpropertydescriptor()It is a trap for the [[GetOwnProperty]] object internal method.
    7getprototypeof()It is a trap for the internal method.
    8has()It is used to hide any property that you want.
    9isextensible()It is used to determine whether the new property can be added or not the target object.
    10ownkeys()It is a trap for the [[OwnPropertyKeys]] object internal method.
    11set()It is a trap for the [[Set]] object internal method.
    12setprototypeof()Allows you set the prototype of a specified object to another object to another object.

  •  DataView

    TheDataViewis an object in JavaScript that allows you to work with the binary data stored in theArrayBuffer. It provides a low-level interface for reading and writing number types in a binary ArrayBuffer.

    The DataView object provides built-in methods for reading and writing 1, 2, and 4-byte signed and unsigned integers, as well as 4 and 8-byte floating-point numbers from the buffer.

    An ArrayBuffer is an array of bytes, usually referred to in other languages as a “byte array”. You cannot directly manipulate the data of an ArrayBuffer like a regular array. Using the ArrayBuffer you can create DataView object, which represents the buffer in a specific format. You can use the DataView object to read from and write to the contents of the buffer.

    Syntax

    Following is the syntax to create a DataView object in JavaScript −

    newDataView(buffer, byteOffset, byteLength)

    Here, the buffer is an existing ArrayBuffer used for storage. The byteOffset parameter (optional) represents the offset in bytes to the first byte in the buffer, and the byteLength parameter (also optional) represents the number of elements in the byte array.

    Example : Creating a DataView Object

    The following example demonstrates how to create a DataView object in JavaScript.

    <html><body><script>const buffer =newArrayBuffer(16);//creating dataview objectconst data_view =newDataView(buffer);
       document.write("The type of data_view is: "+typeof(data_view));</script></body></html>

    Output

    The above program displays the type of the data_view as −

    The type of data_view is: object
    

    JavaScript DataView Properties

    Here is a list of the properties of DataView object −

    • buffer − It returns the ArrayBuffer of SharedArrayBuffer.
    • byteLength − It returns the length (in bytes) of this view.
    • byteOffset − It returns the offset (in bytes) of this view from the start of itsArrayBufferorSharedArrayBuffer.

    JavaScript DataView Methods

    Following are the methods of the JavaScript DataView object −

    Sr.No.Methods & Description
    1getBigInt64()It returns a BigInt from the range of -263 to 263-1, included.
    2getBigUint64()It returns a BigInt from the range of 0 to 264-1, included.
    3getFloat32()It returns a floating point number from -3.4e38 to 3.4e38.
    4getFloat64()It returns any number value.
    5getInt16()It returns an integer from -32768 to 32767, included.
    6getInt32()It returns an integer from the range of -2147483648 to 2147483647, included.
    7getInt8()It returns an integer from the range of -128 to 127, included.
    8getUint16()It returns an integer from the range of 0 to 65535, included.
    9getUint32()It returns an integer from the range of 0 to 4294967295, included.
    10getUint8()It returns an integer from the range of 0 to 255, included.
    11setBigInt64()It returns undefined.
    12setBigUint64()It returns undefined.
    13setFloat32()It returns undefined.
    14setFloat64()It returns undefined.
    15setInt16()It returns undefined.
    16setInt32()It returns undefined.
    17setInt8()It returns undefined.
    18setUint16()It returns undefined.
    19setUint32()It returns undefined.
    20setUint8()It returns undefined.
  • Date

    The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below.

    Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object using either local time or UTC (universal, or GMT) time.

    The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent the date and time till the year 275755.

    Syntax

    You can use any of the following syntaxes to create a Date object using the Date() constructor −

    new Date( )
    new Date(milliseconds)
    new Date(datestring)
    new Date(year,month,date[,hour,minute,second,millisecond ])
    

    Note − Parameters in the brackets are always optional.

    Parameters

    • No Argument − With no arguments, the Date() constructor creates a Date object set to the current date and time.
    • milliseconds − When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the getTime() method. For example, passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70.
    • datestring − When one string argument is passed, it is a string representation of a date in the format accepted by the Date.parse() method.
    • 7 agruments − To use the last form of the constructor shown above. Here is a description of each argument −
      • year − Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998 rather than 98.
      • month − Integer value representing the month, beginning with 0 for January to 11 for December.
      • date − Integer value representing the day of the month.
      • hour − Integer value representing the hour of the day (24-hour scale).
      • minute − Integer value representing the minute segment of a time reading.
      • second − Integer value representing the second segment of a time reading.
      • millisecond − Integer value representing the millisecond segment of a time reading.

    Return Value

    It returns the date string containing day, month, date, year, hours, minutes, seconds, and timezone, as shown below.

    Wed Aug 09 2023 09:24:03 GMT+0530 (India Standard Time)
    

    JavaScript Date Reference

    In JavaScript, the Date object provides methods for creating, manipulating, and formatting dates and times. Here, we have listed all the methods present in Date class −

    JavaScript Date Methods

    Here is a list of the methods used with Date and their description.

    Date Static Methods

    These methods are invoked using the Date object −

    Sr.No.Name & Description
    1Date.parse()Parses a string representation of a date and time and returns the internal millisecond representation of that date.
    2Date.UTC()Returns the millisecond representation of the specified UTC date and time.

    Date Methods

    These methods are invoked using the instance of the Date object −

    Sr.No.Name & Description
    1getDate()Returns the day of the month for the specified date according to local time.
    2getDay()Returns the day of the week for the specified date according to local time.
    3getFullYear()Returns the year of the specified date according to local time.
    4getHours()Returns the hour in the specified date according to local time.
    5getMilliseconds()Returns the milliseconds in the specified date according to local time.
    6getMinutes()Returns the minutes in the specified date according to local time.
    7getMonth()Returns the month in the specified date according to local time.
    8getSeconds()Returns the seconds in the specified date according to local time.
    9getTime()Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.
    10getTimezoneOffset()Returns the time-zone offset in minutes for the current locale.
    11getUTCDate()Returns the day (date) of the month in the specified date according to universal time.
    12getUTCDay()Returns the day of the week in the specified date according to universal time.
    13getUTCFullYear()Returns the year in the specified date according to universal time.
    14getUTCHours()Returns the hours in the specified date according to universal time.
    15getUTCMilliseconds()Returns the milliseconds in the specified date according to universal time.
    16getUTCMinutes()Returns the minutes in the specified date according to universal time.
    17getUTCMonth()Returns the month in the specified date according to universal time.
    18getUTCSeconds()Returns the seconds in the specified date according to universal time.
    19setDate()Sets the day of the month for a specified date according to local time.
    20setFullYear()Sets the full year for a specified date according to local time.
    21setHours()Sets the hours for a specified date according to local time.
    22setMilliseconds()Sets the milliseconds for a specified date according to local time.
    23setMinutes()Sets the minutes for a specified date according to local time.
    24setMonth()Sets the month for a specified date according to local time.
    25setSeconds()Sets the seconds for a specified date according to local time.
    26setTime()Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.
    27setUTCDate()Sets the day of the month for a specified date according to universal time.
    28setUTCFullYear()Sets the full year for a specified date according to universal time.
    29setUTCHours()Sets the hour for a specified date according to universal time.
    30setUTCMilliseconds()Sets the milliseconds for a specified date according to universal time.
    31setUTCMinutes()Sets the minutes for a specified date according to universal time.
    32setUTCMonth()Sets the month for a specified date according to universal time.
    33setUTCSeconds()Sets the seconds for a specified date according to universal time.
    34toDateString()Returns the “date” portion of the Date as a human-readable string.
    35toISOString()Returns date string in the ISO format.
    36toLocaleDateString()Returns the “date” portion of the Date as a string, using the current locale’s conventions.
    37toJSON()Converts a date to a string.
    38toLocaleString()Converts a date to a string, using the current locale’s conventions.
    39toLocaleTimeString()Returns the “time” portion of the Date as a string, using the current locale’s conventions.
    40toString()Returns a string representing the specified Date object.
    41toTimeString()Returns the “time” portion of the Date as a human-readable string.
    42toUTCString()Converts a date to a string, using the universal time convention.
    43valueOf()Returns the primitive value of a Date object.

    Date Object Constructor

    Following is the Date Object Constructor in JavaScript −

    Sr.No.Name & Description
    1Date()Returns today’s date and time.

    Example: Creating JavaScript Date Object

    In the example below, we create a new instance of the date object. In the output, you can observe that it returns the current time.

    <html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
       const date = new Date();
       document.getElementById("output").innerHTML = 
    
      "Today's date is : " + date;
    </script></body></html>

    Output

    If we execute the above program, it returns the current time.

    Example: Setting up custom date

    In the example below, We have passed the custom date string as a parameter of the Date() constructor to create a custom date.

    The Date() constructor returns the standard date string, which you can see in the output.

    <html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
       const date = new Date("August 19, 2024 09:30:54");
       document.getElementById("output").innerHTML = 
    
      "The custom date is : " + date;
    </script></body></html>

    Output

    If we execute the above program, it returns the custom time as provided.

    Example

    In the example below, we have passed milliseconds as an argument of the Date() constructor. If you pass the positive milliseconds as an argument, the object returns the date according to the 1st January 1970 00:00:00 + milliseconds.

    Otherwise, it returns the date according to the 1st January 1970 00:00:00 milliseconds if negative milliseconds passed as an argument.

    <html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
       const output = document.getElementById("output");
       let date = new Date(999999999999);
       output.innerHTML += "The Date after 1st January, 1970 is - " + date + "<br>";
       date = new Date(-999999999999);
       output.innerHTML += "The Date before 1st January, 1970 is - " + date;
    </script></body></html>

    Output

    It returns the date after 1st January, 1970 and before 1st January, 1970 as result.

    Example: Constructing a date from 7 arguments

    In the example below, we have passed the year, month, date, hour, minute, second, and millisecond as a Date() constructor argument. The Date() constructor returns the full date string, which you can see in the output.

    <html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
       const date = new Date(2001, 5, 14, 6, 43, 58, 342);
       document.getElementById("output").innerHTML = 
    
      "The custom date is : " + date;
    </script></body></html>

    Output

    If we execute the above program, it returns the custom time as provided.

    However, you can use the different methods of the Date object to format the date string. Lets look at the example below.

    Example: Formatting a date string

    In the example below, three different methods are used to format the date string.

    The toDateString() method extracts the date only from the date string and removes the time part.

    The toISOString() method converts the date string into the ISO format.

    The toUTCString() method converts the date string into the UTC time format.

    <html><head><title> JavaScript - Formatting the date </title></head><body><p id = "output"></p><script>
       const date = new Date(999999999999);
       document.getElementById("output").innerHTML += 
    
      "The Date after 1st January, 1970 is: " + date.toDateString() + "&lt;br&gt;"+
      "The Date after 1st January, 1970 is: " + date.toISOString() + "&lt;br&gt;"+
      "The Date after 1st January, 1970 is: " + date.toUTCString();
    </script></body></html>

    Output

    It will return the ouptut of the above provided methods, respectively.

  •  Array

    The JavaScript Array object lets you store multiple values in a single variable. An array is used to store a sequential collection of multiple elements of same or different data types. In JavaScript, arrays are dynamic, so you dont need to specify the length of the array while defining the array. The size of a JavaScript array may decrease or increase after its creation.

    Syntax

    Use the following syntax to create an array object in JavaScript −

    const arr =newArray(val1, val2, val3,..., valN)

    Parameters

    • val1, val2, val3, …, valN − It takes multiple values as an argument to initialize an array with them.

    Return value

    It returns an array object.

    Note − When you pass the single numeric argument to the Array() constructor, it defines the array of argument length containing the undefined values. The maximum length allowed for an array is 4,294,967,295.

    You can add multiple comma separated elements inside square brackets to create an array using the array literal −

    const fruits = [ "apple", "orange", "mango" ];
    

    You will use ordinal numbers to access and to set values inside an array as follows.

    fruits[0] is the first element
    fruits[1] is the second element
    fruits[2] is the third element
    

    JavaScript Array Reference

    In JavaScript, the Array object enables storing collection of multiple elements under a single variable name. It provides various methods and properties to perform operations on an array. Here, we have listed the properties and methods of the Array class.

    JavaScript Array Properties

    Here is a list of the properties of the Array object along with their description −

    Sr.No.Name & Description
    1constructorReturns a reference to the array function that created the object.
    2lengthReflects the number of elements in an array.

    JavaScript Array Methods

    Here is a list of the methods of the Array object along with their description −

    Array Static methods

    These methods are invoked using the Array class itself −

    Sr.No.Name & Description
    1from()Creates a shallow copy of the array.
    2isArray()Returns boolean values based on the argument is an array.
    3Of()Creates an array from multiple arguments.

    Array instance methods

    These methods are invoked using the instance of the Array class −

    Sr.No.Name & Description
    1at()To get element from the particular index.
    2concat()Returns a new array comprised of this array joined with another array (s) and/or value(s).
    3copyWithin()To Copy part of the array into the same array at different locations.
    4entries()To get each entry of the array.
    5every()Returns true if every element in this array satisfies the provided testing function.
    6fill()To fill the array with static values.
    7filter()Creates a new array with all of the elements of this array for which the provided filtering function returns true.
    8find()To find an element satisfying the condition.
    9findIndex()To find an index of the element satisfying the condition.
    10findLast()To find an element satisfying the condition from the last.
    11findLastIndex()To find an index of the element satisfying the condition from the last.
    12flat()To flatten the array.
    13flatMap()To get a new array after flattening the array.
    14forEach()Calls a function for each element in the array.
    15Includes()Returns a boolean value if the array contains the specific element.
    16indexOf()Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
    17join()Joins all elements of an array into a string.
    18Keys()Returns an array iterator containing the key for each array element.
    19lastIndexOf()Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
    20map()Creates a new array with the results of calling a provided function on every element in this array.
    21pop()Removes the last element from an array and returns that element.
    22push()Adds one or more elements to the end of an array and returns the new length of the array.
    23reduce()Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
    24reduceRight()Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
    25reverse()Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first.
    26shift()Removes the first element from an array and returns that element.
    27slice()Extracts a section of an array and returns a new array.
    28some()Returns true if at least one element in this array satisfies the provided testing function.
    29toSorted()Sorts the elements of an array in a specific order.
    30sort()Sorts the elements of an array.
    31splice()Adds and/or removes elements from an array.
    32toLocaleString()To convert array elements into the string.
    33toReversed()Returns a reverse of the array.
    34toSpliced()This method returns a new array with some elements removed and/or replaced at a given index.
    35toString()Returns a string representing the array and its elements.
    36unshift()Adds one or more elements to the front of an array and returns the new length of the array.
    37values()To get an iterator containing values of each array index.
    38with()This method returns a new array with the element at the given index replaced with the given value.

    Basic Examples of JavaScript Array Object

    In the following examples, we have demonstrated the usage of basic methods and properties of JavaScript Array Object −

    Example (Creating JavaScript Array Object)

    In the example below, the array strs is initialized with the string values passed as an Array() constructors argument.

    The cars array contains 20 undefined elements. If you pass multiple numeric values, it defines the array containing those elements but needs to be careful with a single numeric argument to the array() constructor.

    <html><head><title> JavaScript -Array() constructor </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");let strs =newArray("Hello","World!","Tutorials Point");
    
      output.innerHTML +="strs ==&gt; "+ strs +"&lt;br&gt;";let cars =newArray(20);
      output.innerHTML +="cars ==&gt; "+ cars +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Execute the above program to see the desired output.

    strs ==> Hello,World!,Tutorials Point
    cars ==> ,,,,,,,,,,,,,,,,,,,
    

    Example (Creating Arrays Using Array Literal)

    In the example below, we have created different arrays. The arr1 array contains the numbers, the arr2 array contains the strings, and the arr3 array contains the boolean values.

    <html><head><title> JavaScript - Array literals </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");const arr1 =[10,40,50,60,80,90];// Array of numbersconst arr2 =["Hello","Hi","How","are","you?"];// Array of stringsconst arr3 =[true,false,true,true];// Array of booleans
    
    
      output.innerHTML +="arr1 ==&gt;  "+ arr1 +"&lt;br&gt;";
      output.innerHTML +="arr2 ==&gt;  "+ arr2 +"&lt;br&gt;";
      output.innerHTML +="arr3 ==&gt;  "+ arr3 +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Execute the above program to see the desired output.

    arr1 ==> 10,40,50,60,80,90
    arr2 ==> Hello,Hi,How,are,you?
    arr3 ==> true,false,true,true
    

    Accessing JavaScript Array Elements

    The array index starts from 0. So, you can access the array element using its index.

    let number = arr[index]

    In the above syntax, arr is an array, and index is a number from where we need to access the array element.

    Example

    In the example below, we have created the array of numbers and accessed the elements from the 0th and 2nd index of the array. The element at the 0th index is 1, and the element at the 2nd index is 6.

    <html><head><title> JavaScript - Accessing array elements </title></head><body><p id ="output"></p><script>const nums =[1,5,6,8,90];
    
      document.getElementById("output").innerHTML ="Element at 0th index is : "+ nums[0]+"&lt;br&gt;"+"Element at 2nd index is : "+ nums[2];&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
    Output
    Element at 0th index is : 1
    Element at 2nd index is : 6
    

    JavaScript Array length

    The length property of the array is used to find the length of the array.

    let len = arr.length;

    Example

    In the example below, the length property returns 5, as array contains 5 elements.

    <html><head><title> JavaScript - Array length </title></head><body><p id ="output"></p><script>const nums =[1,5,6,8,90];
    
      document.getElementById("output").innerHTML ="Array length is : "+ nums.length;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
    Output
    Array length is : 5
    

    Adding a new element to the array

    You can use the push() method to insert the element at the end of the array. Another solution is that you can insert the array at the index equal to the array length.

    arr.push(ele)OR
    arr[arr.length]= ele;

    In the above syntax, ele is a new element to insert into the array. Here, if the array length is N, the array contains elements from 0 to N 1 index. So, we can insert the new element at the Nth index.

    Example

    In the example below, we insert 6 to the array using the push() method. Also, we used the length property to insert the element at the end.

    <html><body><p id ="output"></p><script>const output = document.getElementById("output");const nums =[1,2,3,4,5];
    
      nums.push(6);// Inserting 6 at the end
      output.innerHTML +="Updated array is : "+ nums +"&lt;br&gt;";
      nums[nums.length]=7;// Inserting 7
      output.innerHTML +="Updated array is : "+ nums +"&lt;br&gt;"&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
    Output

    As we can see in the output, provided element has been added.

    Updated array is : 1,2,3,4,5,6
    Updated array is : 1,2,3,4,5,6,7
    

    Updating JavaScript Array Elements

    To update any array element, you can access the array index and change its value.

    arr[index]= ele;

    In the above syntax, index is an index where we need to update a value with the ele value.

    Example

    In the example below, we update the element at the first index in the array.

    <html><body><p id ="output"></p><script>const nums =[1,2,3,4,5];
    
      nums[0]=100;// Updating first element
      document.getElementById("output").innerHTML ="Updated array is : "+ nums;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
    Output
    Updated array is : 100,2,3,4,5
    

    Traversing a JavaScript Array

    You can use the loop to traverse through each array element. However, some built-in methods exist to traverse the array, which we will see in later chapters.

    for(let p =0; p < nums.length; p++){// Access array using the nums[p]}

    Example

    In the below code, the array contains 5 numbers. We used the for loop to traverse the array and print each element.

    However, while and do-while loops can also be used to traverse the array.

    <html><body><p id ="demo"></p><script>const output = document.getElementById("demo");const nums =[1,2,3,4,5];for(let p =0; p < nums.length; p++){
    
         output.innerHTML +="nums["+ p +"] ==&gt; "+ nums[p]+"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    nums[0] ==> 1
    nums[1] ==> 2
    nums[2] ==> 3
    nums[3] ==> 4
    nums[4] ==> 5
    

  • Strings

    The String object in JavaScript lets you work with a series of characters; it wraps JavaScript’s string primitive data type with a number of helper methods.

    As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive.

    The string is a sequence of characters containing 0 or more characters. For example, ‘Hello’ is a string.

    Syntax

    JavaScript strings can be created as objects using the String() constructor or as primitives using string literals.

    Use the following syntax to create a String object −

    var val =newString(value);

    The String parameter, value is a series of characters that has been properly encoded.

    We can create string primitives using string literals and the String() function as follows −

    str1 ='Hello World!';// using single quote
    str2 ="Hello World!";// using double quote
    str3 ='Hello World';// using back ticks
    str4 =String('Hello World!');// using String() function

    JavaScript String Object Properties

    Here is a list of the properties of String object and their description.

    Sr.No.PropertyDescription
    1constructorReturns a reference to the String function that created the object.
    2lengthReturns the length of the string.
    3prototypeThe prototype property allows you to add properties and methods to an object.

    JavaScript String Object Methods

    Here is a list of the methods available in String object along with their description.

    Static Methods

    The static methods are invoked using the ‘String’ class itself.

    Sr.No.PropertyDescription
    1fromCharCode()Converts the sequence of UTF-16 code units into the string.
    2fromCodePoint()Creates a string from the given sequence of ASCII values.

    Instance Methods

    The instance methods are invoked using the instance of the String class.

    Sr.No.MethodDescription
    1at()Returns the character from the specified index.
    2charAt()Returns the character at the specified index.
    3charCodeAt()Returns a number indicating the Unicode value of the character at the given index.
    4codePointAt()Returns a number indicating the Unicode value of the character at the given index.
    5concat()Combines the text of two strings and returns a new string.
    6endsWith()Checks whether the string ends with a specific character or substring.
    7includes()To check whether one string exists in another string.
    8indexOf()Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
    9lastIndexOf()Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
    10localeCompare()Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
    11match()Used to match a regular expression against a string.
    12matchAll()Used to match all occurrences of regular expression patterns in the string.
    13normalize()To get the Unicode normalization of the string.
    14padEnd()To add padding to the current string with different strings at the end.
    15padStart()To add padding to the current string with different strings at the start.
    16raw()Returns a raw string form of a given template literal.
    17repeat()To get a new string containing the N number of copies of the current string.
    18replace()Used to find a match between a regular expression and a string and replace the matched substring with a new one.
    19replaceAll()Used to find a match between a regular expression and a string and replace all the matched substring with a new one.
    20search()Executes the search for a match between a regular expression and a specified string.
    21slice()Extracts a section of a string and returns a new string.
    22split()Splits a String object into an array of strings by separating the string into substrings.
    23substr()Returns the characters in a string beginning at the specified location through the specified number of characters.
    24substring()Returns the characters in a string between two indexes into the string.
    25toLocaleLowerCase()The characters within a string are converted to lowercase while respecting the current locale.
    26toLocaleUpperCase()The characters within a string are converted to the upper case while respecting the current locale.
    27toLowerCase()Returns the calling string value converted to lowercase.
    28toString()Returns a string representing the specified object.
    29toUpperCase()Returns the calling string value converted to uppercase.
    30toWellFormed()Returns a new string that is a copy of this string.
    31trim()It removes white spaces from both ends.
    32trimEnd()It removes white spaces from the start.
    33trimStart()It removes white spaces from the end.
    34valueOf()Returns the primitive value of the specified object.

    String constructor

    Sr.No.ConstructorDescription
    1String()Creates a string object and initializes it with the provided value.

    Examples

    Let’s take understand the JavaScript String object and string primitives with the help of some examples.

    Example: Creating JavaScript String Objects

    In the example below, we used the string() constructor with the ‘new’ keyword to create a string object.

    <html><head><title> JavaScript - String Object </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");const str =newString("Hello World!");
    
      output.innerHTML +="str == "+ str +"&lt;br&gt;";
      output.innerHTML +="typeof str == "+typeof str;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    str == Hello World!
    typeof str == object
    

    Accessing a string

    You can access the string characters using its index. The string index starts from 0.

    Example

    In the example below, we access the character from the 0th and 4th index of the string.

    <html><body><p id ="output"></p><script>const output = document.getElementById("output");let str1 =newString("Welcome!");let str2 ="Welcome!";
    
      output.innerHTML +="0th character is - "+ str1[0]+"&lt;br&gt;";
      output.innerHTML +="4th character is - "+ str2[4]+"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
    Output
    0th character is - W
    4th character is - o
    

    JavaScript string is case-sensitive

    In JavaScript, strings are case-sensitive. It means lowercase and uppercase characters are different.

    Example

    In the example below, char1 contains the uppercase 'S', and char2 contains the lowercase 's' characters. When you compare char1 and char2, it returns false as strings are case-sensitive.

    <html><head><title> JavaScript - String case-sensitivity </title></head><body><p id ="output"><script>let char1 ='S';let char2 ='s'let ans = char1 == char2;
    
      document.getElementById("output").innerHTML +="s == S "+ ans;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
    Output
    s == S false
    

    JavaScript Strings Are Immutable

    In JavaScript, you can't change the characters of the string. However, you can update the whole string.

    Example

    In the example below, we try to update the first character of the string, but it doesn't get updated, which you can see in the output.

    After that, we update the whole string, and you can observe the changes in the string.

    <html><head><title> JavaScript − Immutable String </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let str ="Animal";
    
      str[0]='j';
      output.innerHTML +="The string is: "+ str +"&lt;br&gt;";
      str ="Hi!";
      output.innerHTML +="The updated string is: "+ str;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
    Output
    The string is: Animal
    The updated string is: Hi!
    

    Escape Characters

    You can use the special characters with the string using the backslash (\) characters. Here is the list of special characters.

    Escape characterDescription
    \"Double quote
    \'Single quote
    \\Backslash
    \nNew line
    \tTab
    \bbackspace
    \fForm feed
    \vVerticle tab
    \rCarriage return
    \uXXXXUnicode escape

    Example

    In the example below, we added a single quote between the characters of the str1 string and a backslash between the characters of the str2 string.

    <html><head><title> JavaScript - Escape Characters </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let str1 ="Your\'s welcome!";let str2 ="Backslash \\";
    
      output.innerHTML +="str1 == "+ str1 +"&lt;br&gt;";
      output.innerHTML +="str2 == "+ str2 +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
    Output
    str1 == Your's welcome!
    str2 == Backslash \
    

    String HTML Wrappers

    Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML tag.

    Sr.No.Method & Description
    1anchor()Creates an HTML anchor that is used as a hypertext target.
    2big()Creates a string to be displayed in a big font as if it were in a <big> tag.
    3blink()Creates a string to blink as if it were in a <blink> tag.
    4bold()Creates a string to be displayed as bold as if it were in a <b> tag.
    5fixed()Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag.
    6fontcolor()Causes a string to be displayed in the specified color as if it were in a <font color="color"> tag.
    7fontsize()Causes a string to be displayed in the specified font size as if it were in a <font size="size"> tag.
    8italics()Causes a string to be italic, as if it were in an <i> tag.
    9link()Creates an HTML hypertext link that requests another URL.
    10small()Causes a string to be displayed in a small font, as if it were in a <small> tag.
    11strike()Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.
    12sub()Causes a string to be displayed as a subscript, as if it were in a <sub> tag.
    13sup()Causes a string to be displayed as a superscript, as if it were in a <sup> tag.

    In the following sections, we will have a few examples to demonstrate the usage of String methods.

  • The Boolean Object

    The JavaScript Boolean object represents two values, either “true” or “false”. You can create a boolean object using the Boolean() constructor with a ‘new’ keyword. It takes a value as parameter and returns a boolean object. If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (“”), the object has an initial value of false. In programming, the if-else statement evaluates either the code of the ‘if’ block or the ‘else’ block based on the boolean value of the conditional expression.

    Syntax

    Use the following syntax to create a boolean object.

    const val =newBoolean(value);

    Here value is an expression to convert into a Boolean object.

    It returns an object containing the boolean value.

    You can create a boolean primitive in JavaScript by assigning a boolean value to a variable −

    let bool =true;

    Boolean Properties

    Here is a list of the properties of Boolean object −

    Sr.No.Property & Description
    1constructorReturns a reference to the Boolean function that created the object.
    2prototypeThe prototype property allows you to add properties and methods to an object.

    In the following sections, we will have a few examples to illustrate the properties of Boolean object.

    Boolean Methods

    Here is a list of the methods of Boolean object and their description.

    Sr.No.Method & Description
    1toSource()Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.
    2toString()Returns a string of either “true” or “false” depending upon the value of the object.
    3valueOf()Returns the primitive value of the Boolean object.

    In the following sections, we will have a few examples to demonstrate the usage of the Boolean methods.

    Example: Creating a Boolean Object

    In the example below, we have defined the boolObj variable and stored the boolean object.

    We used the typeof operator to check the type boolObj variable. In the output, you can observe that the type of the boolObj is the object.

    <html><body><p id ="output"></p><script>const boolObj =newBoolean('true');//defining boolean object
    
      document.getElementById("output").innerHTML ="typof boolObj == "+typeof boolObj;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    typof boolObj == object
    

    JavaScript Boolean() Function

    The Boolean() function allows the developer to get the boolean value after evaluating the particular expression passed as a parameter.

    Boolean(Expression);

    Here value is an expression to evaluate and get related boolean values. The Boolean() function returns the true or false based on the expression passed as a parameter.

    Example

    In the example below, We used the Boolean() function and passed different expressions as a parameter. In the output, you can observe the boolean value returned by the Boolean() function.

    <html><body><p id ="output"></p><script>let res =Boolean(100>90);
    
      document.getElementById("output").innerHTML ="Boolean(100 &gt; 90) : "+ res +"&lt;br&gt;";
      res =Boolean(100&lt;90);
      document.getElementById("output").innerHTML ="Boolean(100 &lt; 90) : "+ res +"&lt;br&gt;";
      res =100==90;
      document.getElementById("output").innerHTML ="100 == 90 : "+ res +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Boolean(100 > 90) : true
    Boolean(100 < 90) : false
    100 == 90 : false
    

    JavaScript Falsy Boolean Values

    The Boolean() function returns false for the falsy values. There are six falsy values false, null, undefined, 0 (zero), "" (empty string), NaN.

    Let's look at the example below.

    Example

    In the code below, we have passed all the falsy values as a parameter of the Boolean() function and printed the returned value from the Boolean() function. The Boolean() function returns false for all 7 values.

    <html><body><p id ="demo"></p><script>
    
      document.getElementById("demo").innerHTML ="Boolean(0) : "+Boolean(0)+"&lt;br&gt;"+"Boolean(-0) : "+Boolean(-0)+"&lt;br&gt;"+"Boolean(null) : "+Boolean(null)+"&lt;br&gt;"+"Boolean(undefined) : "+Boolean(undefined)+"&lt;br&gt;"+"Boolean('') : "+Boolean('')+"&lt;br&gt;"+"Boolean(NaN) : "+Boolean(NaN)+"&lt;br&gt;"+"Boolean(false) : "+Boolean(false);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Boolean(0) : false
    Boolean(-0) : false
    Boolean(null) : false
    Boolean(undefined) : false
    Boolean('') : false
    Boolean(NaN) : false
    Boolean(false) : false
    

    All other values are truthy, and the Boolean() function returns true.

    Example

    In the below code, we passed the truthy values as a Boolean() function parameter. The Boolean() function returns true for all truthy values. Even if we have passed the object and function as a Boolean() function parameter, it returns true.

    <html><body><p id ="demo"></p><script>
    
      document.getElementById("demo").innerHTML ="Boolean(1) : "+Boolean(1)+"&lt;br&gt;"+"Boolean(-1) : "+Boolean(-1)+"&lt;br&gt;"+"Boolean('Hello') : "+Boolean('Hello')+"&lt;br&gt;"+"Boolean(true) : "+Boolean(true)+"&lt;br&gt;"+"Boolean(10.99) : "+Boolean(10.99)+"&lt;br&gt;"+"Boolean({name: 'John'}) : "+Boolean({ name:'John'})+"&lt;br&gt;"+"Boolean(() =&gt; {return 1;}) : "+Boolean(()=&gt;{return1;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Boolean(1) : true
    Boolean(-1) : true
    Boolean('Hello') : true
    Boolean(true) : true
    Boolean(10.99) : true
    Boolean({name: 'John'}) : true
    Boolean(() => {return 1;}) : true

  • The Number Object

    The JavaScript Number object represents numerical data as floating-point numbers. It contains different properties (constants) and methods for working on numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class.

    A JavaScript Number object can be defined using the Number constructor. Other types of data such as strings, etc., can be converted to numbers using Number() function.

    A JavaScript number is always stored as a floating-point value (decimal number). JavaScript does not make a distinction between integer values and floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.

    Syntax

    The syntax for creating a number object is as follows −

    const val =newNumber(number);

    In the place of number, if you provide any non-number argument, then the argument cannot be converted into a number, it returns NaN (Not-a-Number).

    We can also create the number primitives by assigning the numeric values to the variables −

    let num1 =24;let num2 =35.65;

    The JavaScript automatically converts the number primitive to the Number objects. So we can use all properties and methods of Number object on number primitives.

    Number Properties

    Here is a list of each property and their description.

    Sr.No.Property & Description
    1EPSILONIt represents the difference between 1 and the smallest floating point number greater than 1.
    2MAX_SAFE_INTEGERIt returns the maximum safe integer value.
    3MAX_VALUEThe largest possible value a number in JavaScript can have 1.7976931348623157E+308.
    4MIN_SAFE_INTEGERIt returns the minimum safe integer value.
    5MIN_VALUEThe smallest possible value a number in JavaScript can have 5E-324.
    6NaNEqual to a value that is not a number.
    7NEGATIVE_INFINITYA value that is less than MIN_VALUE.
    8POSITIVE_INFINITYA value that is greater than MAX_VALUE
    9prototypeA static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document.
    10constructorReturns the function that created this object’s instance. By default this is the Number object.

    Number Methods

    The Number object contains only the default methods (instance and static methods) that are a part of every object’s definition.

    Instance Methods

    Sr.No.Method & Description
    1toExponential()Forces a number to display in exponential notation, even if the number is in the range of standard notation.
    2toFixed()Formats a number with a specific number of digits to the right of the decimal.
    3toLocaleString()Returns a string value version of the current number in a format that may vary according to local settings.
    4toPrecision()Defines how many total digits (including digits to the left and right of the decimal) to display of a number.
    5toString()Returns the string representation of the number’s value.
    6valueOf()Returns the number’s value.

    Static Methods

    Sr.No.Method & Description
    1isNaN()It checks whether the value is a valid number or not.
    2isFinite()It checks whether the number is finite.
    3isInteger()Returns Boolean when the number is an integer value.
    4isSafeInteger()It ensures that the integer is a safe integer.
    5parseFloat()Parses the float value from the string.
    6parseInt()Parses the integer value from the string.

    Examples

    Let’s take a few examples to demonstrate the properties and methods of Number.

    Example: Creating Number Object

    In the example below, the num variable contains the number object having the value 20. In the output, you can see that type of the num variable is an object.

    <html><body><p id ="output"></p><script>const num =newNumber(20);
    
      document.getElementById("output").innerHTML ="num = "+ num +"&lt;br&gt;"+"typeof num : "+typeof num;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num = 20
    typeof num : object
    

    Example: Number Properties

    In the example below, we have displayed some Number properties. You should try to print more properties.

    <html><body><div id="output"></div><script>
    
      document.getElementById("output").innerHTML ="Max Value : "+ Number.MAX_VALUE+"&lt;br&gt;"+"Min Value : "+ Number.MIN_VALUE+"&lt;br&gt;"+"Positive Infinity : "+ Number.POSITIVE_INFINITY+"&lt;br&gt;"+"Negative Infinity : "+ Number.NEGATIVE_INFINITY+"&lt;br&gt;"+"NaN : "+ Number.NaN+"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Max Value : 1.7976931348623157e+308
    Min Value : 5e-324
    Positive Infinity : Infinity
    Negative Infinity : -Infinity
    NaN : NaN
    

    Example: Number Methods

    In the example below, we have used some properties of Number. You can try edit the program to use more methods.

    <html><body><div id="output"></div><script>const num =877.5312
    
      document.getElementById("output").innerHTML ="num.toExponetial() is : "+ num.toExponential()+"&lt;br&gt;"+"num.toFixed() is : "+ num.toFixed()+"&lt;br&gt;"+"num.toPrecision(2) is : "+ num.toPrecision(2)+"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num.toExponetial() is : 8.775312e+2
    num.toFixed() is : 878
    num.toPrecision(2) is : 8.8e+2
    

    JavaScript Number() Function

    The Number() function converts the variable into a number. You can use it to change the data type of the variable.

    let num =Number(val)

    Here val is a variable or value to convert into a number. It doesn't create a number object instead it returns a primitive value.

    Example

    We passed the integer and string value to the Number() function in the example below. In the output, the code prints the numeric values. The type of the num2 variable is a number, as the Number() function returns the primitive number value.

    <html><body><p id ="output"></p><script>let num =Number(10);
    
      document.getElementById("output").innerHTML ="num = "+ num +"&lt;br&gt;"+"typeof num = "+typeof num;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num = 10
    typeof num = number
    

    Example: Converting Numeric Strings to Numbers

    We can use the Number() function to convert numeric strings to numbers. Try the following example −

    <html><body><p id ="output"></p><script>let str ="102.34";let num =Number(str);
    
      document.getElementById("output").innerHTML ="num = "+ num +"&lt;br&gt;"+"typeof num = "+typeof num;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num = 102.34
    typeof num = number
    

    Try the above example with different numbers such as integers, floating point, octal, hexadecimal, etc.

  • Smart Function Parameters

    The concept of smart function parameters in JavaScript is a way to make a function adaptable to different use cases. It allows the function to handle the different kinds of arguments passed to it while invoking it.

    In JavaScript, the function is an important concept for reusing the code. In many situations, we need to ensure the function is flexible to handle different use cases.

    Here are different ways to define a function with smart parameters.

    Default Function Parameters

    In JavaScript, the use of default function parameters is a way to handle the undefined argument values or arguments that haven’t passed to the function during invocation of the function.

    In the below code snippet, we set default values of the parameters, a and b to 100 and 50.

    functiondivision(a = 100, b = 50){// Function body}

    Example

    In the below code, the division() function returns the division of the parameters a and b. The default value of parameter a is 100, and parameter b is 50 whenever you want to pass any argument or pass an undefined argument, parameters with initialized with their default value which you can observe from the values printed in the output.

    <html><head><title> JavaScript - Default parameters </title></head><body><p id ="output"></p><script>functiondivision(a = 100, b = 50){return a / b;}
    
      document.getElementById("output").innerHTML =division(10,2)+"&lt;br&gt;"+division(10,undefined)+"&lt;br&gt;"+division();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    5
    0.2
    2
    

    JavaScript Rest Parameter

    When the number of arguments that need to pass to the function is not fixed, you can use the rest parameters. The JavaScript rest parameters allow us to collect all the reaming (rest) arguments in a single array. The rest parameter is represented with three dots (...) followed by a parameter. Here this parameter works as the array inside the function.

    Syntax

    Follow the below syntax to use the rest parameters in the function declaration.

    functionfuncName(p1, p2, ...args){// Function Body;}

    In the above syntax, 'args' is rest parameter, and all remaining arguments will be stored in the array named args.

    Example

    In the example below, the sum() function returns the sum of all values passed as an argument. We can pass an unknown number of arguments to the sum() function. The function definition will collect all arguments in the 'nums' array. After that, we can traverse the 'nums' array in the function body and calculate the sum of all argument values.

    The sum() function will also handle the 0 arguments also.

    <html><head><title> JavaScript - Rest parameters </title></head><body><p id ="demo"></p><script>functionsum(...nums){let totalSum =0;for(let p =0; p < nums.length; p++){
    
            totalSum += nums[p];}return totalSum;}
      document.getElementById("demo").innerHTML =sum(1,5,8,20,23,45)+"&lt;br&gt;"+sum(10,20,30)+"&lt;br&gt;"+sum()+"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    102
    60
    0
    

    Note You should always use the rest parameter as a last parameter.

    JavaScript Destructuring or Named parameters

    You can pass the single object as a function argument and destructuring the object in the function definition to get only the required values from the object. It is also called the named parameters, as we get parameters based on the named properties of the object.

    Syntax

    Follow the below syntax to use the destructuring parameters with the function.

    functionfuncName({ prop1, prop2, ... }){}

    In the above syntax, prop1 and prop2 are properties of the object passed as an argument of the function funcName.

    Example

    In the example below, we have defined the 'watch' object containing three properties and passed it to the printWatch() function.

    The printWatch() function destructuring the object passed as an argument and takes the 'brand' and 'price' properties as a parameter. In this way, you can ignore the arguments in the function parameter which are not necessary.

    <html><head><title> JavaScript - Parameter Destructuring </title></head><body><p id ="output"></p><script>functionprintWatch({ brand, price }){return"The price of the "+ brand +"\'s watch is "+ price;}const watch ={
    
         brand:"Titan",
         price:10000,
         currency:"INR",}
      document.getElementById("output").innerHTML =printWatch(watch);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The price of the Titan's watch is 10000
    

    The above three concepts give us flexibility to pass the function arguments.