Monday, 1 October 2018

Node.js: Interactive shell

Open command prompt (or) terminal and execute the command 'node'.

Node opens REPL (Read Eval Print Loop) interactive command prompt like below.

C:\>node
>

Evaluating expressions in REPL prompt
REPL prompt waits for the instructions to execute. Let’s try to evaluate some arithmetic expressions.

C:\>node
> 1 + 2
3
> 1 - 2
-1
> 1 * 2
2
> 1 / 2
0.5
> 1 + (2 * 3)/ 4
2.5


You can even assign values to variables and reuse.

> x = 10
10
> y = 20
20
> z = x + y
30

As you see, the value stored in the variable is printed immediately. If you use ‘var’ keyword while defining the variable, then the value is printed as undefined.

> var a = 10
undefined
> var b = 20
undefined
> var c = a + b
undefined
> console.log("Value of a is " + a)
Value of a is 10
undefined
> console.log("Value of b is " + b)
Value of b is 20
undefined
> console.log("Value of c is " + c)
Value of c is 30
Undefined


Is node REPL supports multi line expressions?
Yes, let me explain with an example.

> x = 10
10
> while (x != 0 ){
... console.log(x);
... x--;
... }
10
9
8
7
6
5
4
3
2
1
1


Previous                                                 Next                                                 Home

No comments:

Post a Comment