Open CheatSheet Back To List Next Tutorial

Intermediate JavaScript Introduction

Intro

This is the first tutorial in the Intermediate JavaScript tutorial series and the third tutorial overall. This assumes you have already reviewed the two Beginning JavaScript tutorials. 

  • There is a separate tutorial for each major topic on the JavaScript CheatSheet.
  • The intent of this tutorial series is to get you to a highly proficient intermediate skill level by focusing on topics that you will need to be familiar with while excluding advanced topics that you are less likely to use.

  • The example code from the tutorial series is available for download on GitHub: github.com/LearnByCheating/javascript-tutorial
    • Each tutorial includes example code. It is recommended you try out the example code in your own JavaScript file, or run the example code from the GitHub repository. The repository has a separate file or folder for each tutorial. The javascript-tutorial Readme file has instructions on how to create a test file to run your code, and how to run the example code from the GitHub repository.


Documentation

JavaScript documentation is provided by the Mozilla Developers Network (aka MDN), which is a joint project among three of the top browser vendors: Mozilla, Google, and Microsoft.

They have lots of excellent documentation including:


  • MDN is also the principal documentation source for HTML and CSS.

  • StackOverflow.com is the top question/answer resource for software developers in any programming language. Googling questions will frequently point you to a Stack Overflow question and answer. You can also search for previous answers on a topic directly in their search bar. Or you can create an account and ask your own question, although all the basic questions have been asked and answered years ago. 



Where and How to Run JavaScript

There are two main environments where you can run JavaScript. The web browser and Node.js:

  • Web Browsers: JavaScript was created specifically to run in a web browser. Its initial purpose was to manipulate elements on HTML pages, making static web pages dynamic.

  • Node.js: In 2009, Ryan Dahl created the Node.js runtime environment allowing JavaScript to be run on the server. This became immediately popular with developers. Suddenly JavaScript could be run in both the browser (the front end) and the server (the back end) environments. Node uses the Chrome Browser's open source JavaScript engine, called V8. And it adds several built-in modules to interact with the host server or personal computer's operating system and with HTTP requests over the internet. It hosts a package manager called npm where third parties can make Node packages that accomplish specialized tasks, big or small. They are available for download to use in your projects.


Run code with Node.js
  • The Beginning tutorial showed how to run JavaScript code using Node.js in two ways:
  • Node Shell: 
    • Open your Terminal application. If you are using VS Code you can open the Terminal panel by clicking the Terminal menu > then select New Terminal. 
    • To launch the Node shell application inside the Terminal enter: node
    • The Shell is a REPL (Read, Evaluate, Print, Loop) program. It reads the code you enter, evaluates it, prints the output to the terminal, and waits for the next input. Enter statements one at a time:
      • let x = 5; 
      • x + 7; 
      • // Prints 12
    • Exit the shell by typing in dot exit: .exit or press Control+D.

  • Run files with Node.js: You can also execute whole files or projects from the command line.
    • Create a file named general.js. JavaScript files have a .js extension.
    • In the file add a single line that will log the given text to the console.
    • general.js
      console.log('This is a JavaScript file.');

    • To execute a JavaScript file in Node type in "node" then the path to the file. The .js extension is implied.
      • node general
    • That will execute the file and and print the console log to the Terminal.



