Node.js - Getting Started with Variables

by
Jeremy Canfield |
Updated: November 25 2024
| Node.js articles
There are three main types of variables that are used in Node.js, const and var and let. Let's say you have a file named app.js that contains the following.
const my_constant = "Hello";
var my_variable = "World";
let my_let = "foo";
console.log(my_constant);
console.log(my_variable);
console.log(my_let);
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
Here are examples of the different types of variables you can create.
const my_string = "Hello World";
const my_list = ["Hello", "World"]
const my_boolean = true;
const my_integer = 42;
const my_json = '{"foo": "Hello", "bar" :"World"}';
const my_object = JSON.parse(my_json);
var my_undefined;
console.log(`my_string = ${my_string}`);
console.log(`my_list = ${my_list}`);
console.log(`my_boolean = ${my_boolean}`);
console.log(`my_integer = ${my_integer}`);
console.log(`my_json = ${my_json}`);
console.log(`my_object = ${my_object}`);
console.log(`my_undefined = ${my_undefined}`);
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