Trending February 2024 # How Iife Work In Javascript With Programming Examples # Suggested March 2024 # Top 11 Popular

You are reading the article How Iife Work In Javascript With Programming Examples updated in February 2024 on the website Bellydancehcm.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 How Iife Work In Javascript With Programming Examples

Introduction to JavaScript IIFE

The JavaScript Immediately Invoked Function Expression (IIFE) is a function which helps in providing a method that defines a sequence of a particular context. Once a variable is defined inside a function it is not possible to access it outside the function where it is defined. The functions which are created in JavaScript have named functions, anonymous functions and by making use of IIFE we can execute these as soon as they are mounted. This functionality makes them IIFE. Let us have a look in detail at how this function works

Start Your Free Software Development Course

Syntax

Below is the syntax for JavaScript IIFE:

(function () { })();

Explanation: The primary use of this function is that the variables should be accessible only within the scope of the defined function that is there.

The declaration should begin with the keyword function(). In the function definition, you can define any statements which are to be performed. This function should be hoisted. A hoisted function is always placed at the start of the program or functional scope when the JavaScript code is being executed. You can also use the below syntax:

The parentheses let JavaScript know that there is a function expression and the last pair of parentheses will invoke the function.

How does IIFE work in JavaScript?

Let us see how does it work:

Code: 

(function () { var userName = "Snehal"; function display(name) { alert("MyCode2.js: " + name); } display(userName); })();

The above code is an example of IIFE. The IIFE helps in including all functions and variables with the same name and they can be accessed globally. Here we define a function and in its definition,  we are creating a variable username. We immediately write another function that will display this username. This is the display function where we are sending the username as a parameter. We have created an alert for the same where we display the code script name and then by making use of IIFE we have simply called the function at the end. In this way we have called two functions one after the other. We have rather immediately invoked. Let us check a few examples to understand better.

Examples to Implement JavaScript IIFE

Below are the examples mentioned:

Example #1

Code:

// anonymous function #1 var isLucky = function() { var iife = Math.round(Math.random() * 100); return “You are checking Immediate Invoking Function Expression!”; } else { return “We are not in IIFE, better luck next time!”; } }; var me = isLucky(); alert(me); window.setTimeout(function() { alert(“JavaScript and EduCBA is awesome!!!”); }, 2000);

At first, the result is displayed as per the condition. When we again run the program the result is the else part. Once the time outspan is over then the output of the above program will be as below:

Explanation: The above script helps us understand the IIFE in Javascript better. Here we have created a function isLucky where we are rounding off a random number and then multiplying it by 100. The random number is being generated by the Math.random() function. After this number is generated then we check if the number is less or greater than 50. If the number is greater than 50 then the message will be displayed as: “You are checking Immediate Invoking Function Expression!”. Else the corresponding message for it will be displayed. Once this function is done we are calling it and storing it in a variable called me. Whatever message is returned it will be displayed in the form is an alert window in the browser. Just after this, another function is invoked. This function will time out and display another alert will be displayed. Below will be the output when we run for the first time.

Example #2

Let us take another example of IIFE. We can use this function without if else block as well.

(function() { var create = “I have learnt what is Immediate Invoking Function Expression from EduCBA successfully !!!”; alert(create); })(); window.setTimeout(function() { alert(“JavaScript and Edu is awesome!!!”); }, 2000);

Output:

The message is displayed as soon as the above code is run. Once the timeout happens below alert window turns up automatically.

Explanation: The above code is an example of a classic and simple IIFE. We create a function and immediately call it. We have not named this function with any name. We have just created a variable create. This function then uses this to display this message as the sun as the function is invoked. As per the syntax, we are bound to use the parenthesis correctly. If there are any misses in the parenthesis then the code will not give the desired result. We can easily invoke the function as soon as the function is declared and defined. We will just pass empty parentheses in order to invoke the function that we have created. We send the variable to create as a parameter to an alert. When the program is run the alert will be called and whatever is present in the created variable will be displayed in the alert window. We also created a similar function as in Example 1. This will work in a similar way. It will wait for timeout and will again display an alert window with the specified message. The timeout time we have mentioned here is 2 milliseconds. Once this is over the message will be displayed automatically. Let us see the output of the above code.

