Skip to content

Latest commit

 

History

History
267 lines (191 loc) · 7.31 KB

File metadata and controls

267 lines (191 loc) · 7.31 KB
layout post
title The Node.js REPL
author NodeKC
tags

The Node.js REPL

In this lab you will learn how to use the Node.js REPL (read-eval-print loop) to execute ad-hoc JavaScript statements. By the end of this lab you should be comfortable using the REPL and defining strings, objects, arrays, and functions in JavaScript.

Starting the Node.js REPL and Executing Statements

To launch the Node.js REPL open a command prompt or terminal and execute node. Once open, evaluate a few simple expressions:

{% highlight javascript %}

1 + 5 6

var add = function (a, b) { return a + b; } undefined

add(1, 5) 6 {% endhighlight %}

Notice the result of the statement executed is printed on the following line without >. If you made a typo you can cancel your statement by pressing CTRL+C once.

If you forgot to assign the value of the previously executed statement, the Node.js REPL provides a useful syntax to access the previous result through _.

{% highlight javascript %}

"Node.js Rocks!" 'Node.js Rocks!'

_ 'Node.js Rocks!'

var lastResult = _ undefined

lastResult 'Node.js Rocks!' {% endhighlight %}

Interacting with Arrays

A major difference between arrays in JavaScript and many other languages is that they are mutable and the size is not required upon creation. Use the array initializer (or array syntax) to create arrays:

{% highlight javascript %}

[1, 2] [1, 2]

[1,2].length 2 {% endhighlight %}

Adding an item to an array existing array:

{% highlight javascript %}

var a = ['apple', 'banana', 'kiwi'] undefined

a.length 3

a.push("lemon") 4 // push returns the size of the array after the push operation completes

a.unshift("lime") 5 // unshift adds an element to the beginning of the array and returns the new length {% endhighlight %}

Now inspect the contents of your array:

{% highlight javascript %}

a [ 'lime', 'apple', 'banana', 'kiwi', 'lemon' ] {% endhighlight %}

Removing an item from an array:

{% highlight javascript %}

a.pop() 'lemon' // pop removes and returns the last value in the array.

a.shift() 'lime' // shift removes and returns the first value in the array. {% endhighlight %}

The slice function can be used to copy a portion of an array to a new array. It does not modify the original array; rather, it copies it and returns a portion. It takes two arguments: a start index and end index. The end index is not inclusive.

{% highlight javascript %}

a ['apple', 'banana', 'kiwi']

a.slice(0, 1) ['apple']

a ['apple', 'banana', 'kiwi'] // the original array is not changed.

a.slice(0) ['apple', 'banana', 'kiwi'] // copies the entire array. {% endhighlight %}

You can even grab the last 2 values from an array using slice.

{% highlight javascript %}

a.slice(-2, a.length) [ 'banana', 'kiwi' ] {% endhighlight %}

Interacting with Objects

An object is not much more than a collection of keys and values. An object can be created using the object initializer (or object syntax). Properties can be set using the dot operator:

{% highlight javascript %}

var o = {} undefined

o.foo undefined

o.foo = 'bar' 'bar'

o.foo.length 3 {% endhighlight %}

The array syntax (brackets) can allow you to create properties on objects that would otherwise be impossible to access using the dot syntax above. An interesting note here is that objects in JavaScript can have any value as keys, not just strings or numbers.

{% highlight javascript %}

o['foo^bar'] = 'things' 'things'

o['foo^bar'] 'things'

o.foo^bar //This won't work because of the special character ReferenceError: bar is not defined at repl:1:8 at REPLServer.self.eval (repl.js:110:21) at Interface. (repl.js:239:12) at Interface.EventEmitter.emit (events.js:95:17) at Interface._onLine (readline.js:202:10) at Interface._line (readline.js:531:8) at Interface._ttyWrite (readline.js:760:14) at ReadStream.onkeypress (readline.js:99:10) at ReadStream.EventEmitter.emit (events.js:98:17) at emitKey (readline.js:1095:12) {% endhighlight %}

What if we wanted the keys of our objects to be functions? That's ok too! If you don't quite understand the function syntax yet don't worry that's coming up next.

{% highlight javascript %}

var x = function () { return 101; } undefined var o = {} undefined o[x] = 1 1 o[x] 1 x() //look it's just a function! 101 {% endhighlight %}

The array syntax o['foo'] and the dot syntax o.foo can be used interchangeably for simple string values.

Objects can be composed of other objects:

{% highlight javascript %}

o.bar = [1, 2, 3, 4] [1, 2, 3, 4]

o.bar.length 4

o.foobar = function () { return 'foo bar!'; } [Function]

o.foobar() 'foo bar!'

o'foobar' 'foo bar!' {% endhighlight %}

Creating and Calling Functions

JavaScript functions are declared using the function keyword. This will create functions called foo and bar that do nothing:

{% highlight javascript %}

var foo = function () {} // this syntax is known as a function expression undefined

foo [Function]

function bar () {} // this syntax is known as a function declaration undefined

bar [Function: bar] {% endhighlight %}

Both function declarations and expressions define functions the same way. If you use a function declaration, it may be possible to call the function in your code in lines of code above where it is defined. This practice is not recommended.

It's recommended to always use function expressions unless you understand function hoisting (further reading).

Functions that do not have a name are anonymous. For example, function () { } is considered anonymous. These are commonly used as callback arguments to other functions.

{% highlight javascript %} // declare a function that takes a callback argument

var foo = function (callback) { ... callback(); ... } undefined

// passing an anonymous function as a callback

foo(function () { ... // callback function body ... }); undefined {% endhighlight %}

Multi-line Statements in the REPL

You may have noticed that the Node.js REPL allows for multi-line statements to be executed. When a line cannot be processed as a complete JavaScript statement the Node.js REPL prompts for more input, as demonstrated when starting a function declaration above.

The ... indicates that the Node.js REPL expects more input. CTRL+C can be used to cancel the multi-line statement if it was made in error.

Now, define a multi-line function and execute it:

{% highlight javascript %}

var boo = function () { ... return "Hello World!"; ... } undefined

boo() 'Hello World!' {% endhighlight %}

Exiting the Node.js REPL

Exiting the Node.js REPL can be done by keyboard interrupt or exiting the process.

To exit by keyboard interrupt, press CTRL+C twice.

To instruct the Node.js process to exit:

{% highlight javascript %}

process.exit() {% endhighlight %}