Bootstrap FreeKB - NodeJS - Getting Started with Variables
NodeJS - Getting Started with Variables

Updated:   |  NodeJS articles

There are two main types of variables that are used in NodeJS, const and var. Let's say you have a file named app.js that contains the following.

const my_constant = "Hello";
var my_variable = "World";

console.log(my_constant);
console.log(my_variable);

 

If you use the node CLI to run app.js, the following should be displayed as stdout on your console.

~]$ node app.js
Hello
World

 

Be aware that var can be declared in an if statement and then used outside of the if statement, but const cannot.

if ("foo" === "foo") {
  const my_constant = "Hello";
  var my_variable = "World";
}

console.log(my_constant);
console.log(my_variable);

 

Something like this will be returned.

]$ node app.js
file:///usr/local/app.js:6
console.log(my_constant);
            ^

ReferenceError: my_constant is not defined
    at file:///usr/local/app.js:6:13
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async loadESM (node:internal/process/esm_loader:34:7)
    at async handleMainPromise (node:internal/modules/run_main:113:12)

Node.js v20.10.0

 




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 b421be in the box below so that we can be sure you are a human.