Author: admin

  • JavaScript – 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;</script></body></html>

    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 > 90) : "+ res +"<br>";
          res =Boolean(100<90);
          document.getElementById("output").innerHTML ="Boolean(100 < 90) : "+ res +"<br>";
          res =100==90;
          document.getElementById("output").innerHTML ="100 == 90 : "+ res +"<br>";</script></body></html>

    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)+"<br>"+"Boolean(-0) : "+Boolean(-0)+"<br>"+"Boolean(null) : "+Boolean(null)+"<br>"+"Boolean(undefined) : "+Boolean(undefined)+"<br>"+"Boolean('') : "+Boolean('')+"<br>"+"Boolean(NaN) : "+Boolean(NaN)+"<br>"+"Boolean(false) : "+Boolean(false);</script></body></html>

    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)+"<br>"+"Boolean(-1) : "+Boolean(-1)+"<br>"+"Boolean('Hello') : "+Boolean('Hello')+"<br>"+"Boolean(true) : "+Boolean(true)+"<br>"+"Boolean(10.99) : "+Boolean(10.99)+"<br>"+"Boolean({name: 'John'}) : "+Boolean({ name:'John'})+"<br>"+"Boolean(() => {return 1;}) : "+Boolean(()=>{return1;});</script></body></html>

    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
  • JavaScript – 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 +"<br>"+"typeof num : "+typeof num;</script></body></html>

    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+"<br>"+"Min Value : "+ Number.MIN_VALUE+"<br>"+"Positive Infinity : "+ Number.POSITIVE_INFINITY+"<br>"+"Negative Infinity : "+ Number.NEGATIVE_INFINITY+"<br>"+"NaN : "+ Number.NaN+"<br>";</script></body></html>

    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()+"<br>"+"num.toFixed() is : "+ num.toFixed()+"<br>"+"num.toPrecision(2) is : "+ num.toPrecision(2)+"<br>";</script></body></html>

    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 +"<br>"+"typeof num = "+typeof num;</script></body></html>

    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 +"<br>"+"typeof num = "+typeof num;</script></body></html>

    Output

    num = 102.34
    typeof num = number
    

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

  • JavaScript – 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)+"<br>"+division(10,undefined)+"<br>"+division();</script></body></html>

    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)+"<br>"+sum(10,20,30)+"<br>"+sum()+"<br>";</script></body></html>

    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);</script></body></html>

    Output

    The price of the Titan's watch is 10000
    

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

  • JavaScript – 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 +"<br>"+"y = "+ y +"<br>"+"z = "+ z;</script></body></html>

    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 -> Inside the function = "+ a +"<br>";
             output.innerHTML +="b -> Inside the function = "+ b +"<br>";}test();
          output.innerHTML +="a -> Outside the function = "+ a +"<br>";
          output.innerHTML +="b -> Outside the function = "+ b +"<br>";</script></body></html>

    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 -> Inside the function = "+ a +"<br>";}test();
            output.innerHTML +="a -> Outside the function = "+ a +"<br>";</script></body></html>

    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.

  • JavaScript – 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</script></body></html>

    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();</script></body></html>

    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 -> Inside the block = "+ x +"<br>";
                output.innerHTML +="y -> Inside the block = "+ y +"<br>";
                output.innerHTML +="z -> Inside the block = "+ z +"<br>";}
             output.innerHTML +="x -> Outside the block = "+ x +"<br>";// y and z can't be accessible here}func();</script></body></html>

    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 -> "+ first +"<br>";
             output.innerHTML +="Second -> "+ second +"<br>";
             output.innerHTML +="Third -> "+ third +"<br>";}func();</script></body></html>

    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.

  • JavaScript – 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! <br>";functioninner(){
                output.innerHTML +="The inner function is executed! <br>";}inner();}outer();</script></body></html>

    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! <br>";returnfunctioninner(){
                output.innerHTML +="The inner function is executed! <br>";}}const func =outer();func();func();</script></body></html>

    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 +"<br>";}decrement();decrement();decrement();</script></body></html>

    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 +"<br>";}}const func =counter();// Returns the decrement() function expressionfunc();func();func();</script></body></html>

    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();</script></body></html>

    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.
  • JavaScript – Function bind() Method

    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');</script></body></html>

    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();</script></body></html>

    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+"<br>";}const printFunc2 =printVal.bind(points1);printFunc2();const printFunc3 =printVal.bind(points2);printFunc3();const printFunc4 =printVal.bind(points3);printFunc4();</script></body></html>

    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 5×2=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);</script></body></html>

    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.

  • JavaScript – Function apply() Method

    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();</script></body></html>

    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);</script></body></html>

    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;</script></body></html>

    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.

  • JavaScript – Function call() Method

    Function call() Method

    The Function call() method allows us to invoke a function given a specific value for this and arguments provided individually. When a normal function is called, the value of this inside the function is the object that the function was accessed on. We can manipulate the this value and can assign an arbitrary object to this by using the call() method. In other word, we can call existing function as a method of an object without attaching the function to the object as a method.

    In JavaScript, every function is a Function object. The Function object provides properties and methods for functions. These properties and methods are defined on Function.prototype and shared by all Function instances. Some of the important methods provided by the Function object are call(), apply() and bind() methods.

    Let us understand the syntax of the Function call() method.

    Syntax

    The syntax of Function call() method in JavaScript is as follows −

    funcName.call(thisArg, arg1, arg2,... argN);

    In the above syntax, the ‘funcName’ is the name of the function to be called.

    Parameters

    • thisArg − It represents the context for the function. It is an object whose properties or methods we need to access using the ‘this’ keyword inside the function.
    • arg1, arg2, … argN − It is N arguments to pass to the function. They are optional arguments.

    By default, the context of the function is a global (window) object. So, the ‘this’ keyword refers to the ‘window’ object.

    Return value

    The call() method returns the value returned from the function.

    Examples

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

    Function call() method without specifying arguments

    In the example below, we have defined the test() function. We have invoked the function using the function name and call() method. In both cases, the function prints the same output. So, when you don’t pass any arguments, the call() method gives the same output as a normal function call.

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

    Output

    The function is invoked!
    The function is invoked!
    

    Function call() method with ‘this’ argument only

    As we discussed above, ‘this’ argument is used to specify the context of the function. Here, we have defined the person1 and person2 objects containing the name and age properties.

    We passed the object as an argument of the call() method. In the printMessage() function, we access the object’s properties, which is passed as a function argument using the ‘this’ keyword.

    In the output, you can observe that it prints the object properties’ value according to the object passed as an argument of the call() method.

    <html><head><title> JavaScript - Function call() method </title></head><body><p id ="output1"></p><p id ="output2"></p><script>functionprintMessage(){return"The age of the "+this.name +" is "+this.age;}const person1 ={
          name:"John Doe",
          age:22,}const person2 ={
          name:"Jane Doe",
          age:40,}
       document.getElementById("output1").innerHTML =printMessage.call(person1);
       document.getElementById("output2").innerHTML =printMessage.call(person2);</script></body></html>

    Output

    The age of the John Doe is 22
    The age of the Jane Doe is 40
    

    Function call() method with multiple arguments

    The example below demonstrates passing multiple arguments to the call() method. The printSum() function returns the sum of function parameters and object properties in the below code.

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

    Output

    Total sum is 87
    

    When you pass the ‘this’ keyword as the first argument of the call() method instead of an object, it specifies the function itself as a function context.

    Using a method of different object

    Using Function call() method, an object can use a method that is defined in other object. In the below example, we create three objects student, student1 and student2. We define a method getAge() of the object student. This getAge() method is used by the other two objects (student1 and student2) to access the age. The objects student1 and student2 are passed as arguments to the call() method.

    <html><head><title> JavaScript - Function call() method </title></head><body><p id ="output1"></p><p id ="output2"></p><script>const student ={getAge:function(){returnthis.age;}}const student1 ={
          name:"John",
          age:22}const student2 ={
          name:"Doe",
          age:18}
      
       document.getElementById("output1").innerHTML =student.getAge.call(student1);
       document.getElementById("output2").innerHTML =student.getAge.call(student2);</script></body></html>

    The Function call() and apply() methods are the same but with minor difference as call() method accepts a list of arguments but the apply() method accepts an array of arguments. Let’s understand the Function apply() method in detail in the next chapter this tutorial.

  • JavaScript – Function Invocation

    Function Invocation

    The function invocation in JavaScript is the process of executing a function. A JavaScript function can be invoked using the function name followed by a pair of parentheses. When you write a function code in JavaScript, it defines the function with expressions and statements. Now, to evaluate these expressions, it is necessary to invoke the function. The function invocation is the synonym of the function call or function execution.

    A JavaScript function can be defined using function declaration or function expression. The code inside the curly braces in the function definition are not executed when function is defined. To execute the code, we need to invoke the function.

    The call a function and invoke a function are two interchangeable terms are commonly used. But we can invoke a function without calling it. For example, self-invoking functions are invoked without calling them.

    Syntax

    The syntax of function invocation in JavaScript is as follows

    functionName()ORfunctionName(arg1, arg2,... argN);

    Here ‘functionName’ is the function to be invoked. We can pass as many arguments as the number of parameters listed in function definition.

    Example

    In the example below, we have defined the merge() function taking two parameters. After that, we used the function name to invoke the function by passing the arguments.

    <html><body><p id ="output"></p><script>functionmerge(str1, str2){return str1 + str2;}
          document.getElementById("output").innerHTML =merge("Hello"," World!");</script></body></html>

    Output

    Hello World!
    

    Invocation of Function Constructor

    When you invoke a function with the ‘new’ keyword, it works as a function constructor. The function constructor is used to create an object from the function definition.

    Syntax

    Following is the syntax to invoke the function as a constructor.

    const varName =newfuncName(arguments);

    In the above syntax, we invoked the function with a ‘new’ keyword and passed the arguments.

    Example

    In the example below, we use the function as an object template. Here, the ‘this’ keyword represents the function object, and we use it to initialize the variables.

    After that, we invoke the function car with the ‘new’ keyword to create an object using the function template.

    <html><body><p id ="output"> The ODCar object is:</p><script>functionCar(name, model, year){this.name = name;this.model = model;this.year = year;}const ODCar =newCar("OD","Q6",2020);
          document.getElementById("output").innerHTML +=JSON.stringify(ODCar);</script></body></html>

    Output

    The ODCar object is: {"name":"OD","model":"Q6","year":2020}
    

    Object Method Invocation

    We haven’t covered JavaScript objects yet in this tutorial but we will cover it in upcoming chapters. Here, let’s learn the object method invocation in short.

    The JavaScript object can also contain the function, and it is called the method.

    Syntax

    Following is the syntax below to invoke the JavaScript object method.

    obj.func();

    In the above syntax, the ‘obj’ is an object containing the method, and ‘func’ is a method name to execute.

    Example

    In the example below, we have defined the ‘obj’ object containing the ‘name’ property and the ‘getAge()’ method.

    Outside the object, we access the method by the object reference and invoke the method. In the output, the method prints 10.

    <html><body><p id ="output">The age of John is:</p><script>const obj ={
             name:"John",getAge:()=>{return10;}}
          document.getElementById("output").innerHTML +=  obj.getAge();</script></body></html>

    Output

    The age of John is: 10
    

    Self-Invoking Functions

    The self-invoking functions in JavaScript are executed just after they are defined. There is no need to call these types of function to invoke them. The self-invoking functions are always defined using anonymous function expression. These types of functions are also called immediately invoked function expressions (IIFEs). To invoke these function, we wrap the function expression within a grouping operator (parentheses) and then add a pair of parentheses.

    Example

    Try the following example. In this example, we define a function to show a “Hello world” message in alert box.

    <html><head><script>(function(){alert("Hello World")})();</script></head><body></body></html>

    Other methods to invoke the function

    JavaScript contains two special methods to invoke the function differently. Here, we have explained each method in the table below.

    MethodFunction invocationArguments
    Call()Immediate invocationSeparate arguments
    Apply()Immediate invocationArray of arguments

    The difference between the call() and apply() method is how it takes the function arguments. We will learn each of the above methods with examples in the next chapters one by one.