Conclusion

The Immediate Invoking Function Expression is an easy way of calling a function just after it is created. It helps in keeping the local variables local or global variables as global whenever required. It is fast and hence very efficient to use. It fulfills the programmer’s purpose of keeping the variables intact. IIFE can be used with a name or without any name. They can also be used with unary operators when needed.

Recommended Articles

This is a guide to JavaScript IIFE. Here we discuss an introduction to JavaScript IIFE, syntax, how does it work and programming examples. You can also go through our other related articles to learn more –

You're reading How Iife Work In Javascript With Programming Examples

How Linux Zcat Command Works With Programming Examples

Introduction to Linux Zcat

In Linux Zcat, Linux ecosystem, we are able to compress the files with the help of gzip or gunzip. But when we need to check the compress file content without uncompressing the compressed files then we are using the zcat command.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Note: The zcat utility is only working with the gzip or gunzip compress files. If it will work with the tar compression technique, it will not work. It will provide the garbage value. The Zcat command utility was written by Miloslav Trmac.

Syntax

Syntax of Zcat command:

zcat [ option ] [ name ]

zcat: We can use the zcat keyword in the syntax or command. It will take the two-argument as an option and file name. Provide the end result to display the compress file content without uncompressing the file.

option: We can provide the different flags as options that are compatible with the zcat command example “-fhLV”.

How does Linux Zcat Command work?

Basically, the zcat is a command-line utility. It is used to display the compressed file content without uncompressing the compressed file. It will swell the compressed file into standard output and allowing to end-user to look at the contents available in it. A few more updates, the zcat is compatible to run the gunzip –c command.

The zcat command is majorly working with two components i.e. option and the compressed file name. When any end-user or client will trigger the zcat command? The zcat command will accept the input as an option and compressed file as standard input and display the compress file content as standard output.

Examples to Implement Linux Zcat Command

Below are examples mentioned:

1. Zcat Command

It is a very simple and common way to use the zcat command in a Linux environment. It will print the compress file content which is provided to the zcat command.

Code:

zcat data.txt.gz

Output:

Explanation: We are creating a few sample files in the data directory. As per screenshot 1 (a), we have created the chúng tôi file and compress it with the help of gzip. With the help of the zcat command, we are able to read the compressed file content (refer screenshot 1 (b)). In the same file contented, we are not able to read with normal cat command (refer screenshot 1 (c)).

2. Zcat Command: Multiple Compressed File View

In zcat command, we are having the functionality to view the multiple compressed files at the same time in the same command.

Code:

zcat chúng tôi data1.txt.gz

Output:

Explanation: As per the above zcat command, we are able to read the number of compress file at the same time. From the data directory, we are reading the two compress files i.e. chúng tôi data1.txt.gz at the same time.

3. Zcat Command: Force File View

In the zcat command, we are having the functionality to display the file content whether the file is compressed or not. To print the file contented forcefully, we need to use the “-f” option with the zcat command.

zcat -f data.txt.gz

Output:

Explanation: As per the below screenshot, the zcat file is compatible with gzip files. But if we need to read the content of the normal file, it will not possible. Hence we need to use the “-f” option to read the file forcefully with the zcat command.

4. Zcat Command: With More Command

When do we need to display the huge compress file data? It would be more difficult to display the data in a single window. We can use the more command to view the zcat data.

Note: We can use the more command functionality with the zcat command.

Code:

Output:

Explanation: If we need to view the huge amount of log data, it would be more difficult to view or print in a single screen. We can use the more command functionality to read the huge amount of compressed log files.

Note: we are using pipe functionality to read the zcat data in more command.

5. Zcat Command: With Less Command

In the zcat command, we are having the functionality to display the huge amount of data with less command utility.

Note: We can use the more command functionality with the zcat command.

Code:

Output:

Explanation: As per the more command, we can read the huge compressed file. Similarly, we can use the less command functionality to read the huge amount of compressed log files.

Note: we are using pipe functionality to read the zcat data in less command.

