When it comes to JavaScript, the evaluation order of arguments and delayed evaluation play a crucial

  1. Assuming function( arg1, arg2 ), is it true that arg1 will always evaluate before arg2 (unlike traditional C)?

  2. Is there a way to create a function where arguments are not evaluated immediately, but only on demand? For instance, in if( cond1 || cond2 ), cond2 is evaluated only if cond1 is false. Is it feasible to build a custom if-like function for this purpose?

For example, could a function similar to oracle's nvl( arg1, arg2, ... ) be devised to return the first non-null argument by lazily evaluating them? In typical function calls, all arguments are evaluated prior to executing the function body.

Answer №1

Function parameters are assessed before being transferred to the function, so achieving what you're requesting is not technically feasible. However, there's a workaround:

function evaluate() {
    for (var j = 0; j < arguments.length; j++) {
        var result = arguments[j]();
        if (result)
            return result;
    }
}

evaluate(function() { return true; }, 
    function() { return "hello"; }, 
    function() { return false; });

The execution of evaluate will yield the string "hello".

All function wrappers are constructed, but only the content of the first two functions are assessed within evaluate.

While this may not be the most elegant solution, it does provide a way to avoid running a costly operation in any functions following the one that returns a truthy value.

Answer №2

When looking at your initial example, it is important to note that if you are calling a function, the evaluations will occur in order.

However, in the second scenario, JavaScript does not evaluate every parameter (similar to C), as shown here:

if(true || x++){

In this case, x++ will never be executed.

Could you provide more details on what you are attempting to achieve?

Answer №3

  1. Indeed
  2. Absolutely, when using the condition if(cond1 || cond2), cond2 is only evaluated if cond1 is false.

Check out this function that retrieves the first truthy argument:

function getFirstTruthyArgument(){
    for(var i in arguments){
        if(arguments[i]){
           return arguments[i];
        }
     }
 }

For instance,

getFirstTruthyArgument(0, null, undefined, "", "hello", "goodbye")
would output "hello".

If your goal is to obtain the first non-null argument rather than just the first truthy one, you can switch if(arguments[i]) with if(arguments[i] !== null). In this case, the function would result in 0 based on the previous example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The instance does not have a defined "key" property or method in this Vue/Laravel application

When I attempt to delete a register in my application, I encounter a Vue-warn message: The property or method "key" is referenced during render but is not defined on the instance. Make sure that this property is reactive by initializing it in the data o ...

The compatibility between Polymer JS and Rails Turbolinks is problematic

Currently, I am facing a challenge in integrating PolymerJs with a Ruby on Rails project that has Turbolinks enabled. The issue arises when I click on a link - the new page loads correctly but my Polymer components do not reinitialize. They appear as if no ...

Updates to object properties are not appearing in Vue component

I am facing an issue with a Vue component that has a single prop, which is an object. Despite changing a property in this object, it does not reflect the update in the Vue template. Below is a simplified version of the component: <template> <p ...

Secure User Validation Using ExpressJS and CouchDB

I am currently working on implementing a CouchDB User login into my express app using a frontend form and storing the login information in the session. Here is what I have done so far: In my app.js file: var express = require('express'); var co ...

navigating through a specific section of a data chart

I need the first column of a table to stay fixed while the rest of the columns scroll horizontally. Here's the code I have: <div id="outerDiv"> <div id="innerDIv"> <table> <tr><td>1</td><t ...

What is the best way to access a DOM node within a withStyle component?

Currently, I am involved in a react project where my team and I are utilizing Material UI. I encountered a situation where I needed to access the DOM node of another component that was wrapped by a HOC. To achieve this, I attempted using ref in React but o ...

Suggestions for a JavaScript tool that automatically crops images

Is there a tool available, either browser-based or in Java, that can analyze an uploaded image, identify different characters within it, and crop them out into separate images? For instance, if this image contains three unique runic symbols, I would like ...

replace the standard arrow key scrolling with a new custom event

Currently, I am in the process of creating a unique scroll box to address my specific needs. The standard html <select> box is not cutting it for me as I require two columns displayed, which I couldn't achieve with a regular <select>. Howe ...

Downloading a zip file using PHP works successfully when initiated directly, but encounters errors when attempted through a web application

I have been working on a PHP script that generates a zip file and allows it to be downloaded from the browser. The download function in the code snippet below: download.php // ensure client receives download if (headers_sent()) { echo 'HTTP head ...

"Mongoose Nodejs is throwing an error as it is unable to retrieve the property 'id' from an undefined

I'm currently attempting to retrieve and delete an object from MongoDB, but I keep encountering the following error. Cannot read property 'id' of undefined My goal is to fetch an object by its ID. The ID is crucial in my Schema as I am e ...

Having difficulty extracting image and product names from Amazon or Flipkart pages using Jsoup

I'm having trouble retrieving the main image and product name from Amazon or Flipkart using Jsoup. This is my Java/Jsoup code: // For amazon Connection connection = Jsoup.connect(url).timeout(5000).maxBodySize(1024*1024*10); Document doc = connectio ...

Creating a spherical shape without relying on SphereGeometry: Is it possible?

I am attempting to create a sphere without utilizing SphereGeometry. My approach involves drawing the sphere using latitudes and longitudes. Below is the code snippet I am working with: for (var phi = -Math.PI / 2; phi < Math.PI / 2; phi += Math.PI / 1 ...

Retrieving raw PCM data from webAudio / mozAudio APIs

I have been exploring ways to store the output from the webAudio API for future reference. It seems that capturing PCM data and saving it as a file might meet my needs. I am curious to know if the webAudio or mozAudio APIs have built-in functionality for ...

The Express server is set up with CORS enabled, however, it continues to encounter issues when attempting to make asynchronous HTTP requests from

We're currently experiencing an unusual issue and are seeking assistance to resolve it. Initially, our Express server is functioning well as an API when accessed from the same domain. However, we also need to utilize this API on our computers for tes ...

What could be causing the malfunction in one of the functions within my JavaScript code?

As a JavaScript beginner, I am currently working on creating a To-do App with JavaScript. Most of the functions are functioning perfectly except for one called doneTask at line 36. Despite numerous attempts to identify the issue, I have been unsuccessful s ...

Attempting to execute a code snippet using Express framework on the local server at port 3000

Having some trouble with my initial attempt at a basic application. The Scraper.js file successfully scrapes a URL and outputs the array to the document object when executed in the console. Now, I want to set up an Express server to run the script whenever ...

Steps for inserting an additional header in an Angular table

https://i.stack.imgur.com/6JI4p.png I am looking to insert an additional column above the existing ones with a colspan of 4, and it needs to remain fixed like a header column. Here is the code snippet: <div class="example-container mat-elevation-z8"> ...

How can I make my iPad switch to landscape mode in my specific situation?

I'm attempting to trigger the landscape mode on an iPad web browser, including the address bar and tabs, when a user clicks a link. Here's what I currently have: <div> <a ng-click="click me()" href="www.cnn.com">Click me</a&g ...

Exploring the Process of Setting Up a Temporary Endpoint in Express

Currently, I am working with the node.js framework express and my goal is to establish a temporary endpoint. This can either be one that automatically deletes itself after being visited once, or one that I can manually remove later on. Any assistance wou ...

Unable to adjust the width of a table column within a horizontally scrollable container

I am struggling to resize the columns of a large table with 20 headers. Despite trying to place the table inside a div with overflow:auto, I still cannot achieve horizontal scrolling or make the div expand when resizing the columns. A sample code snippet ...