Menü schliessen
Created: November 18th 2021
Last updated: December 10th 2021
Categories: Common Web Development,  IT Development,  JavaScript Development
Author: Tim Fürer

JavaScript Basics: Second Lesson

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Welcome to the second lesson of JavaScript Basics!

If you've missed the previous lesson, check it out first: JavaScript Basics; First Lesson

This lesson, we'll discuss the following topics:

  • Declaring functions using the "function" keyword
  • Comparison and boolean operators
  • If statements
  • Switch statements
  • Debugging

Again, there's a lot to learn this time, so let's get right into it!


Chapter 1: The "function" Keyword

We've already talked about functions such as "alert()" and "console.log()". These are built into JavaScript. The "function" keyword allows you to declare your own functions.

To declare a function, write the "function" keyword followed by a name and a pair of parentheses, and after that, a pair of curly brackets. The rules for function naming are equal to the ones for variables. Inside the parentheses, you can define function parameters (these are optional), and inside the curly brackets belong your function-related scripts.

What are parameters?

Parameters are similar to variables. They have the same naming rules as variables do and have to be comma separated when multiple are declared. Their scope is only effective inside their functions, which generally applies to all variables declared inside functions (I've briefly mentioned this in the previous lesson). Parameters' values get assigned when calling the function.

Function Calls

To call a function, write its name, followed by a pair of parentheses, inside which you can define values that are to be assigned to the function declared parameters, in the same order they're declared in and comma separated as well.

Example

function exampleFunction(firstPart, secondPart)
{
    alert(firstPart + secondPart); // Will alert: "Hello World!"
}

exampleFunction("Hello ", "World!");

 


Chapter 2: Comparison and boolean operators

Comparison operators compare values with another and return either a true or false response.

The following operators are available:

  • Equal to ( == )
  • Not equal to ( != )
  • Equal and same data type to ( === )
  • Not equal or same data type to ( !== )
  • Greater than ( > )
  • Greater than or equal to ( >= )
  • Less than ( < )
  • Less than or equal to ( <= )

Boolean operators allow for boolean algebra and also return either a true or false response.

The following operators are available:

  • And ( && )
  • Or ( || )
  • Not ( ! )

All above-shown operators are generally used with if statements, which we'll take a look at now.


Chapter 3: If Statements

"if" statements are used for creating forks. They are declared with the "if" keyword, after which follow a pair of parenthesis and curly brackets.

The deal with the curly brackets remains the same, it's where the code goes, but the parenthesis on the other hand serve a different purpose this time around. Inside them belong the conditions for the if statement.

Essentially, an "if" statement will only run its code when the return value of what's inside the parenthesis equals true.

Example

if (age >= 18)
{
    // Is adult
}

Else

After an "if", you can follow up with an "else". "else" does not require parenthesis, its condition is to only run its code when the "if" it's related to, fails.

Example

if (name == "John Doe")
{
    // Is named John Doe
}
else
{
    // Isn't named John Doe
}

Else If

This is the combination of the "if" and "else" keyword, where the "if" is directly placed after the "else".

Example

if (favouriteColour == "red")
{
    // Favourite colour is red
}
else if (favouriteColour == "blue")
{
    // Favourite colour is blue
}
else
{
    // Favourite colour is neither red nor blue
}

Chapter 4: Switch Statements

Similar to "if" statements, "switch" statements create forks in code, too. Their strength lies in being able to handle high amounts of forks at great performance and readability, unlike "if" statements, which comparatively would experience strong slow down and read horribly.

At the benefits of speed and looks however, "switch" statements compensate in their complexity regarding conditions. Knowing when to use "if" statements for precise conditioning and when to use "switch" statements for mass-forking is key to performant programming.

To define a "switch" statement, write the "switch" keyword followed by a pair of parenthesis and curly brackets. Inside the parenthesis, define the variable that is to be used as the "switch" statement's condition.

"switch" statements work using jumping. Jumping allows to quickly move to a specific point in code. Those points are referred to as "labels", and these must be named.

A "switch" statement tells JavaScript to jump to a label inside its curly brackets that is named equally to the current value of the condition. This makes "switch" statements fast, because really, there aren't any traditional comparisons done here, yet we're achieving the effect of a fork.

To define a "switch" statement label, inside the curly brackets, write the keyword "case" followed by a value and end it with a colon. If you were to write multiple labels now, each would also execute the code of the labels below itself. Should that not be the intended effect, you can end a label's effective area by jumping to the "switch" statement's end using the "break" keyword.

When no label, equal to the "switch" statement condition's value, is found, the jump resorts to the "default" label, which fittingly is declared using the "default" keyword. The "default" label is optional, though, so if none exists, the "switch" statement instead, jumps to its end like with a "break".

Examples

switch(favouriteColour)
{
    case 'red':
        // Favourite colour is red
        break;
    case 'blue':
        // Favourite colour is blue
        break;
    default:
        // Favourite colour is neither red nor blue
}
switch(colour)
{
    case 'red':
    case 'blue':
    case 'green':
        // Colour is either red, blue, or green.
}

Chapter 5: Debugging

Encountering errors in programming is common and avoiding them is easier said than done. While you're learning to program and get better and better at it, it's useful to acquire and refine your debugging skills. Each bug fixed means another problem learned to solve, and that can help you fix or catch similar mistakes faster and earlier in the future.

The developer console is your friend. If you encounter syntax errors, it will tell you the exact line and reason, and when you need to know a variable's value or if a certain part of code is executed, you can use "console.log()". The console also allows you to set "break points" in your code that, when JavaScript reaches them, pause execution and notify you. You can also run JavaScript directly from it.

Not experiencing any errors in your program during use can be a great sign. However, don't assume because of that that the program is free of them. It is of upper-most importance to thoroughly check every nook and cranny for potential problems, or else, they might surprise you at times you'd be glad you would've already found them.

Once done checking for bugs yourself, it's also a good idea to get someone else to do the same as well. Even if you think you've tested and accounted for every possible scenario, a different person might still find new ones to tackle.


Conclusion

Thus ends the second lesson of JavaScript basics. Next time, we'll take a broad look at user input.

Helpful Resources