6. Zcat command: Print Compression Information

With the help of the zcat command, we are able to get the compression information of the file. To print the compression information, we need to use the “-l” option with the zcat command.

Code:

zcat -l log.txt.gz

Output:

Explanation: As per the above command, we are able to find the compression status of the compressed file. We are using one of the log files i.e. chúng tôi The compression information will display the compressed, uncompressed, ratio information with the compressed file name.

7. Zcat Command – suppress Warning

Some times while printing any compress data, the lots of warning come. To avoid this condition, we need to use the “-q” option with the zcat command.

Code:

zcat -q data.txt.gz

Output:

Explanation: When we are reading the compress file content, sometimes the number of warning comes due to different issues. As per the below screenshot, we can avoid the warring while reading the compressed file contented. We can use the “-q” option with the zcat command to avoid the warning.

Conclusion

We have seen the uncut concept of “Linux Zcat Command” with the proper example, explanation and command with different outputs. The zcat command is compatible with the gunzip –c command. It will really helpful to print the compress file content without uncompressing the actual file.

Recommended Articles

We hope that this EDUCBA information on “Linux Zcat” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Does Prolog Programming Work?

Introduction to Prolog Programming

Web development, programming languages, Software testing & others

Why we need Prolog programming?

It is a first-order logic programming language.

The programmer does not require complex algorithms and coding.

this programming is easier for Pattern matching and searching data than in other programming languages.

It works with abstract models and deals with objects.

This programming is the prolog is an easy, simple, and formula-based programming language.

This programming separates logics and controls of the data.

The prologs are based on the symbolic and computation for manipulation.

It is based on numerical data for pattern matching.

This programming language is a relational database for maintaining a memory management system.

It provides small syntaxes and small coding patterns.

It is based on the searching tree of determination and possibility.

The prolog supports a lot of the extensions like socket interface, global variables, and operating system interfaces.

It supports the native code compiler and becomes a stand-alone programming language.

The prolog supports constraints like arithmetic, Boolean, symbolic, etc.

This programming provides an efficient constraint solver and makes compatibility with integrals and variables.

The prolog supports compiled predicates and consulted predicates in the compiler.

This programming supports powerful interfaces between the prolog and C programming language.

How does Prolog programming works?

The following shows the prologue programming’s working environment.

Download or save the software in the required path.

The downloaded software saves in the exe file format to install the software.

The working procedure of the prolog programming shows below.

The warren abstract machine (WAM) is working as a compiler for prolog language.

The compiler file is converted into independent low-level machine language.

The resulting file again translates into the target machine.

This working procedure makes a stand-alone programming language.

Advanced prolog programming requires constraints for problem-solving.

You choose arithmetic constraints, Boolean constraints, and symbolic constraints, and so on.

The basic procedure of this programming is shown below.

The prolog software creates a file with the chúng tôi format. The “*.pl” is an extension of the prolog file.

Write the syntax of the prolog programming language. You can use many entities in single relation.

It shows the basic syntax below.

Format –

relation (objects or data). relation (data1, data2, data).

The prolog programming example shows the basic output.

Example-

Example-

Advantages

The Prolog programming software is easy to build and install the software.

This programming language does not need lengthy syntax and coding.

This compiler is working fast and hustle-free.

It has powerful interfaces between the prolog and C programming language.

The user of prolog programmer creates their constraints with customization.

The prolog programmer provides several extensions.

This programming language provides high-level and categorized constraints.

The prolog supports easier pattern matching and searching data features.

The prolog language does not use complex algorithms and coding.

This language maintains and operates data lists with easy coding.

The several algorithm and code for input and output procedures are not easy.

The LISP language dominates and overcomes input and output features.

It does not support graphics features. If you need graphics, then you must use turbo prolog.

The prolog order affects the efficiency of the programming language.

This language does not support the “OR” logical conditions. This language does not support multiple true statements.

This language does not support the “NOT” logical condition. This language does not support negative statements.

The prolog is first-order logic language. This language does not allow second-order logic directly.

Uses

It is mostly usable in artificial intelligence technology.

