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

Creating a JavaScript function that responds to multiple click events

Can someone please help me out? I have the link to the output of my work below using JavaScript and HTML: My goal is for only one circle to be active when clicked, while the others are disabled. Currently, when I click on a circle and then another one, bo ...

Managing JSON Forms using jQuery on Google's App Engine

Having difficulty getting jQuery to function properly on GAE in python 2.7. The main issue is that jQuery is unable to retrieve the json data sent by the server. A basic comment form with no special features: <form action="/postcomment/" method="post" ...

Having difficulties retrieving the <td> id using jQuery

I am a beginner in the world of JavaScript and jQuery, and I am currently attempting to extract both the ID and the value of an element. Here is my initial AJAX request: $.ajax({ type: "POST", url: "Home/AddText", data: JSON.stringify({ te ...

You can click on the link within the Leaflet Popup to trigger JavaScript functionality

My leaflet map is functioning with GeoJSON polygons and popups attached to each one. These popups display information about the polygon. I want a link inside the popup that, when clicked, triggers a JavaScript function to retrieve and display smaller polyg ...

Having trouble constructing the Grand-Stack-Starter api because babel-node is not being recognized

As I endeavor to create the initial api for the Grand Stack Starter, I encounter difficulties every time I try to execute npm start: >nodemon --exec babel-node src/index.js [nodemon] 1.18.7 [nodemon] to restart at any time, enter `rs` [nodemon] watchi ...

What is the best way to create a new variable depending on the status of a button being disabled or enabled

Imagine a scenario where a button toggles between being disabled when the condition is false (opacity: 0.3) and enabled when the condition is true (opacity: 1). Let's set aside the actual condition for now -- what if I want to determine when the butt ...

In order to preserve the data inputted by the user within a file

Check out this HTML code snippet:- ` AngularJS | $http server <div ng-controller="people"> <ul> <h2> Names and Ages of programmers: </h2> <li ng-repeat="person in persons"> { ...

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

apostrophe cutting off a portion of the input field's value

I am facing an issue with a reloaded input box on a web page that is updated through an ajax call. Whenever the input contains a single quote, the rest of the value gets cut off. How can I resolve this problem? The value assigned to myVal dynamically from ...

You are not able to access the instance member in Jest

My first encounter with Javascript has left me puzzled by an error I can't seem to figure out. I'm attempting to extract functions from my class module in order to use them for testing purposes, but they remain inaccessible and the reason eludes ...

Detecting the Escape key when the browser's search bar is open - a step-by-step guide

One feature on my website is an editor window that can be closed using the Escape key. The functionality is implemented in JavaScript: $(document).keyup( function(e) { // Closing editor window with ESCAPE KEY if(e.which == 27) { // Clic ...

Arrays passed as query parameters to Next.js router.query may result in the value being

When trying to pass objects from an array to another page using router.query, individual objects like router.query.title work as expected. However, when attempting to pass arrays such as router.query.reviews, it returns something like reviews: ['&apos ...

In Angular/Typescript, dynamically add a class to a `td` element when it is clicked. Toggle the class on and off

My problem arises when trying to individually control the arrow icons for each column in my COVID-19 data table. By using Angular methods, I aim to show ascending and descending arrows upon sorting but run into the challenge of changing arrows across all c ...

Updating or removing fullCalendar events in Symfony

I'm struggling to figure out how to update or delete fullcalendar events in my Symfony project. When adding a new event, I open a modal window with a form for submitting the event and inserting it into the database. This is my working controller: $ ...

Ways to personalize the onSubmit function within tinacms

Having an issue with my Tina project. I am trying to develop my own submit button in Tinacms project, rather than using the sidebar or top bar provided by tinacms. I want to customize a button for onSubmit functionality. Any suggestions on how to achieve ...

Unable to decipher the mysterious map of nothingness

I am currently working on a GET method in Node.js. My goal is to fetch data using the GET request and then use the MAP function to gather all the names into an array. However, I encountered the following error: /root/server.js:21 ...

Navigating within a React application - rendering JSX components based on URL parameters

As I work on developing a web-app with a chapter/lesson structure, I have been exploring ways to handle the organization of lessons without storing HTML or React code in my database. One idea I had was to save each lesson as a .jsx file within a folder str ...

Error occurred: Unable to access 'client' property as it is undefined. Process will continue running

Hi there! I'm currently working on building a key bot for my website, but I keep encountering this error UNCAUGHT EXCEPTION - keeping process alive: TypeError: Cannot read properties of undefined (reading 'client') along with another one rel ...

Can you please tell me the event that is triggered when an option is unselected in Vue.Drag

I am trying to figure out the event for selecting an item since I already know about the "choose" event. However, I am uncertain about what to use for un-selecting an item. In my particular case, I am unable to utilize the @end event. <draggable :list= ...

What is the best way to pass the reference of the p tag every time the button is clicked?

This is the code I used to create a button: <button type="submit" id="likebtn" onclick="likedpost(this) " data-postid="<%=blog._id%>" data-author="<%=user.username%>">Like</button> ...