JavaScript Basics - Cheat Sheet

Oct 22, 2022 - 5 minute read | Logan Murphy

Javascript is the programming language of the web. With its move to more system level capabilities through NodeJS and the cross domain libraries available it is quickly becoming the number one programming language in the world to know. It is a great language for quickly prototyping as it is untyped and dynamically executed.

No matter what language you are dealing with, they will all come with their own way to provide comments. Javascript has both inline and multiline comment support.

// This is an inline comment
/*
This is a multiline comment
*/

In Javascript most commands are terminated with a semi-colon.

Storing Data

Javascript has 5 high level usable types. New data can be stored using the var keyword but more modern development uses both let (mutable values) and const (immutable values).

  • Boolean - true or false
  • Number - any real number
  • String - characters
  • Function - invokable procedure with given input and output
  • Object - a group of name value pairs

Additional types to look out for in Javascript are undefined (undeclared value) and null (an intentional empty value). You can also run operations between variables and values.

var boolean = true;
let number = 1.2;
const string = "Hello World";
const object = {
    property : "value"
};
const sum = number + 5;

Conditions

When you have to make a decision in a program the usual approach is to use conditions. In Javascript, the keyword associated with this type of branching logic is if and else. For the checks, you execute the code if the condition evaluates to a truthy value.

const condition = true;
if(condition) {
    // if true, we do
} else {
    // otherwise we do this
}

An alternative approach to if/else statements are switch statements. These give you the power to compare a single value against many others very quickly.

const input = "a";
switch(input) {
    case "a":
        // if input === "a"
        break;
    case "b":
        // if input === "b"
        break;
    case "c":
        // if input === "c"
        break;
}

Arrays

When you need to store a bunch of related data, arrays are the go to data structure to support this. Arrays (also referred to as lists) can be dynamically resized and have their contents changed on a by-index basic. Array indexes, like in many other programming languages, start at 0.

const array = [1, 2, 3];
array[0] = 4; // replaces 1 with 4

Loops

When you find yourself in a situation where you need to do a set of tasks over and over again, loops will be you solution. Loops are commonly used to iterate over the contents of an array but can also be used to calculate complicated math problems. Similar to if/else, loops continue to execute while the condition is true, so you usually have a variable to keep track of where you are in the loop.

const r = [1, 2, 3];
let i = 0;
let sum = 0;
while(i < r.length) { // while true, we do
    sum = sum + r[i];
    i++; // change our tracker (iterator/index)
}

for(let i = 0; i < r.length; i++) { // a while loop can be simplified to a for loop
    sum += r[i]; // adding to the sum variable can look like this as well
}

We can also use break (exit the loop) and continue (go to the next iteration) statements inside of loops to jump around a bit. It is best to use these statements sparingly, if ever. Do loops are another construct that allow you to loop at least once every time.

Functions

Are a way to package reusable code together with a fixed and predictable input and output. Javascript comes with a lot of helpful functions and libraries already built in. The Math, Date, console, and JSON modules are something you will find yourself using quite often.

const max = Math.max(1, 2); // returns the bigger number of the 2
const now = Date.now(); // gets the current timestamp in milliseconds
const json = JSON.stringify("Send this to a JSON API"); // returns a JSON representation of any given value
// an unamed function
const anonymous = function(arg) {
    console.log(arg);
};

anonymous("Hello World"); // prints Hello World

function named(a, b) {
    return a + b;
}

console.log(named(1, 2)); // prints 3

Exceptions

Sometimes things will unexpectedly go wrong with your program. Other times you may want to report that something has gone wrong with your program. This is where errors and error handling comes in handy. Javascript has the ability to both throw and catch exceptions.

try {
    throw new Error("Something went wrong.");
} catch(e) {
    console.log(e); // prints details about the thrown exception
}

Exceptions should not be used to control program flow. They should only be used for when something has gone wrong.

HackingIntoCoding.com © 2024
Logan Murphy