Skip to main content

Hello World

To get a sense of how to write code using the tools for this course and to ensure that your development environment is set up correctly, let's start with a simple "Hello World".

  1. If you haven’t already, be sure to download and install the current release of Node.js. If you’re not sure whether or not you have Node.js installed, open the Command Prompt and type node -v. If Node.js has been installed, this will output the version.

  2. Make sure you have Visual Studio Code installed. This is an open-source, cross-platform development environment provided by Microsoft. While it is true that you can write your code in any text editor, Visual Studio Code works very nicely alongside Node.js and all examples going forward will assume that you are using Visual Studio Code. You can download it here

  3. On your Local computer, navigate to your desktop and create a folder called Ex1

  4. Open Visual Studio Code and select File -> Open Folder. Choose your newly created “Ex1” Folder and click “Select Folder”

  5. You should see an “Explorer” pane open on the left side with two items: “Open Editors” and “Ex1”. Click to expand “Ex1” and locate the “New File” button ( New File Button ). Click this and type “hello.js”.

  6. You should now see your newly created “Hello.js” file in the editor. Enter the following line of code:

    console.log('Hello World!');

    and click File -> Save (Ctrl + S)

  7. Open the Integrated Terminal by selecting View -> Integrated Terminal (Ctrl + `) and type:

    node hello.js

Hello World! This is the most basic example in Node.js – notice how we didn’t need to open a web browser, scratchpad, devtools, etc? It’s also important to note that the command “node hello.js” can be executed in any command prompt as long as the active working directory is set to wherever your hello.js file is located (Ex1 in this case). The Integrated Terminal is just a quick, easy way to get a command prompt running in the correct location without leaving the development environment.

Introduction to JavaScript

As you may have guessed from above, the first web technology we will learn is JavaScript. JavaScript (often shortened to JS) is a lightweight, interpreted or JIT (i.e., Just In Time) compiled language meant to be embedded in host environments, for example, web browsers or runtime environments such as "Node.js".

JavaScript looks similar to C/C++ or Java in some of its syntax, but is quite different in philosophy; it is more closely related to Scheme than C. For example, JavaScript is a dynamic scripting language supporting multiple programming styles, from object-oriented to imperative to functional.

JavaScript is one of, if not the most popular programming languages in the world, and has been for many years. Learning JavaScript well will be a tremendous asset to any software developer, since so much of the software we use is built using JS.

JavaScript's many versions: JavaScript is an evolving language, and you'll hear it referred to by a number of names, including: ECMAScript (or ES), ES5, ES6, ES2015, ES2017, ..., ES2021, ES2022, etc. ECMA is the European Computer Manufacturers Association, which is the standards body responsible for the JS language. As the standard evolves, the specification goes through different versions, adding or changing features and syntax. In this course we will primarily focus on ECMAScript 6 (ES6) and newer versions, which all browsers support. We will also sometimes use new features of the language, which most browsers support. Language feature support across browsers is maintained in this table.

JavaScript Resources

Throughout the coming weeks, we'll make use of a number of important online resources. They are listed here so you can make yourself aware of them, and begin to explore on your own. All programmers, no matter how experienced, have to return to these documents on a routine basis, so it's good to know about them.

JavaScript Environments

JavaScript is meant to be run within a host environment. There are many possible environments, but we will focus on the following:

If you haven't done so already, you should install all of the above.

JavaScript Engines

JavaScript is parsed, executed, and managed (i.e., memory, garbage collection, etc) by an engine written in C/C++. There are a number of JavaScript engines available, the most common of which are:

  • V8, maintained an used by Google in Chrome and in node.js
  • SpiderMonkey, maintained and used by Mozilla in Firefox
  • ChakraCore, maintained and used by Microsoft in Edge
  • JavaScriptCore, maintained and used by Apple in Safari

These engines, much like car engines, are meant to be used within a larger context. We will encounter them indirectly via web browsers and in node.js.

It's not important to understand a lot about each of these engines at this point, other than to be aware that each has its own implementation of the ECMAScript standards, its own performance characteristics (i.e., some are faster at certain things), as well as its own set of bugs.

JavaScript Syntax

Recommend Readings

We will spend the next few weeks learning JavaScript, and there is no one best way to do it. The more you read and experiment the better. The following chapters/pages give a good overview:

Important Ideas

  • JavaScript is Case-Sensitive: customerCount is not the same thing as CustomerCount or customercount

  • Name things using camelCase (first letter lowercase, subsequent words start with uppercase) vs. snake_case.

  • Semicolons are optional in JavaScript, but highly recommended. We'll expect you to use them in this course, and using them will make working in C++, Java, CSS, etc. much easier, since you have to use them there.

  • Comments work like C/C++, and can be single or multi-line

    // This is a single line comment. NOTE: the space between the // and first letter.

    /*
    This is a multi-line comment,
    and can be as long as you need.
    */
  • Whitespace: JavaScript will mostly ignore whitespace (spaces, tabs, newlines). In this course we will expect you to use good indentation practices, and for your code to be clean and readable. Many web programmers use Prettier to automatically format their code, and we will too:

    // This is poorly indented, and needs more whitespace
    function add(a, b) {
    if (!b) {
    return a;
    } else {
    return a + b;
    }
    }

    // This is much more readable due to the use of whitespace
    function add(a, b) {
    if (!b) {
    return a;
    } else {
    return a + b;
    }
    }
  • JavaScript statements: a JavaScript program typically consists of a series of statements. A statement is a single-line of instruction made up of objects, expressions, variables, and events/event handlers.

  • Block statement: a block statement, or compound statement, is a group of statements that are treated as a single entity and are grouped within curly brackets {...}. Opening and closing braces need to work in pairs. For example, if you use the left brace { to indicate the start of a block, then you must use the right brace } to end it. The same matching pairs applies to single '......' and double "......." quotes to designate text strings.

Variables

Variables are declared using the let keyword. You must use the let keyword to precede a variable name, but you do not need to provide a type, since the initial value will set the type.

let year;
let seasonName = 'Fall';

// Referring to and using syntax:
year = 2023;
console.log(seasonName, year);

NOTE: JavaScript also supports the var and const keywords for variable declaration.

Variables must start with a letter (a-zA-Z), underscore (_), or dollar sign ($). They cannot be a reserved (key) word. Subsequent characters can be letters, numbers, underscores. If you forget to use the let keyword, JavaScript will still allow you to use a variable, and simply create a global variable. We often refer to this as "leaking a global," and it should always be avoided:

let a = 6; // GOOD: a is declared with let
b = 7; // BAD: b is used without declaration, and is now a global

Data Types

JavaScript is a typeless language -- you don't need to specify a type for your data (it will be inferred at runtime). However, internally, the following data types are used:

  • Number - a double-precision 64-bit floating point number. Using Number you can work with both Integers and Floats. There are also some special Number types, Infinity and NaN.

  • BigInt - a value that can be too large to be represented by a Number (larger than Number. MAX_SAFE_INTEGER,) can be represented by a BigInt. This can easily be done by appending n to the end of an integer value.

  • String - a sequence of Unicode characters. JavaScript supports both single ('...') and double ("...") quotes when defining a String.

    NOTE: JavaScript doesn't distinguish between a single char and a multi-character String -- everything is a String. You define a String using either single ('...'), double ("...") quotes. Try to pick one style and stick with it within a given file/program vs. mixing them. Modern ECMAScript also allows for the use of template literals. Instead of ' or ", a template literal uses ` (backticks), and you can also interpolate expressions.

  • Boolean - a value of true or false. We'll also see how JavaScript supports so-called truthy and falsy values that are not pure Booleans.

  • Object, which includes Function, Array, Date, and many more. - JavaScript supports object-oriented programming, and uses objects and functions as first-class members of the language.

  • Symbol - a primitive type in JavaScript that represents a unique and anonymous value/identifier. They can normally be used as an object's unique properties.

  • null - a value that means "this is intentionally nothing" vs. undefined

  • undefined - a special value that indicates a value has never been defined.

DeclarationTypeValue
let s1 = "some text";String"some text"
let s2 = 'some text';String"some text"
let s3 = '172';String"172"
let s4 = '172' + 4;String"1724" (concatenation vs. addition)
let n1 = 172;Number172 (integer)
let n2 = 172.45;Number172.45 (double-precision float)
let n3 = 9007199254740993n;BigInt9007199254740993n (integer)
let b1 = true;Booleantrue
let b2 = false;Booleanfalse
let b3 = !b2;Booleantrue
let s = Symbol("Sym");symbolSymbol(Sym)
let c;undefinedundefined
let d = null;objectnull

Arrays

We can create an Array in JavaScript using an "Array literal", using the following syntax (we will discuss the "Array Object" further in the coming weeks):

let arr2 = [1, 2, 3]; // array literal

Like arrays in C / C++, a JavaScript Array has a length, and items contained within it can be accessed via an index:

let arr = [1, 2, 3];
let len = arr.length; // len is 3
let item0 = arr[0]; // item0 is 1

Unlike languages such as C / C++ , a JavaScript Array can contain any type of data, including mixed types:

let list = [0, '1', 'two', true];

JavaScript Arrays can also contain holes (i.e., be missing certain elements), change size dynamically at runtime, and we don't need to specify an initial size:

let arr = []; // empty array
arr[5] = 56; // element 5 now contains 56, and arr's length is now 6

NOTE: a JavaScript Array is really a map, which is a data structure that associates values with unique keys (often called a key-value pair). JavaScript arrays are a special kind of map that uses numbers for the keys, which makes them look and behave very much like arrays in other languages. We will encounter this map structure again when we look at how to create Objects.

Operators

Common JavaScript Operators (there are more, but these are a good start):

OperatorOperationExample
+Addition of Numbers3 + 4
+Concatenation of Strings"Hello " + "World"
-Subtraction of Numbersx - y
*Multiplication of Numbers3 * n
/Division of Numbers2 / 4
%Modulo7 % 3 (gives 1 remainder)
++Post/Pre Incrementx++, ++x
--Post/Pre Decrementx--, --x
=Assignmenta = 6
+=Assignment with additiona += 7 same as a = a + 7. Can be used to join Strings too
-=Assignment with subtractiona -= 7 same as a = a - 7
*=Assignment with multiplicationa *= 7 same as a = a * 7
/=Assignment with divisiona /= 7 same as a = a / 7
&&Logical ANDif(x > 3 && x < 10) both must be true
()Call/Create() invokes a function, f() means invoke/call function stored in variable f
||Logical ORif(x === 3 || x === 10) only one must be true
|Bitwise OR3.1345|0 gives 3 as an integer
!Logical NOTif(!(x === 2)) negates an expression
==Equal1 == 1 but also 1 == "1" due to type coercion
===Strict Equal1 === 1 but 1 === "1" is not true due to types. Prefer ===
!=Not Equal1 != 2, with type coercion
!==Strict Not Equal1 !== "1". Prefer !==
>Greater Than7 > 3
>=Greater Than Or Equal7 >=7 and 7 >= 3
<Less Than3 < 10
<=Less Than Or Equal3 < 10 and 3 <=3
typeofType Oftypeof "Hello" gives 'string', typeof 6 gives 'number'
cond ? a : bTernarystatus = (age >= 18) ? 'adult' : 'minor';

NOTE: JavaScript is dynamic, and variables can change value and type at runtime:

let a; // undefined
a = 6; // 6, Number
a++; // 7, Number
a--; // 6, Number
a += 3; // 9, Number
a = 'Value=' + a; // "Value=9", String
a = !!a; // true, Boolean
a = null; // null

JavaScript is also a garbage collected language. Memory automatically gets freed at runtime when variables are not longer in scope or reachable. We still need to be careful not to leak memory (i.e., hold onto data longer than necessary, or forever) and block the garbage collector from doing its job.

Expressions

A JavaScript expression is any code (e.g., literals, variables, operators, and expressions) that evaluates to a single value. The value may be a Number, String, an Object, or a logical value.

let a = 10 / 2; // arithmetic expression
let b = !(10 / 2); // logical expression evaluates to false
let c = '10 ' + '/' + ' 2'; // string, evaluates to "10 / 2"