For a simple contract:

pragma solidity ^0.4.11;

contract Test {
   uint private val;

   function getVal() constant returns(uint) {
       return val;

   function setVal(uint newVal) payable {
       val = newVal;

   function() {

getVal will be called from web3.js something like this:

contract.getVal.call(function(err, val) {

setVal will be called from web3.js something like this:

     gas: gas, 
     from: web3.eth.defaultAccount
  function(err, result) {

How to trigger unnamed function from Javascript? Is it possible?

2 Answers 2


The simplest is to use web3.eth.sendTransaction.

Use the contract address for to. Leave data empty (this is the field that determines which function is invoked in a contract). Usually you would specify the amount of wei value, but you can omit this if you just want to invoke the fallback function.

Fallback functions are not intended to be used the way you might be planning. For example: they are not executed after any other function executes (you can't do work in other functions and expect that the fallback would be called to then increment a variable); they are also not intended for cleanup.

For more background: When does the fallback function get called?


To call a contract fallback function you can use the below way using Javascript:

Consider I have to call a set function that has a uint256 as a parameter.

        const demo = await Demo.new();
        const valueToUpdate = 1234;
        const signature = web3.utils.sha3('set(uint256)').slice(0,10);
        const msgData = signature + web3.utils.toHex(valueToUpdate).slice(2).padStart(64, '0');
        await web3.eth.sendTransaction({
            from: yourAddress,
            to: demo.address,
            // value: ???,     // If you want to send ether with the call.
            // gas: ???,       // If you want to specify the gas.
            // gasPrice: ???,  // If you want to specify the gas price.
            data: msgData},

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.