Bootstrap FreeKB - Node.js - Getting Started with Functions
Node.js - Getting Started with Functions

Updated:   |  Node.js articles

In Node.js, function is a reserved keyword that is used to define a function. 

A function contains markup that can be used one or more times in a script. Unlike certain programming language like bash and python, it doesn't matter where in your script the function is defined. You don't need to worry about defining your function before of after the function is called, which is really nice.

function foo() {
  return "Hello World"
}

console.log(foo())

 

In this example, a function named "Hello" is defined that will simply print the text "Hello World".

~]$ node app.js
Hello World

 

And here is an example of how to store the value returned by the function in a constant (const).

function bar() {
  return "Hello World"
}

const response = bar()
console.log(response)

 

Passing in values

Values are commonly passed into a function. In this example, value "Hello World" is passed into the Hello function.

function Hello(greeting) {
  return greeting;
}

console.log(Hello("Hello World"));

 

In this example, running the Node.js script should print "Hello World".

~]$ node app.js
Hello World

 

Keyword Args

The above example if fine for very simple functions that have little to no chance of ever needing a change. However, for more complex scenarios and for functions that may evolve over time, it almost always makes sense to pass keyword arguments into the function, so that later on if you need to add/change/remove the options being passed into the function you only need to update the code that is calling the function and not the function itself. This makes the function future proof.

function my_function(options) {
  return options.foo;
}

console.log(my_function({ foo: "Hello", bar: "World" }));

 

In this example, running the Node.js script should print "Hello World".

~]$ node app.js
Hello

 

async function

Fundamental to Node.js is the concept of asynchronous which is the idea of doing multiple things simultaenously. The async keyword can be used so that you immediately move through the script without waiting for a response from the async function. 

async function Hello(greeting) {
  return await greeting;
}

console.log(Hello("Hello World"));

 

Now running the script should return the following.

~]$ node app.js
Promise { 'Hello World' }

 

.then is used if you want the value being returned by the async function.

async function Hello(greeting) {
  return await greeting;
}

Hello("Hello World").then(response => {console.log(response)});

 

Which should print "Hello World".

~]$ node app.js
Hello World

 

Or, more commonly, with .then and .catch.

async function Hello(greeting) {
  return await greeting;
}

Hello("Hello World")
  .then(response => {console.log(response)})
  .catch(err => {console.error(err)});

 

You may also want to exit after the response or err are returned.

async function Hello(greeting) {
  return await greeting;
}

Hello("Hello World")
  .then(response => {
      console.log(response)
      process.exit(0)
  })
  .catch(err => {
      console.error(err)
      process.exit(1)
  });

 

throw error

throw is often used when the function detects some issue and needs the function to immediately exit.

function sayHello(message) {
  if (message != "hello") {
    throw new Error("message does not equal hello")
  }
  return message
}

try {
  console.log(sayHello("nope"))
} catch (err) {
  console.error(err.message)
}

 

Running this script should return the following.

~]$ node demo.js
message does not equal hello

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 3d74e4 in the box below so that we can be sure you are a human.