This programming language uses for pattern matching using the parse tree feature.

The prolog is used in the computation schematics.

This programming uses in the problem-solving and understanding of natural language.

This language uses planning and designing of the robot.

The prolog is used in the automation system and theorem proving with a variety of constraints.

The prolog is a useful language in machine learning and the graphical user interface.

This is used for expert system and term rewriting using arithmetic and symbolic constraints.

Conclusion

It is simple planning and problem-solving programming language.

This language is used for AI, machine learning, and computational technology.

The prolog works in large-size applications in small and easy coding.

Recommended Articles

We hope that this EDUCBA information on “Prolog Programming” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Javascript Bind() Method With Practical Examples

In JavaScript, the bind() method is an effective way to create new functions with a bound ‘this’ value and, if needed, pre-set arguments.

Section 1: Setting the ‘this’ value for a function

One of the primary uses of the bind() method is to set the ‘this’ value of a function to a specific object without altering the original function. This is particularly useful when you want a function to work with a specific object but don’t want to modify the function itself.

Consider the following example:

const studentA = { name: 'Sophia', score: 85, result() { console.log(`${this.name}'s score is ${this.score}.`); } }; const studentB = { name: 'Lucas', score: 92 }; const boundResult = studentA.result.bind(studentB); boundResult();

In this example, we have a ‘studentA’ object with a ‘result()’ method that uses the ‘this’ keyword to refer to the object. We also have another object, ‘studentB’, with its own ‘name’ and ‘score’ properties. By calling the bind() method on ‘studentA.result()’, we pass in ‘studentB’ as the ‘this’ value, effectively binding it to ‘studentB’. When ‘boundResult()’ is called, the ‘this’ keyword in the function will refer to ‘studentB’ rather than ‘studentA’.

Section 2: Creating a function with pre-set arguments

The bind() method also allows you to create a new function with pre-set arguments. This can be useful when you need a function to always use specific arguments without altering the original function.

Let’s take a look at the example below:

function multiply(x, y) { return x * y; } const multiplyByFive = multiply.bind(null, 5); console.log(multiplyByFive(3)); console.log(multiplyByFive(4));

In this example, we have a ‘multiply()’ function that takes two arguments and returns their product. We then create a new function, ‘multiplyByFive()’, by calling bind() on ‘multiply()’. We pass ‘null’ as the ‘this’ value and ‘5’ as the first argument. This ensures that when ‘multiplyByFive()’ is called, it will always multiply the passed argument by 5, without needing to modify the original ‘multiply()’ function.

Section 3: Using bind() with event handlers

The bind() method can also be useful when working with event handlers, as it allows you to set the ‘this’ value within the handler function. This can be particularly helpful when using object methods as event handlers.

Consider the following example:

const buttonController = { button: document.getElementById('myButton'), console.log(this.message); }, init() { } }; buttonController.init(); Section 4: Partial application with bind()

The bind() method allows for partial application of arguments, enabling you to fix a certain number of arguments for a function, while leaving others to be passed in later. This can be helpful for creating more specialized versions of general functions.

Here’s an example:

function product(a, b, c) { return a * b * c; } const doubleProduct = product.bind(null, 2); console.log(doubleProduct(3, 4)); console.log(doubleProduct(5, 6));

In this example, we have a ‘product()’ function that takes three arguments and returns their product. We then create a new function, ‘doubleProduct()’, by calling bind() on ‘product()’ and fixing the first argument to ‘2’. This results in a new function that takes two arguments and calculates the product, always doubling the result.

How Does Risk Parity Work With Examples?

What is Risk Parity?

Start Your Free Investment Banking Course

Download Corporate Valuation, Investment Banking, Accounting, CFA Calculator & others

Explanation How Does Risk Parity Work?

