Writing code | Node js

Episode 03 - Writing Code

Hey everyone! Welcome back to the Node.js tutorial series. Today we are going to actually write some code!

I am super excited because this is where the real fun begins. Let's get started!

What we will cover:

  • Installing Node.js
  • Verifying Installation
  • Node REPL
  • Writing Code in VSCode
  • Global Objects in Node.js
  • globalThis - The Standard Way

1. Installing Node.js

Let's start by installing Node.js on your system!

Go to: https://nodejs.org/en

Download the LTS (Long Term Support) version and install it.

Follow the installation wizard - just click Next, Next, Next!

2. Verify Installation

After installation, we need to verify if Node.js is installed correctly!

Open your terminal and write this command:

node -v
OUTPUT:
v18.17.0

The command node -v is used to check the installed version of Node.js.

Important: If Node.js is NOT installed, this command will produce an error indicating that the node command is not recognized or not found!

Now let's check NPM version:

npm -v
OUTPUT:
9.6.7

The command npm -v displays the version of NPM (Node Package Manager) that is currently installed on your system.

If you see version numbers for both, congratulations! Node.js is installed correctly!

3. Node REPL - Read, Evaluate, Print, Loop

Now let's write some code!

Open terminal and write command:

node
OUTPUT:
Welcome to Node.js v18.17.0.
Type ".help" for more information.
>

You can now write and execute any code on REPL (Read-Evaluate-Print-Loop)!

> 2 + 2
4

> let name = "Node JS"
undefined

> name
'Node JS'

> console.log("Hello World!")
Hello World!
undefined

> Math.random()
0.7234567891234

This is all running in a Node runtime environment!

Remember: NodeJS is a JS runtime environment, and behind the scenes, it is using the V8 engine.

It's similar to a browser console!

REPL = Read, Evaluate, Print, Loop
=====================================

Read    → Reads your input
Evaluate → Executes the code
Print   → Prints the result
Loop    → Goes back to Read (waits for next input)

To exit REPL, type .exit or press Ctrl + C twice.

But wait - we cannot write code like this for a long time; it's frustrating!

Let's write code on VSCode or any code editor you like!

4. Writing Code in VSCode

Let's set up a proper coding environment!

Step 1: Create a Folder

Start by creating a new folder on your computer. You can name it anything you like (e.g., my-nodejs-project).

Step 2: Open the Folder in VSCode

Open Visual Studio Code (VSCode) and go to File > Open Folder. Select the folder you just created.

Step 3: Create a File Named app.js

Inside your opened folder in VSCode, create a new file named app.js.

Step 4: Write Code

You can now start writing your code inside the app.js file:

// app.js

let name = "Node JS 03";
let a = 5;
let b = 10;
let c = a + b;

console.log(name);
console.log(c);

