JavaScript Basics

 

Setting up your environment

  1. Install Node.js (Current v14+)

  2. Create a new file cs355-demos/javascript-basics.js

  3. Open it up in your text editor of choice, I recommend Visual Studio Code

  4. Go through each demo, adding the code to javascript-basics.js running each block of code and checking the output to ensure it makes sense.

  5. To run a program in Visual Studio Code, You can go to Run > Run without Debugging or press CTRL + F5

     

  6. [Optional]

    Most of the code in this basic lecture can also be run in a browser, but later demos will use Node.js only APIs that are unavailable in the browser for security reasons. So make sure you can run programs via steps 1-5 first.

    There are also browser only APIs like the DOM, the window object, and fetch that Node.js doesn't have

    The benefit of running code in your browser's interpreter is the convivence of copying and pasting, giving you instant feedback without. To do this in Firefox or Chrome navigate to a page that is not particularly busy. Firefox home or google.com work well.

    In your browser press CTRL + SHIFT + I to open the document inspector, on top should be a tab for Console. Click on that and ignore any of the errors and warnings. This console is a full fledged JavaScript interpreter and you can type JS code into it.

     

    Try it with 1 + 1;

    Note as with most command prompt styled interpreters, the last value returned is always outputted on the screen (which is why we see 2 without using a print statement)

     

    This value will often be undefined when using functions like console.log(); which has no return value, so don't worry about seeing an extra undefined when using a browser. It's a feature of command prompt styled interpreters. If you run a program via a file they should go away.

     

    Additional note: Memory of all variables persist in this environment until you refresh, you will get redeclaration errors if you copy and paste the same code twice. Refresh your browser to fix.

Printing

Primitive Datatypes

JavaScript has 6 basic primitive data types

Number

There are no ints in JavaScript. All numbers are 64-bit floating point numbers, this means you need to be careful when working with decimal numbers.

Whole numbers should be safe as long as you stay within the range of ±2^53−1.

You can use Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER instead.

Strings

Single Quotes and Double Quotes can be used interchangeably.

Template strings to evaluate expressions can be added using Backticks

String.length

All primitives also have an object version instantiable with the new keyword

When we invoke a primitive, the interpreter will automatically coerce it into the object form, that way we can use property/method dot operations on what should be a primitive.

Objects

JavaScript contains non-data structural types that wrap primitives to form complex objects.

The Object is the most basic of these structural types, all other objects are derived from this.

An object is a dictionary styled list of comma separated key : value pairs. Each pair is separated with a colon.

Objects are denoted by a set curly braces.

Keys can be only strings (or Symbols, but we won't be talking about them)

When referencing keys, non-quoted values are treated as strings.

We can also access properties using square braces, this can be useful if you want to use a variable as your key. Because of the previous rule

When referencing keys, non quoted values are treated as strings.

You cannot use the dot operator with a variable, as it is automatically treated as a string.

 

Computed property names

Another way to do this is with computed property names which accept expressions that return strings

Objects are compared by their references

You can add double quotes to your keys, these are equivalent

const

const is short for a constant, they cannot be set to a new value. They must be initialized at declaration.

Regarding objects this does not mean the internals cannot be changed

If you want to prevent an object from changing, you can apply Object.freeze() to make it immutable. Any changes will be silently ignored.

Destructuring Assignment

The destructuring assignment allows the creation of multiple variables using the properties of an existing object

The variables are arranged based on their names, you do not need to pull out properties that you have no use for.

Property value shorthand

If you have a variable and you want to create an object with that variable and are fine using the same property name, a shorthand allows you to omit the colon and duplicate key value definitions. This doesn't work if you need to rename the property.

Function

In JavaScript functions are objects

You will have to run this in a browser to see the properties (or just take my word on this), Node.js prints just the function body when using console.log()

We can define functions in (at least 2 ways)

Function Declaration

A function declaration will be "hoisted" to the top of it's scope.

Function Expression

In contrast a function expression can only be used after it is defined

Function Constructor [reference]

Using the function constructor is more academic and not really used in practice, especially since it uses an evil eval() command under the hood, which prevents it from being run in browsers.

Should work in Node.js, but most browser will block it

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was created.

-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function#Difference_between_Function_constructor_and_function_declaration

Function names

When using a function expression the function name is not used, instead the variable name (functon_05 in this example) is the only way to refer to the function, it is generally good practice to include a function name to describe it, but it is not required.

Anonymous Functions

An anonymous function is a function without a name

These can be used when passing functions to higher-order functions. As an example, the Array's map method takes a function as it's argument and applies that function to every element in the array.

Here we pass in an anonymous function function(x) {return x * x}

This is typically done if we don't plan on needing this function again.

Arrays

Arrays are collections of data, you can mix types inside your array.

Can you get the number 4 to print using this array?

Arrays have a Array.length property and several methods (like Array.map), we will go over a few basic ones now and the rest will be explained as we encounter them.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Appending

Search

If no match is found -1 is returned

Removal

Filter takes a function as it's argument and applies that function to each element in the array, all the values that return a true are returned in a new array. The original array is unchanged.

 

Spread Operator

Arrays have a special operator called the spread operator that effectively removes the braces from an array so that it can be used in functions that take a comma separated list of numbers

Math.max() expects a comma separated list of numbers

Rest Operator

Rest operator is similar, it's usage is inside functions parameters however, the argument becomes an array when used like this.

It's called rest because you can access the rest of the argument list with it, in this scenario the first two variables are removed and the rest are accessed in the array rest. This can possibly be an empty array.

undefined vs null

There is a "7th" primitive that you may encounter called null

The difference between undefined and null is semantic:

undefined is used in the case where a value has not been set yet, it does not convey any information.

null is used in the case where a value has been explicitly set, but the value represents a null, empty, or non-existent reference.

Declaring variables

In JavaScript there are 4 ways to declare a variables types

Block scoped means that a variable can only be accessed within the set of curly braces in which it was defined, in addition let and const only allow variables to be accessed after they've been defined. You will get an error if you try to access it while in this "temporal dead zone".

When a variable is declared with var, if it is used inside a function, the variable is locally scoped, otherwise it becomes a global. In addition it ignores the temporal dead zone rule, instead initializing all variables to undefined.

There are some special edge cases where var can be helpful, but even I rarely encounter them. As for global's you should always avoid them. For this course, use of let and const is recommended and will work for any problem I give you, and personally I'd recommend avoiding var usage.