The risk parity strategy uses leverage to diversify and reduce the equity risk of an investment portfolio while maintaining the returns at the long-term target level. Using leverage allows investment in lower-risk assets such that the overall portfolio’s return is similar to equity-like returns. The portfolio leverage (by borrowing) with a higher allocation to lower-risk assets delivers a higher return than a direct investment in higher-risk assets with a similar risk level. So, higher allocation goes into bonds compared to equities, as stocks are typically riskier than bonds. In this way, it ensures that risk contribution from both asset classes is equal. Next, it is essential to ensure that the cost of borrowing is sufficiently low such that the net return of the leveraged portfolio (= portfolio return -borrowing cost) exceeds the expected return of the traditional allocation. It is a compelling strategy for investors with easy access to borrowed funds.

Examples of Risk Parity

The following are examples of some of the best risk parity funds available in the world:

AQR Risk Parity II HV Fund (QRHIX): The fund was started on 5th November 2012, and as of 13th November 2023, its total assets under management (AuM) stand at ~$23 million. The fund allocation is such that ~37% of the AuM is invested in equities, ~26% in nominal interest rate bonds, and ~37% in inflation-linked bonds, which results in an equity and bond mix of 1:1.7. During the last three years/ 5 years/ since inception, the fund has generated return of 4.79%/ 6.70%/ 4.34%, which indicates that its performance has been slightly fluctuating with realized volatility of 12.5% since inception. The fund’s management fee and adjusted expenses ratio are 0.80% and 1.03%, respectively.

Horizons Resolve Adaptive Asset Allocation ETF (HRAA): The fund was started on 21st July 2024 as Horizons Global Risk Parity ETF (HRA), Canada’s first Global risk parity fund. On 30th July 2023, the fund was reorganized into Horizons Resolve Adaptive Asset Allocation ETF, and as of 20th September 2023, its total assets under management (AuM) stand at ~$70 million. The fund allocation is such that ~6% of the AuM is invested in equities and ~53% in bonds. Before reorganization, the fund generated returns of 1.35% in the last three years with a volatility of 5.75%. The fund’s management fee is 0.85% plus 15% of the amount by which the fund outperforms the high water mark.

Source: Horizon ETFs, Yahoo Finance

Who Invented Risk Parity?

It was Bridgewater Associates that first launched a risk parity fund by the name All Weather asset allocation strategy in the year 1996. Although the risk parity fund was introduced to the market by Bridgewater Associates, the term was not coined until 2005, when Edward Qian of PanAgora Asset Management first used this term in his authored white paper. In 2008, Andrew Zaytsevof Alan Biller and Associates named Risk Parity one of his investment categories. Soon, the entire asset management industry adopted the term.

Diagram

Typically, any risky asset generates higher returns than plain cash. So, it makes sense to borrow and purchase risky assets (a.k.a. financial leverage) to earn higher portfolio returns. This strategy results in negative allocation to cash while the allocation to risky assets (mix of bonds and stocks) exceeds 100%. In the above chart, it can be seen that as compared to the traditional portfolio allocation of 60% to equities and 40% to bonds in the 3-asset risk parity portfolio, the portfolio allocation to equities has been halved and that of bonds has been increased three-fold resulting in negative allocation to cash (indicating borrowed fund). In this way, the portfolio risk contribution of equities is brought down while increasing that of bonds to ensure equal risk contribution of both the asset classes (considering zero risk for cash).

Criticisms Conclusion

So, it can be seen that the risk parity approach is an essential portfolio management strategy wherein the capital allocation is done in such a way that the risk contribution of each asset class is equal. The risk parity approach is believed to result in a higher Sharpe ratio, i.e., higher risk-adjusted return.

Recommended Articles

This is a guide to Risk Parity. Here we also discuss the introduction and how does it work? Along with examples. You may also have a look at the following articles to learn more –

How Does Powershell Wget Work With Examples?

Introduction to PowerShell wget

The PowerShell Wget, which is an alias for the Invoke-WebRequest in PowerShell, is a non-interactive utility that sends the request to the HTTP or HTTPS web page or the web services and parses the response and returns the collection of the links, images, and HTML elements and it also helps to download the files from the webpage, post or delete or modify the data on the website with the forms, checks the status of the websites, etc.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax

[-UseBasicParsing] [-AllowUnencryptedAuthentication] [-UseDefaultCredentials] [-SkipCertificateCheck] [-DisableKeepAlive] [-ProxyUseDefaultCredentials] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [-PreserveAuthorizationOnRedirect] [-SkipHeaderValidation]