Step 5: Run the Code

  1. Open terminal using the shortcut Ctrl + ` (backtick)
  2. Write command node app.js to run the code
node app.js
OUTPUT:
Node JS 03
15

AMAZING! You just ran your first Node.js program!

5. Global Objects in Node.js

Now let's talk about global objects in Node.js!

Reference: https://developer.mozilla.org/en-US/docs/Glossary/Global_object

In the browser, we have the window object:

// In Browser:

console.log(window);        // The global window object
console.log(window.alert);  // Alert function
console.log(window.document); // DOM

Important: The window object is a global object provided by the browser, NOT by the V8 engine!

Now, in Node.js...

The global object is known as global, which is equivalent to the window object in the browser!

// In Node.js:

console.log(global);
OUTPUT:
<ref *1> Object [global] {
  global: [Circular *1],
  setTimeout: [Function: setTimeout],
  setInterval: [Function: setInterval],
  clearTimeout: [Function: clearTimeout],
  clearInterval: [Function: clearInterval],
  ...
}

Key Points:

  • A global object is NOT a part of the V8 engine
  • It's a feature provided by Node.js
  • This global object offers various functionalities like setTimeout(), setInterval(), and more!
Browser vs Node.js Global Objects:
==================================

Browser:
--------
window.setTimeout()
window.setInterval()
window.alert()
window.document

Node.js:
--------
global.setTimeout()
global.setInterval()
global.console
global.process

Important Note: console.log(this)

Here's something interesting!

// app.js

console.log(this);
OUTPUT:
{}

Wait, what? An empty object?

When you use console.log(this) at the global level in Node.js, it will log an empty object {}!

This indicates that this does NOT refer to the global object in this context.

Why? Because in Node.js, each file is wrapped in a module, and this refers to module.exports which is initially an empty object!

// In Browser:
console.log(this === window);  // true

// In Node.js:
console.log(this === global);  // false
console.log(this);             // {}
console.log(this === module.exports);  // true!

globalThis - The Standard Way

Now here comes something important!

globalThis is always a global object, regardless of where it is accessed!

It was introduced in ECMAScript 2020 to provide a standardized way to refer to the global object in any environment (browsers, Node.js, etc.).

// globalThis works everywhere!

// In Browser:
console.log(globalThis === window);  // true

// In Node.js:
console.log(globalThis === global);  // true

Key Points about globalThis:

  • In browsers, globalThis is equivalent to window
  • In Node.js, globalThis is equivalent to global
  • It provides a consistent way to access the global object
  • No need to worry about the environment!
// Using globalThis (Works in both Browser and Node.js!)

globalThis.setTimeout(() => {
    console.log("After 1 second!");
}, 1000);

console.log(globalThis.Math.random());
The Problem Before globalThis:
==============================

// Browser code:
window.myVar = "Hello";

// Node.js code:
global.myVar = "Hello";

// Universal code? Had to do this:
var globalObj = typeof window !== 'undefined' ? window : global;
globalObj.myVar = "Hello";

// With globalThis (ES2020):
globalThis.myVar = "Hello";  // Works everywhere!

Much cleaner!

Quick Recap

Concept Description
node -v Check Node.js version
npm -v Check NPM version
node Enter REPL mode
REPL Read, Evaluate, Print, Loop
node app.js Run a JavaScript file
window Global object in Browser
global Global object in Node.js
this Empty object {} at global level in Node.js
globalThis Standard global object (ES2020) - works everywhere

Interview Questions

Q: What is REPL in Node.js?

"REPL stands for Read-Evaluate-Print-Loop. It's an interactive shell where you can execute JavaScript code line by line. You enter REPL by typing 'node' in terminal. It's similar to browser console."

Q: What is the global object in Node.js?

"In Node.js, the global object is called 'global', which is equivalent to 'window' in browsers. It provides functionalities like setTimeout, setInterval, console, etc. It's provided by Node.js, not the V8 engine."

Q: Why does console.log(this) output {} in Node.js?

"At the global level in Node.js, 'this' refers to module.exports which is initially an empty object. Each file in Node.js is wrapped in a module, so 'this' doesn't refer to the global object like it does in browsers."

Q: What is globalThis?

"globalThis was introduced in ECMAScript 2020 to provide a standardized way to access the global object in any environment. In browsers it equals window, in Node.js it equals global. It provides consistency across platforms."

Key Points to Remember

  • node -v and npm -v to verify installation
  • REPL = Read, Evaluate, Print, Loop
  • REPL is like browser console but runs in Node.js runtime
  • Use node filename.js to run code files
  • window is browser's global object (NOT from V8)
  • global is Node.js global object
  • console.log(this) outputs {} in Node.js
  • globalThis works in both browser and Node.js (ES2020)

What's Next?

Now you know how to install Node.js, use REPL, write code in VSCode, and understand global objects! In the next episode, we will:

  • Learn about modules in Node.js
  • Understand require() and module.exports
  • Work with built-in modules

Keep coding, keep learning! See you in the next one!