The Node.js REPL (Read-Eval-Print Loop) is an interactive shell that allows us to execute Javascript code directly in a terminal or command prompt.
It provides a easily and convenient way to experiment with Javascript, test small code snippets, and debug.
Read: It reads the user's input; parses the input into Javascript data structure and stores it in memory.
Eval: It takes the input and evaluates the value in Javascript code.
Print: It prints the evaluated result.
Loop: It loops the above command until the user presses `ctrl-c` twice.
To start the Node.js REPL, Open the terminal or command prompt and type:-> node
After hitting Enter, we should see the > prompt, indicating that we are in the Node.js REPL. From here, we can type and execute Javascript code line by line.
nodeTutorial ~ % node Welcome to Node.js v21.2.0. Type ".help" for more information. >
we can declare variables in the REPL Environment using let, var and const.
// const num1 = 30; is declared as variable > const num1 = 30; undefined > const num2 = 40; undefined > const sum = num1 + num2; undefined > sum 70
we can initialize objects in the REPL Environment and can modify them as well.
let employee = { name: 'Alice', age: 30, deptNo: 123 }; undefined > employee.deptNo 123 > employee.deptNo = 333 333 > employee.deptNo 333 > employee.name 'Alice' > employee.name = "alice" 'alice'
We can use the underscore "_" variable to get the last result.
> const num1 = 30; undefined > const num2 = 40; undefined > const sum = num1 + num2 undefined > _ undefined > sum 70 > sum === _ true
> function getFullName(firstName, lastName) { return firstName + " " + lastName; } undefined > getFullName("Alice", "Collin") 'Alice Collin'
press -> `control + c` twice or type ".exit".