Run files with VS Code Debugger
  • Another way to run you JavaScript files that is useful when developing an application is with the VS Code Debugger.
  • VS Code has a built-in Debugger. You can run a file with the Debugger, then pause your code at specified breakpoints to view expression and variable values. 

    • Run the Debugger:
      • Click the Run and Debug icon on the Activity bar along the left side of the text editor. That will open the Run and Debug sidebar.
      • Click the Run and Debug button. Then select Node.js from the dropdown menu. This will run the file that is open and pause at the first breakpoint.

    • Breakpoints: 
      • Your code will pause at breakpoints. The breakpoint gives you a snapshot of your code before executing the line you pause at. There are two ways to create breakpoints.
        1. Debugger keyword: Putting the keyword debugger; in your code creates a breakpoint.
        2. In the Editor window, Enter Breakpoints in your code by clicking left of the line number. 
          • Breakpoints are indicated with red dots.
          • The break happens at the start of the line, not the end.
          • Click the red dot again to remove it.

    • Variables: 
      • In your code, assign variables to expression values you want to view.
      • View variable values: When the code pauses at a breakpoint, all the variables can be viewed in the Debug sidebar under the Variables heading grouped by scope:
        • Local: lists all the declared variables and their values as of that breakpoint. 
          • Local includes the this object covered below.
        • Global: lists all the properties of the Global object (covered below)

    • The Debug Toolbar: The Debug Toolbar includes icon buttons to:
      • Continue to the next breakpoint. 
      • Step Over: Execute the next line of code then pause. Will step over a function body.
      • Step Into: Execute the next line of code then pause. Will step into a function body.
      • Restart the debugger. 
      • Stop the debugger.

  • To test it out put the below code in your general.js file then run it with the debugger. At each breakpoint (debugger keyword), in the Debug sidebar you will see the variables grouped by scope, with the values as of that breakpoint. The scopes will be: global, local, local function, or block. We will talk more about scope in the Variables tutorial.
glob = 'I am in the global scope';
let loc = 'I am in the local scope';
debugger;
if (true) {
  const blk = 'I am in a block scope';
  debugger;
}
function func() {
  const func = 'I am in a local function scope';
  loc = 'My value was changed but I am still in the local scope"
  debugger;
}
func();


The JavaScript Programming Language

JavaScript Syntax

Now we'll cover JavaScript syntax.

Some syntax rules are required, others are a matter of preference.

There are a few popular style guides published. Two of the most popular are the AirBnB and Google JavaScript style guides. They agree on most of their recommendations, which we will use throughout this tutorial series.

  • Whitespace: 
    • Whitespace includes spaces, tabs, and new line characters. 
    • JavaScript recognizes tabs, new line characters, and single spaces, but it ignores multiple spaces, except with used for indentation. 
    • Indent your code by two spaces. Do not use tabs. Although, you can set your text editor to insert two space when you press the tab key.
  • Semicolons: 
    • Semicolons go at the end of each JavaScript statement, like periods at the end of a sentence. 
    • Do not put semicolons at the end of code blocks.
  • Code blocks: 
    • Code blocks are a grouping of statements placed inside curly braces. They include if statements, functions, loops, try/catch blocks and more. 
    • Put semicolons at the end of statements within a code block, but do not put semicolons after code blocks.
      • Function declaration example:  function add1(x) { return x + 1; }
    • Functions formatted as function expressions, including arrow functions, do end in a semicolon. 
      • const add1 = (x) => x + 1; 
  • Double vs single quotes: 
    • Stings can be enclosed in either double or single quotes. The style guides recommend using single quotes.
  • Comments: 
    • Single line comments come after two forward slashes: // this is a comment
    • For multiple lines you can use this syntax: /* This is a comment */
    • You can use comments before statements to explain or document the statements that follow.
    • You can also use comments to temporarily disable a chunk of code while you are developing your app.



JavaScript Data Types

When you work with data in a programming language, the way the data is handled depends on what type of data it is. Each language has its own set of data types. 

JavaScript currently has 8 data types, including 7 primitive types and an object type. 

Primitive types represent low level values and include the following:
  • Sting
  • Number
  • BigInt (introduced in ES 2020)
  • Boolean
  • Null
  • Undefined
  • Symbol (introduced in ES 2015)

The most frequently used primitives are String, Number, Boolean, Null and Undefined.

Typeof operator: The typeof operator returns the data type of a value. We'll use the typeof operator to demonstrate data types.

Change the general.js file to the below and save the file:
general.js
console.log(7, typeof 7); // number
console.log('Hello', typeof 'Hello'); // string
console.log('true', typeof true); // boolean
let x;
console.log('undefined', typeof x); // undefined
x = null; // The value null represents the intentional absence of any value.
console.log('null', typeof x); // object. The typeof operator returns object for null.
console.log('{}', typeof {}); // object
console.log('[]', typeof []); // object. Array is a type of object.
console.log('function() {})', typeof function() {}); // function. Although, function is a type of object.

