Working with JavaScript in Node.js
Understand how JavaScript behaves in Node.js, focusing on the global object and built-in functions like setTimeout.
When using JavaScript in the browser, we work with the window object as the global scope, which includes methods like alert() and properties like location. However, in Node.js, there is no window object because it operates outside the browser environment. Instead, Node.js uses its own global object, global, to store globally accessible properties and functions. Functions like console.log() and setTimeout() are part of this global scope and can be used directly in Node.js applications.
While we can reference properties on the global object explicitly, in most cases, we can access global properties directly without needing the global. prefix.
Common global properties and functions
Here are a few commonly used properties and functions from the global scope in Node.js:
console: Used for printing output, similar to logging in the browser.setTimeoutandsetInterval: Functions for scheduling delayed and repeated code execution.process: Provides information and control over the current Node.js process (we’ll coverprocessin more detail later).
These examples illustrate the types of functionality available globally in Node.js, forming part of the tools we’ll commonly use when developing applications.
Using setTimeout in Node.js
The setTimeout function allows us to delay the execution of a function. This can be useful in asynchronous programming when we want to execute code after a certain amount of time.