Blog

  •  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.

  • Global Variables

    JavaScript Global Variables

    The global variables in JavaScript are the variables that are defined outside of the function or any particular block. They are accessible from anywhere in JavaScript code. All scripts and functions can access the global variables.

    You can define the global variables using the varlet, or const keyword. The variables defined without using any of the var, let or const keywords automatically becomes global variables.

    JavaScript Global Scope

    The global variables have global scope. So a variable declared outside of a function or block has global scope. The global scope is visible or accessible in all other scope. In client side JavaScript the global scope is the web page in which all the code is being executed. A global variable declared with var keyword belongs to window object.

    var x =10;// Global Scopelet y =20;// Global Scope	const z =30;// Global Scope

    Here the variables, x, y and z are declared outside of any function and block, so they have global scope and are called global variable.

    Global Variable Examples

    Let’s learn more about global variables using the example below.

    Example

    We have defined the x, y, and z global variables in the code below. You can observe that variables can be accessed anywhere inside the code.

    <html><head><title> JavaScript - Global variables </title></head><body><p id ="output"></p><script>var x =10;let y =20;const z =30;
    
      document.getElementById("output").innerHTML ="x = "+ x +"&lt;br&gt;"+"y = "+ y +"&lt;br&gt;"+"z = "+ z;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    x = 10
    y = 20
    z = 30
    

    Example

    In the example below, we have defined the variables a and b using the var and let keywords. You can see that a and b variables can be accessible inside the function or outside the function as they are global variables.

    <html><head><title> JavaScript - Global variables </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");var a =10;let b =20;functiontest(){
    
         output.innerHTML +="a -&gt; Inside the function = "+ a +"&lt;br&gt;";
         output.innerHTML +="b -&gt; Inside the function = "+ b +"&lt;br&gt;";}test();
      output.innerHTML +="a -&gt; Outside the function = "+ a +"&lt;br&gt;";
      output.innerHTML +="b -&gt; Outside the function = "+ b +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a -> Inside the function = 10
    b -> Inside the function = 20
    a -> Outside the function = 10
    b -> Outside the function = 20
    

    Automatic Global Variables

    When you define the variables anywhere inside the code without using the varlet, or const keywords, the variable automatically becomes the global variable and can be accessible anywhere inside the code.

    Example

    In the below code, we have defined the variable 'a' without using any keyword inside the function. Even if we have defined the variable in the function, it becomes global as we haven't used any keyword to define the function.

    The output shows that variable 'a' can be accessible inside or outside the function.

    <html><head><title> JavaScript - Global variables </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functiontest(){
    
      a =90;
            output.innerHTML +="a -&gt; Inside the function = "+ a +"&lt;br&gt;";}test();
        output.innerHTML +="a -&gt; Outside the function = "+ a +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a -> Inside the function = 90
    a -> Outside the function = 90
    

    Defining the global variables inside the function or particular block is not a good practice, as naming conflict can occur in the code.

  • Variable Scope

    JavaScript Variable Scope

    The variable scope in JavaScript determines to the accessibility and visibility of the variable in different part of the code. The scope is the current context of the code execution. This means the variable scope is determined by where it is executed not by where it is declared.

    In JavaScript, the objects and functions are also variables. So the JavaScript variable scope also determines the accessibility or visibility of objects and functions also in the program.

    It is essential to learn the variable scope in JavaScript to write clear code and avoid naming conflicts.

    There are following types of variable scope in JavaScript.

    • Block scope
    • Function scope
    • Local scope
    • Global scope

    Here, we will cover the block, function, and local scope. We will discuss Global scope in detain in JavaScript Global variable chapter.

    JavaScript Block Scope

    Before JavaScript ES6, there were only Global and Function scopes. ES6 introduced the let and const keywords. These keywords provide the Block Scope in JavaScript.

    The JavaScript variables defined using the ‘let‘ and ‘const‘ keyword inside a { } block can be accessible only inside the block in which they are defined.

    {let x =10;// x is accessible here}//x is not accessible here

    A variable defined with var keyword is does not provide block scope.

    {var x =10;// x is accessible here}//x is accessible here also

    Example

    In the example below, we defined the variable ‘a’ inside the ‘if’ block. In the output, you can see that variable ‘a’ is accessible only inside the ‘if’ block. If you try to access the variable ‘a’ outside the ‘if’ block, it will throw a reference error like ‘variable a is not defined’.

    <html><head><title> JavaScript - Block scope </title></head><body><p id ="output"></p><script>if(true){let a =10;
    
         document.getElementById("output").innerHTML ="a = "+ a;}// a can't be accessed here&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a = 10
    

    Example

    In the below code, we have defined the test() function. In the function, we have added a { } block using the curly braces, and inside the { } block, we have defined the variable 'x'. The variable 'x' can't be accessible outside the { } block as it has a block scope.

    <html><head><title> JavaScript - Block scope </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functiontest(){{let x =30;
    
            output.innerHTML ="x = "+ x;}// variable x is not accessible here}test();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    x = 30
    

    Whenever you define the variable using the 'let' or 'const' keyword inside the block, like loop block, if-else block, etc., it can't be accessible outside the block.

    JavaScript Function Scope

    In JavaScript, each function creates a scope. The variables defined inside a function have function scope. The variable defined in a function are accessible from within the same function only. These variable are not accessible from the outside of the function.

    Whenever you define the variable inside the function using the 'var' keyword, the variable can be accessible throughout the function, even if it is defined inside the particular block.

    For example,

    functionfunc(){{var x;// function scopelet y;// Block scopeconst z =20;// Block scope}// x is accessible here, but not y & z}

    Example

    In the example below, we have defined the variable 'x', 'y', and 'z' using the var, let, and const keywords, respectively. The variable 'x' can be accessible inside the function anywhere as it has a function scope, but 'y' and 'z' can only be accessible inside the block in which it is defined.

    <html><head><title> JavaScript - Function scope </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functionfunc(){{var x =30;let y =20;const z =10;
    
            output.innerHTML +="x -&gt; Inside the block = "+ x +"&lt;br&gt;";
            output.innerHTML +="y -&gt; Inside the block = "+ y +"&lt;br&gt;";
            output.innerHTML +="z -&gt; Inside the block = "+ z +"&lt;br&gt;";}
         output.innerHTML +="x -&gt; Outside the block = "+ x +"&lt;br&gt;";// y and z can't be accessible here}func();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    x -> Inside the block = 30
    y -> Inside the block = 20
    z -> Inside the block = 10
    x -> Outside the block = 30
    

    JavaScript Local Scope

    The JavaScript local scope is a combination of the function and block scope. The JavaScript compiler creates a local variable when the function is invoked and deletes it when the function invocation completes.

    In short, variables defined inside the function or block are local to that particular scope. The function parameters are treated as local variables inside the function.

    Example

    In the below code, we have defined the variables inside the function using the var, let, and const keywords. All variables are local to the function. It can't be accessible outside the function.

    Similarly, we can define the looping variables in the local scope.

    <html><head><title> JavaScript - Local scope </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functionfunc(){let first =34;var second =45;const third =60;
    
    
         output.innerHTML +="First -&gt; "+ first +"&lt;br&gt;";
         output.innerHTML +="Second -&gt; "+ second +"&lt;br&gt;";
         output.innerHTML +="Third -&gt; "+ third +"&lt;br&gt;";}func();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    First -> 34
    Second -> 45
    Third -> 60
    

    We notice that the when a variable is defined inside a function, the variable become Local to the function. In this situation, the variable has function scope. When a variable is defined inside a particular block, it becomes local to that block and has block scope.

  • Closures

    What is Closure?

    The concept of closures in JavaScript allows nested functions to access variables defined in the scope of the parent function, even if the execution of the parent function is finished. In short, you can make global variables local or private using the closures.

    A JavaScript closure is basically a combination of the function and its lexical environment. This allows an inner function to access the outer function scope. A closure is created every time a function is created at the function creation time.

    Before you start learning the concept of closures, you need to know the concept of lexical scoping, nested functions, and returning functions.

    Lexical Scoping

    In JavaScript, the lexical scoping is a concept in which the scope of the variables is determined at the code compilation time based on the structure of the code. For example, the nested function can access the variables from the parent function’s scope is called lexical scoping.

    Nested Function

    You can define the function inside the function, and the inner function is called the nested function. Let’s learn it via the example below.

    Example

    In the example below, we have defined the inner() function inside the outer() function. Also, the inner() function is executed inside the outer() function.

    When we execute the outer() function, it also executes the inner() function, a nested function.

    <html><body><p id ="demo"></p><script>const output = document.getElementById("demo");functionouter(){
    
         output.innerHTML +="The outer function is executed! &lt;br&gt;";functioninner(){
            output.innerHTML +="The inner function is executed! &lt;br&gt;";}inner();}outer();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The outer function is executed!
    The inner function is executed!
    

    Returning Function

    When any function returns the function instead of a value or variable, it is called the returning function. Let's look at the example below.

    Example

    In the below code, the outer() function returns the function definition, and we store it in the 'func' variable. After that, we use the 'func' variable to invoke a function stored in that.

    <html><head><title> JavaScript - Returning function</title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functionouter(){
    
         output.innerHTML +="The outer function is executed! &lt;br&gt;";returnfunctioninner(){
            output.innerHTML +="The inner function is executed! &lt;br&gt;";}}const func =outer();func();func();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The outer function is executed!
    The inner function is executed!
    The inner function is executed!
    

    Now, you learned the prerequisite required to learn the closures.

    The definition of JavaScript closure is a bit confusing, but we will learn the closure concept step by step so it will be clear to you.

    A Counter Dilemma

    For example, you create the counter to increment and decrement the variable. As shown below, you need to use the global variable for the counter.

    Example

    In the example below, the 'cnt', a global variable is initialized with 100. Whenever the decrement() function is executed, it decreases the value of the 'cnt' variable by 1.

    <html><body><p id ="demo"></p><script>const output = document.getElementById("demo");var cnt =100;functiondecrement(){
    
         cnt = cnt -1;
         output.innerHTML +="The value of the cnt is: "+ cnt +"&lt;br&gt;";}decrement();decrement();decrement();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the cnt is: 99
    The value of the cnt is: 98
    The value of the cnt is: 97
    

    The above code perfectly works as a decrement counter, but the problem is 'cnt' variable can be accessed in the code anywhere, and any part of the code can change it without executing the decrement() function.

    Here, JavaScript closure comes into the picture.

    Example: JavaScript Closures

    The counter() function returns the decrement() function in the example below. The 'cnt' variable is defined inside the counter() function rather than in the global scope.

    The decrement() function decreases the value of the 'cnt' by 1 and prints in the output.

    The 'func' variable contains the decrement() function expression. Whenever you execute the func(), it calls the decrement() function.

    <html><body><p id ="demo"></p><script>const output = document.getElementById("demo");functioncounter(){let cnt =100;// Works as a global variable for the decrement function.returnfunctiondecrement(){
    
            cnt = cnt -1;
            output.innerHTML +="The value of the cnt is: "+ cnt +"&lt;br&gt;";}}const func =counter();// Returns the decrement() function expressionfunc();func();func();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the cnt is: 99
    The value of the cnt is: 98
    The value of the cnt is: 97
    

    Now, let's remember the definition of closure again. It says that the nested function can access the variables from the outer function's scope even if the execution of the outer function is finished.

    Here, the execution of the counter() function is finished. Still, you can call the decrement() function and access the 'cnt' variable with an updated value.

    Let's look at another example of closure.

    Example

    In the example below, the name() function returns the getFullName() function. The getFullName() function merges the string with the 'name' variable, defined in the outer function's scope.

    <html><head><title> JavaScript - Closure </title></head><body><p id ="demo"></p><script>const output = document.getElementById("demo");functionname(){let name ="John";returnfunctiongetFullName(){return name +" Doe";}}const fullName =name();
    
      output.innerHTML +="The full name is "+fullName();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The full name is John Doe
    

    Benefits of Closure

    Followings are some benefits of the closures in JavaScript −

    • Encapsulation − The closure allows developers to hide or encapsulate the data. It makes data private and inaccessible from the global scope. So, you can expose only the required variables and functions and hide other internal details of the code.
    • Preserving State − The function remembers its lexical scope even if the execution of the outer function is completed. So, developers can maintain the state as we were maintaining the state of the counter in the above examples.
    • Improved memory efficiency − The closure allows you to manage memory efficiently, as you can only retain access to the necessary variables and don't need to define the variables globally.
  • Function bind

    Function bind() Method

    The function bind() method in JavaScript creates a new function with a specified this value and optional arguments, without invoking the original function immediately. It is commonly used to set the context (this) for a function and partially apply arguments. This method is used to bind a particular object to a common function.

    To understand the function bind() method, we should first understand the “this” keyword. In JavaScript (and other programming languages also), this is a special keyword that is used within functions to refer to the object on which the function is invoked. The value of this is depended on how a function is being called and behaviour of this can vary in different contexts.

    Syntax

    The syntax of JavaScript function bind() method is as follows −

    functionToBind.bind(thisValue, arg1, arg2,...);

    Here functionToBind is the original function whose this value and arguments you want to set.

    Parameters

    • thisValue − The value that should be passed as the this parameter when the new function is called.
    • arg1, arg2, … − Optional arguments that will be fixed (partially applied) when the new function is called. These arguments will be prepended to the arguments provided to the new function.

    Lets now understand the Function bind() method with the help of some program examples.

    Without Function bind() Method

    Here we will create a general and common function greet() which simply prints to the console. We create a constant object named person and give it some property i.e. name and we then invoke the function greet by passing it a message “Hello”.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");functiongreet(message){
    
         output.innerHTML = message +', '+this.name;}const person ={ name:'John Doe'};greet('Hello');&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Hello, 
    

    In this example, when the greet function is called directly without using bind, the this value is not explicitly set, leading to an undefined or global object (window in a browser environment) being used as this.

    With Function bind() method

    To overcome the issue in the previous code where it could not fetch any associated name, we make use of the bind function to bind the object person to the function greet.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");// Original functionfunctiongreet(message){
    
         output.innerHTML = message +', '+this.name;}// Object with a 'name' propertyconst person ={ name:'John Doe'};const greetPerson =greet.bind(person,'Hello');greetPerson();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Hello, John Doe
    

    The bind method was able to create a new function greetPerson wherein the this value has been explicitly set to the person object and argument "Hello" is partially applied as in the previous code as well.

    Using bind() ensures that the function is executed in the desired context, preventing issues related to the default behaviour of this in JavaScript functions.

    Example: Binding different objects to same function

    We have created three objects with x and y coordinates of a point, a function printVal is created to print to the console the coordinates of the point. The bind method binds the points to the printVal function and prints the x, y coordinates of each of the points.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");const points1 ={X:100,Y:100}const points2 ={X:200,Y:100}const points3 ={X:350,Y:400}functionprintVal(){ 
    
         output.innerHTML +="Coordinates: "+this.X+","+this.Y+"&lt;br&gt;";}const printFunc2 =printVal.bind(points1);printFunc2();const printFunc3 =printVal.bind(points2);printFunc3();const printFunc4 =printVal.bind(points3);printFunc4();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Coordinates: 100,100
    Coordinates: 200,100
    Coordinates: 350,400
    

    Example: Setting the default values of function parameters

    This is a new scenario wherein we make use of the bind function to predefine the parameter. The multiply() function simply takes 2 inputs and returns their product. By using the bind() method we can set any of the parameters to a default value as needed.

    In the below example, it sets the variable y to 2 and hence upon calling the function by passing just 1 parameter i.e. x as 5 it gets multiplies by the preset 2 and returns the output of 5x2=10.

    <html><body><div id ="output"></div><script>// Original function with parametersfunctionmultiply(x, y){return x * y;}// Using bind to preset the first parameterconst multiplyByTwo =multiply.bind(null,2);// Calling the bound function with only the second parameter
    
      document.getElementById("output").innerHTML=multiplyByTwo(5);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    10
    

    It is important to note that the bind method creates and returns a new function and does not modify the original function. The same function can be reused and yet made to match different use cases without actually modifying.

  • Function apply

    Function apply() Method

    The Function apply() method in JavaScript allows us to invoke a function given a specific value for this and arguments provided as an array.

    The Function call() and apply() methods are very similar, but the main difference between them is function apply() method takes a single array containing all function arguments, and the function call() method takes individual arguments.

    Same as the Function call() method, we can use the apply() method to manipulate the this value and can assign an orbitrary object to this.

    Syntax

    The syntax of the Function apply() method in JavaScriot is as follows −

    func.apply(thisArg,[arg1, arg2,... argN]);

    Parameters

    • thisArg − The ‘thisArg’ grument represents the function context. It is an object whose properties are needed to access the reference function using the ‘this’ keyword.
    • [arg1, arg2, … argN] − They are arguments to pass to the function.

    Return value

    It returns the resultant value returned from the function.

    Examples

    Let’s understand JavaScript Function apply() method with the help of some examples.

    Using apply() method without passing argument

    In the below code, we have defined the test() function printing the message in the output.

    We invoked the function in a standard way and used the apply() method without passing any argument to invoke the function. The output shows that the apply() method gives the same output as a normal function call.

    <html><head><title> JavaScript - Function apply() method </title></head><body><p id ="output1"></p><p id ="output2"></p><script>functiontest(){return"The function test is invoked!";}
    
    document.getElementById("output1").innerHTML =test();
    document.getElementById("output2").innerHTML =test.apply();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The function test is invoked!
    The function test is invoked!
    

    Using apply() method with this argument only

    In the below code, the 'car' object contains three different properties. We passed the car object as a 'thisArg' argument of the apply() method.

    In the showCar() function, we access the properties of the car object using the 'this' keyword and print it into the output.

    <html><head><title> JavaScript - Function apply() method </title></head><body><p id ="output"></p><script>functionshowCar(){return"The price of the "+this.name +" "+this.model +" is: "+this.price;}let car ={
    
      name:"OD",
      model:"Q6",
      price:10000000,}
    document.getElementById("output").innerHTML =showCar.apply(car);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The price of the OD Q6 is: 10000000
    

    Using apply() method with an array of function arguments

    In the example below, we pass the nums object as the first argument of the apply() method. After that, we pass the array of arguments as an apply() method's argument.

    In the printSum() function, we access the object properties using the 'this' keyword and function arguments using the function parameters.

    <html><head><title> JavaScript - Function apply() method </title></head><body><p id ="output"></p><script>functionprintSum(p1, p2){returnthis.num1 +this.num2 + p1 + p2;}const nums ={
    
      num1:5,
      num2:10,}const ans =printSum.apply(nums,[40,32]);
    document.getElementById("output").innerHTML ="Total sum is "+ ans;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Total sum is 87
    

    Using apply() method with built-in functions

    You can also use the apply() method with built-in object methods. We can invoke the built-in object methods (such as Math.max or Math.min) using apply() method.

    In the example below, we use apply() method with built-in JavaScript functions - Math.max and Math.min. We can't directly use these methods for the arrays. We invoke the Math.max and Math.min methods using apply() method. We pass null as thisArg and the array of five integers as the function argument.

    <html><head><title> JavaScript - Function apply() method </title></head><body><p id ="output-max"> Max element in the array:</p><p id ="output-min"> Max element in the array:</p><script>const numbers =[7,6,4,3,9];
    
      document.getElementById("output-max").innerHTML += Math.max.apply(null, numbers);
    
      document.getElementById("output-min").innerHTML += Math.min.apply(null, numbers);</script></body></html>

    Output

    Max element in the array: 9
    Max element in the array:3
    

    Notice if you use Math.max() or Math.min() methods directly for arrays to find max or min element in the array, the result will be NaN.