In the code, we are applying the typeof operator to different values and using console.log to print the result to the console. 

Run the file with Node.js: node general
It will log each value and its data type.

Let's try it again using the Debugger. Instead of console logs, assign variable datatype to each expression. 

general.js
let datatype = typeof 7;
debugger;
datatype = typeof 'Hello';
datatype = typeof true;
let x;
datatype = typeof x;
x = null; // The value null represents the intentional absence of any value.
datatype = typeof x; // typeof null returns 'object' even though null is a data type.
datatype = typeof {};
datatype = typeof [];
datatype = typeof function() {};
debugger;

  • Run the file with the Debugger. It will stop at the debugger keyword and you can view the datatype variable value in the debug sidebar under Variables: Local. 
  • Then click the Step Over icon to go to the next line and view the new datatype value.
  • Keep clicking the Step Over icon to look at every line. 

  • Now let's go through the values:
  • typeof 7 returns 'number'. 
    • Some languages have separate data types for integers and decimals but in JavaScript, they are both part of the same "number" data type.
    • JavaScript added a data type called BigInt in 2020. It provides a way to represent whole numbers larger than 2**53 - 1, which is the largest number JavaScript can reliably represent with the Number primitive.

  • typeof 'Hello' returns 'string'.
    • A string is just a sequence of characters. They must be put in single or double quotes. Style guides recommend single quotes. There are also something called template strings that use backtics instead of quotes.
    • Putting a number or boolean in quotes changes its data type to a string.

  • typeof true returns 'boolean'. So does typeof false
    • Boolean has only two possible values: true or false.

  • let x;
  • typeof x returns 'undefined'.
    • Here we declared a variable named "x" but didn't initialize it with a value. So the value of x is undefined. And the datatype of x is undefined.

  • x = null; 
  • typeof x returns 'object'
    • Here the value of x is null. 
    • Null represents the intentional absence of a value. 
    • So undefined and null both mean the variable has no value, but null is intentionally assigned, while undefined isn't an intentional assignment. 
    • typeof null returns "object". This is an odd situation because it should return "null" since null is a data type and null is not an object. This is actually a known error coming from the early days of JavaScript. They've decided not to correct it, so just be aware of this anomaly.

  • typeof {} returns 'object'
    • The curly braces create an object. An object is collection of properties that is assigned a separate location in memory. Properties are name-value pairs like name: 'Joey' and age: 22.
    • This object has no properties assigned to it but it is still an object.
    • Below is an object assigned to the variable user with properties for name and age:
    • const user = { name: 'Joey', age: 22 };
    • typeof user returns 'object'
      • While the object has its own data type collectively, its property values individually have their own data types:
      • typeof user.name returns 'string'
      • typeof user.age returns 'number'
      • JavaScript objects are mutable. You can add, remove, or change the properties in an object, but it is still the same object location in memory, just with different properties.

  • typeof [] returns 'object'
    • The square brackets create an array. An array is a list of data items. This is an empty array but it's still an array.
    • The datatype is "object" because arrays are a type of object.
    • Below is an array assigned to the variable things
    • const items = ['house', -4.2, false, user];
    • typeof items returns 'object'
    • The array itself has a data type of 'object', but the data items inside the array all have their own data types:
      • typeof items[0] is for the 'house' item and returns 'string'.
      • typeof items[1] is for the -4.2 item and returns 'number'.
      • typeof items[2] is for the false item and returns 'boolean'.
      • typeof items[3] is for the user item and returns 'object'.
    • Arrays are mutable objects. You can add, remove, or change the data items in your array, and it is still the same object location in memory, just with different elements.

  • typeof function() {} returns 'function'
    • This is a function that does nothing but it's still a function.
    • The typeof operator returns 'function'. Function is not actually a separate data type. Rather, a function is a special type of object that has the characteristic of being callable. 
    • Below is an example with an actual function:
      • typeof function add1(x) { return x + 1; } returns 'function'