If we check the Invoke-Webrequest syntax, PowerShell 7.1 version supports the 4 sets for this command.

The other 3 sets include the below extra parameters.

-NoProxy

-CustomMethod

This means that you can not combine the above 2 parameters with the First set of certain parameters. For example, you can’t use the -Proxy and -NoProxy parameter together but set support the -NoProxy and -CustomMethod both together.

How does PowerShell wget works?

The Invoke-WebRequest was introduced in PowerShell 3.0 onwards and has become very popular for interacting with the webpage.

Wget is the name of the alias of the Invoke-WebRequest command in the PowerShell .Net framework version (v1.0 to 5.1).

Get-Alias -Name wget

Output:

While in the Powershell Core version (6.0 onwards), the wget alias name is replaced with the iwr command.

Get-Alias -Definition Invoke-Webrequest

Output:

Wget and iwr also have the same supported utility called curl, which is a Unix command but introduced as an alias of the Invoke-Webequest command.

Get-Alias -Definition Invoke-WebRequest

Output:

When you parse the web page using the Wget command, a few properties and methods are associated with this command. Let see what those members are.

Output:

There are various properties like Headers, Images, links, which you can retrieve directly through the wget command.

In the examples below, we will see how various parameters are supported with the wget command.

Examples of PowerShell wget

Given below are the examples of PowerShell wget:

Example #1

Using the wget command to check the website status

We can check the status of the webpage using the wget (Invoke-WebRequest) command.

wget -Uri $uri

Output:

StatusCode 200 means that the site is OK. You can check the various status codes on the wiki page link below.

Example #2

Exception handling in the Wget command.

Programming language uses the try/catch methods for exception handling. In this example, we will handle the non-existence website exception using the same method in PowerShell.

}

Output:

To catch the status code of the message.

}

Output:

Example #3

Downloading a file with the Wget command.

We can download files directly from the internet using the wget command as shown below. We are downloading a Web-based net framework from the MS website in this example, as shown below.

wget -Uri $uri -OutFile “C:tempnetframework.exe” -Verbose

Output:

The above command will keep the download file in the C:temp folder with the chúng tôi name.

Example #4

Downloading Images, links from the webpage.

With the wget widget, we can access the images or links from the website directly to the local system, as shown below.

$response = wget -Uri $uri

With the above command, the response from the webpage will be stored in the $Response variable. Thus, we can directly access those properties. But, first, let’s check the images stored on the website.

$response.Images.src

Output:

With some operation on the command above, you can download those images to the particular folder as shown below. It will download all the images from the link to the C:tempWebImages folder.

$imgurl = ($img.Split(‘?’))[0] $imgname = ($imgurl -split ‘/’)[-1] }

Output:

Similarly, you can access the links from the website.

$response.Links.Href

Example #5

Converting Rest API content to JSON data using wget.

When we use the rest API to get the website data, that data is generally is in JavaScript Object Notation (JSON) format. Therefore, when we use the Invoke-RestMethod command, it directly converts the output to the JSON format, as shown below.

Output:

But using the wget command, we need to use some cmdlets to filter the content and then we can convert to the above output display format.

You will get the same output as the first one.

Example #6

Login to the website using the wget post method.

In the below example, we will use the LinkedIn website to log in using wget forms as shown below.

$form = $response.Forms[1] Write-Output “`n`nWebsite Status: $($r.StatusDescription)”

Output:

Conclusion

Wget or Invoke-WebRequest (Curl, iwr) is one of the best command-line tools for webpage scrapping and is used by various developers and scripters to call the APIs, pass, delete, modify, add the information to the APIs or the webpages without using the GUI and also helpful to deal with the various types or webpage errors and reporting purpose.

Recommended Articles

This is a guide to PowerShell wget. Here we discuss How does PowerShell wget work along with the examples and outputs. You may also have a look at the following articles to learn more –

Update the detailed information about How Iife Work In Javascript With Programming Examples on the Bellydancehcm.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!