Normally, there's an ad running in this spot, but you're using an ad blocker. To help support our blog, which provides free tutorials for everybody, we just ask that you whitelist or follow us on facebook, twitter, or subscribe using the form to the leftabove. Thank you!

    Learning JavaScript Using the NodeJS REPL

    Today, we're going to learn how to program JavaScript code exclusively in NodeJS running in the shell or terminal. This tool is sometimes referred to as the interpreter or REPL (read eval print loop), which allows you to quickly execute JavaScript in real time without having to set up any boilerplate code.

    To make it even more convenient, we've even provided a JavaScript REPL in the browser. Feel free to type into the code window below, if you're unable to install NodeJS. I recommend that you have two windows of this page running side-by-side. This allows you to run the code in one window, while scrolling through the article in another.

    JavaScript Fundamentals

    We're not going to waste anymore time. Let's start writing some JavaScript code.

    JavaScript Operators

    > 1+2
    > 2*3
    > 4/2
    > 1+2*4/2
    > (1+2)*4/2

    Math operators +, -, * and / allow you to perform basic calculations. Type out these operations like you would on a calculator. PEMDAS rules apply, so utilize parenthesis when you require a specific order of operations.

    JavaScript Variables

    > var a = 1;
    > var b = 2;
    > a + b
    > b - a

    We can store values into variables, in order to reuse them over multiple operations. When programming JavaScript, variable names should start with a lowercase letter or underscore, and should use camelCasing. The full Style Guide for JavaScript Code is available at W3 Schools.

    Notice that the NodeJS/JavaScript interpreter is printing undefined to the screen after certain declarations. In JavaScript, we have to explicitly define the return statement, or undefined will be returned. In some cases, like where we've run a + b, the result is immediately printed to make it more convenient in the REPL. For now, just remember that there are some differences related to return when using the REPL versus JavaScript running in the browser.

    JavaScript is Weakly Typed

    > var a = "Jane"
    > var b = "Doe"
    > "Hello " + a + " " + b + "."
    'Hello Jane Doe.'
    > var c = 2
    > a + " " + b + " " + c
    'Jane Doe 2'

    Notice that you can override old variables, in JavaScript. In addition, the new variables can be of a different type. Notice how we've replaced a and b's Numbers with strings (letters). This is made possible because JavaScript is both a dynamically typed and weakly typed language, allowing you to reassign variables with different types. But unlike a strongly typed language like Python, adding a string to a number "Jane Doe" + 2 converts the output to a string before printing it to the screen, whereas Python would have thrown an error.

    With a staticly typed language like Java, you have to designate the variable type when you declare it, and attempting to change its type throws errors. So why would we want to use static typing? It helps significantly with debugging, and quickly warns of any bugs related to variable typing. Without the compiler warning us, we'd have to spend time determining if the bugs we're caused by a variable accidentally changing from a string to a number, or a string being inserted into an array that should only accept ints.

    Similar issues are avoided when writing with functional programming languages or practices, but that's a topic for a different tutorial.

    JavaScript Conditionals

    if (condition) {

    Unlike Python code, spacing and indenting is optional. JavaScript utilizes curly braces to encapsulate functions.

    The most basic JavaScript conditional is the if else.

    > var c = 2;
    > if (c > 1) {
    ... console.log(true);
    ... } else {
    ... console.log(false);
    ... }

    Here, we're determining: if c is greater than 1, print true to the screen by calling console.log(). Else, print talse. We've previously declared c to be 2. Feel free to reassign c to 0 and see what happens when you rerun the conditional. Also try to experiment with the following conditional expressions:

    Expression Math Symbol JavaScript Equivalent
    Less than < <
    Greater than > >
    Less than or equal <=
    Greater than or equal >=
    Equals = ==
    Not equals !=
    Equals (strict) = ===
    Not equals (strict) !==

    The == operator checks for equality after performing any necessary type conversions. The === operator does not perform the conversion, so if two values are of different types (Number, string, boolean, etc.) === will return false. So for example:

    Operator Result
    true == 1 true
    true === 1 false

    Note: About console.log().

    Notice that even when printing to the screen with console.log(), the NodeJS REPL still expects the coder to return a value. Otherwise, it will return undefined as usual.

    JavaScript Functions

    > function add(a, b) {
    ... return a + b;
    ... }
    > add(1, 2);

    Here, we've written a function that accepts two numbers and returns the sum.

    In JavaScript, we explicitly declasre functions with function, and the function signature which is comprised of function, the name of the function and parameters within parenthesis. a stores the first integer, and b stores the second. The function will then reference a and b when it performs the addition operation.

    This operation is performed from right to left.

    1. First, a + b is performed.
    2. The result is then passed to the left, to the return statement.
    3. return then passes the result along to the left, out of the function to the function caller, and onto the variable result.

    After we've defined our function, we invoke it by simply calling it by name and giving it values to store in the paramenters like so: add(1, 2).

    A function can contain as many parameters as it needs and consists of as many lines for it to do its job. Generally, you want to keep functions concise, focused on one job, and readable. If a great deal of steps need to be performed, it's best to break up each step across multiple smaller functions to make debugging easier.

    Multiple Ways to Declare JavaScript Functions

    Declaring a JavaScript Function by Storing it into a Variable

    The example below allows us to treat the function with the same properties as a variable, allowing us to be more explicit with how we define its scope, and even reassign the variable, as needed.

    > var add = function(a, b) {
    ... return a + b;
    ... }
    > var result = add(1, 2);
    > result

    Declaring the Same JavaScript Function Without a Returned Value

    Again, console.log() prints the sum to the screen, but undefined is also printed because we haven't explicitly declared anything to return.

    > var add = function(a, b) {
    ... console.log(a + b);
    ... }
    > add(1, 2);


    That's all for this tutorial. In the next chapter of this series, we'll be writing code in .js files using a code editor. While the JavaScript/NodeJS REPL is great for small calculations, large functions and programs are too unwieldy in this environment.

    Did you like this tutorial? Help us pay for server costs by following us on Facebook, Twitter, and subscribing below, where you'll get post notifications, training webinar invites, and free bundles.