Loosely typed / Dynamically typed
  • JavaScript is referred to as a loosely typed or dynamically typed language. This means variables are not directly associated with a data type. Variable x can be assigned to a string value then reassigned to a number value.
  • In strongly typed languages like Java or C++, you must declare a data type for each variable when they are created. The values must be from that data type.  

To demonstrate you can open the Node.js shell and create a variable:
let x = 5;
typeof x; 
// prints 'number'

Then put 5 in quotes and it will be a string:
x = '5';
typeof x; 
// prints 'string' 

Strongly typed languages would throw an error when you tried to reassign x from a number to a string value. 

For large enterprise applications, loosely typed languages can introduce bugs that may be hard to track down.

Typescript: Typescript is a language created by Microsoft that is a superset of JavaScript. It requires you to assign data types to variables when you declare them, thus making a strongly typed version of JavaScript.



The Global Object

[14:36 Video timestamp]

The global object is the object at the top level of JavaScript.
It has a global scope meaning properties assigned to the global object can be accessed anywhere in your code. 
It holds the built-in JavaScript objects and Web APIs or Node core modules, as well as any added by your code.

  • window: In the browser, the global object is named "window".
  • global: In Node.js, the global object is named "global".

In DevTools if you enter: window
It will return an object with all the JavaScript and Web API global objects.

The global object name is implicit, meaning you don't need to enter it to access its properties. Instead just enter the property names directly. 
For example, console is both a Web API and a Node.js core module. 
To access it in the browser you can enter: window.console.log('Hello');
And in Node.js enter: global.console.log('Hello');

But because the global object name is implied, it is common practice to leave it out, just calling the properties directly: console.log('Hello');

You can assign your own variables directly to the global object: 
  • window.username = 'Steve'; in the browser. 
  • global.username = 'Steve'; in Node
  • Or just:
    • username = 'Steve';

Then you can access them directly from the global object:
  • window.username in the browser returns 'Steve'.
  • global.username in Node returns 'Steve'.
  • or just:
    • username; returns 'Steve'.

Assigning variables directly to the global object is considered bad practice, so unless you have a specific reason to do so, it should be avoided. 

This
The keyword this represents the current object that the statement is in.

In the DevTools console if you enter: this 
It will return the object you are in.
Since you are not inside another object you will be in the global scope. So this represents window.
We will cover this in more detail in the Objects tutorial.



JavaScript Built-in Objects

[16:37 Video timestamp]

Most the topics that we will delve into in subsequent tutorials involve built-in objects that are attached to the global object and therefore accessible anywhere in your code.

JavaScript has a set of core built-in objects that are on the global scope. 
They contain properties and methods for working with the specific kind of data.
The major ones we will use have a separate category on the CheatSheet and have their own tutorial in the series. These include:
  • String
  • Number
  • Math
  • Date
  • Boolean
  • RegExp (regular expressions)
  • Function
  • Object
  • Array
  • Promise
  • JSON
  • Error

There are also JavaScript constructs such as variables, operators, conditional statements, loops, and modules.
And there are Web APIs in the Browser outside of the JavaScript engine that you can use in your code to manipulate web pages and other purposes. 

Each of the next tutorials will dive into a specific topic such as one of the core built-in objects, a JavaScript construct, or the Web APIs.


Conclusion

The topics in this tutorial correspond with the JavaScript CheatSheet "General" category. Make sure you understand each topic so you can refer back to the CheatSheet when working on your own projects.

If you have the CheatSheet desktop app and downloaded the JavaScript CheatSheet, then go through the flashcards for this category to the point where you can answer them all in order and shuffled.

Each of the rest of the tutorials focuses on a major JavaScript topic. You don't have to review them in the order presented.
 
The final tutorial is a project. The same To-Do list from the Beginning JavaScript tutorial, upgraded with code from the Intermediate tutorials. 
Open CheatSheet Back To List Next Tutorial