JavaScript Crash Course

What you need to know to become a JavaScript guru.

JavaScript is one of the most widely used programming languages for web development. It enables interactive elements on websites, supports server-side applications (Node.js), and is essential for modern front-end frameworks. To help you get up to speed, this article provides a crash course in JavaScript, covering everything from the basics to some more advanced concepts.

Note: JavaScript does not require installation—it runs directly in web browsers. All modern browsers support JavaScript by default.

First, let's talk about comments. Comments are extremely useful and provide a wonderful way to document your code. There are 5 main reasons to add comments when writing code:

  1. Explanation: Comments clarify complex logic, helping other developers (and yourself) understand the code's purpose and approach.

  2. Documentation: They provide context about why specific code choices were made, function purposes, and expected inputs/outputs.

  3. Debugging: Comments can mark problematic sections, note known issues, or explain workarounds.

  4. Collaboration: They facilitate easier teamwork by making code more readable and maintainable.

  5. Future Reference: When you return to code months later, comments help you quickly recall your original thinking and implementation strategy.

Good comments explain "why" something is done, not just "what" is happening, which can typically be understood from the code itself. There are two ways to add comments in JavaScript: single-line comments and multi-line comments.

// this is a single line comment
/*
This is a multiline comment
that spans multiple
lines
*/
console.log('Hello World');

//I also like to add comments before functions in a JSDocs format

/*---------- begin function encodeHtml
* @describe encodes html chars that would mess up in a browser
* @param str string - string to encode
* @return str - HTML encoded string
* @usage html=encodeHtml(str);
*/
function encodeHtml(str=''){
    if(len(str)==0):
        return str
    str=str.replace('?','[[!Q!]]')
    str=str.replace('<','<')
    str=str.replace('>','>')
    str=str.replace('"','"')
    str=str.replace('[[!Q!]]','?')
    return str;
}

Next is code syntax. JavaScript is case-sensitive. Like PHP, JavaScript uses semi-colons to separate statements and curly brackets to define code blocks (like functions).

Below is an example of a function called isWindows. Notice the semi-colon and curly brackets. Indentation does NOT matter in JavaScript but JavaScript is case-sensitive.

//---------- begin function isWindows ----------
/*
* @describe returns true if the browser is running on Windows 
* @return boolean
* @usage if(isWindows()){...}
*/
function isWindows(){
    return navigator.userAgent.includes("Windows");
}

Up next are variables. JavaScript has dynamic typing and supports var, let, and const for variable declaration.

// var - function scoped - visible in the function where it was declared. If declared in main then visible to all.
var emp_id = 6548;

function logEmpId(){
    console.log(emp_id);
}
//let - block scoped - visible in the block where it is declared
function calculate(a,b){
    let c=a+b;
    return c;
}
//const - block scoped - cannot be changed once defined
const x=33;
let a=x+44;
console.log(a);
/* 
Summary:
    Use var for variables that need to be function-scoped and can be re-declared.

    Use let for variables that need to be block-scoped and can be re-assigned.

    Use const for variables that need to be block-scoped and should not be re-assigned after declaration.
*/

Now lets look at JavaScript’s text functions. These are worth memorizing as you will likely use them in nearly every script you write.

// Assign a string to a variable
let text = "Hello, World!";

// Case modifications
text.toUpperCase(); // "HELLO, WORLD!"
text.toLowerCase(); // "hello, world!"

// Whitespace handling
text.trim(); // Removes whitespace from both ends
text.trimStart(); // Removes whitespace from the left
text.trimEnd(); // Removes whitespace from the right

// Splitting and joining. Note: split defaults to a space unless specified
let parts = text.split(","); // Splits into array: ["Hello", " World!"]
let joinedText = parts.join(","); // Joins array with separator: "Hello, World!"

// Replacement
text.replace("World", "Python"); // "Hello, Python!"

// Checking string content
text.startsWith("Hello"); // Boolean - checks for starts with
text.endsWith("!"); // Boolean - checks for ends with
text.indexOf("World"); // Returns 7 (index where found)
text.includes("World"); // Returns true (membership check)

//regular expressions
/^\d+$/.test(text); // Boolean - checks for numeric
/^[A-Za-z]+$/.test(text); // Boolean - checks for alpha
/^[A-Za-z0-9]+$/.test(text); // Boolean - checks for alphanumeric

When writing JavaScript you will often need to write conditional code. To do so you will likely use an if statement. Below is an example of an if/else statement. Note the “else if”. In PHP, “else if” is written “elseif”. In Python, “else if” is written elif. In JavaScript it is “else if” with a space in between else and if.

if(x > 10){
    console.log("x is greater than 10");
}
else if(x == 10){
    console.log("x is 10");
}
else{
    console.log("x is less than 10");
}

Loops allow you to iterate through variables, like arrays and objects, that contain multiple elements of data.

// Iterate an array (list in Python)
const fruits = ['apple', 'banana', 'cherry'];
for (let fruit of fruits) {
    console.log(fruit);
}

// Iterate an object (dictionary in JavaScript)
const person = {'name': 'Alice', 'age': 30, 'city': 'New York'};
for (let [key, value] of Object.entries(person)) {
    console.log(`${key}: ${value}`);
}

// Iterate an array of objects (list of dictionaries in Python)
const people = [
    {"name":"bob","age":22},
    {"name":"sam","age":19}
];
for (let person of people) {
    console.log(`Name: ${person['name']}, Age: ${person['age']}`);
}

While loops are also useful at times but BE CAREFUL when writing while loops so that you do not write an infinite loop.

// Simple while loop with counter
let count = 0;
while (count < 5) {
    console.log(`Count is: ${count}`);
    count += 1;
}

// While loop with user input
let response = "";
while (response !== "quit") {
    // In browser JavaScript, we'd use prompt() instead of input()
    response = prompt("Enter a command (type 'quit' to exit): ");
    console.log(`You entered: ${response}`);
}

// This is an example of an infinite loop. This is really BAD.
let b = 0;
while (b < 5) {
    console.log("this is an infinite loop");
}

// This is how to fix the infinite loop above
b = 0;
while (b < 5) {
    console.log("hello again");
    b += 1;
}

As you have seen in earlier examples, Functions are defined with function . Function arguments are defined in parenthesis after the function name.

function greet(name){
    return "Hello, " + name;
}

console.log(greet("Alice"));

Even if you are an incredible coder and never write code that has errors you still need to handle errors, especially if your code allows for user input. For error handling use the try/catch method as shown below. Note that in JavaScript, dividing by zero produces infinity, not an error, so we have to manually throw an error for this case.

let x = 0;
try { 
    // To catch Division by zero, check the value of x
    if (x === 0) {
        throw new Error("Division by zero");
    }
    let result = 10 / x;
    console.log("result = "+result);
} catch (error) {
    console.log(error);
}

JavaScript doesn't have specific error types like ZeroDivisionError or FileNotFoundError. Instead, it uses a general Error object with properties like code to identify specific errors.

Congratulations on making it to the end of this article! Thanks again for reading. Please like and SHARE. 🙂 Note: I also find https://javascript.info/ to be a very useful reference for JavaScript. You may want to check it out also.

Sponsor: I recently bought one of these for my mom to keep the grandkids out of her bedroom when she was away. She absolutely loves it! Check it out. https://www.amazon.com/dp/B0DB1CWPRW?tag=fingerpointfo-20