8 JavaScript concepts for beginners with examples

This post will teach you the basics of JavaScript concepts. If you are a beginner you should learn these steps before continuing with intermediate concepts.

1. How to execute your JavaScript code

The most common way JavaScript is executed is through your browser. When the HTML gets downloaded from the server, there will be JavaScript code included in the HTML file. But how do you include your JavaScript code with your HTML documents?

The easiest way to run JavaScript on your website is to include <script> tags inside your HTML like this:

<!DOCTYPE html>
<html>
<head>
    <title>Inline Script</title>
</head>
<body>
    <script>
        console.log('Hello World!');
    </script>
</body>
</html>

This will show Hello World in the browser’s console window when the HTML is loaded. This is not the optimal way. Imagine if you have a big web application. Putting all the JavaScript inside the HTML will get quite messy and you will have a hard time updating and maintaining your application.

Best practice is to move your JavaScript code into different files. This is how that would look:

<!DOCTYPE html>
<html>
<head>
    <title>External JS File</title>
</head>
<body>
    <script src="app.js"></script>
</body>
</html>

And we move the JavaScript code to the app.js file:

console.log('Hello World!');

This way we can organize our app by dividing the JavaScript code into different files. You might have a login.js file which contain all the code for the login page, and you can have another file for the shopping list page.

Notice that we don’t include the <script> tag in the js-file. This is because we already have a script tag in the HTML document with an src attribute which points to the js file.

2. Variables

A variable is a named container where we can store values like numbers, text and other kinds of values.

You can define a variable like this:

let name;

Here we have created a variable called name. Currently, the variable is empty so let us assign a value to it by using the assignment operator =:

name = 'John';

Now we have assigned John to the variable name. We can then use it like this:

let name = 'John';
console.log(name);

The name variable is stored in memory. So we can use it later with the console.log method. Notice that we created the variable name and assigned it to John in one operation.

If you have some experience with JavaScript, you might be thrown off by the let keyword. Older JavaScript code uses the keyword var. The let keyword was introduced in the ES6 version of JavaScript which solves an issue of scoping, which is a topic we will go further into in another article.

3. Data Types

JavaScript consists of different data types. Some of these are:

  • Number
  • String
  • Boolean
  • Arrays
  • Objects
Number

The number type can be either an integer or a float

let integer = 5;
let float = 4.32;
String

You can assign a string variable the following ways:

let firstName = 'John'; // single quotes
let lastName = "Smith" // double quotes;
let greeting = `Hello ${firstName} ${lastName}` // backticks

Unlike numbers, a string has to be surrounded by quotes. You can use both single quotes and double quotes.

Backticks are a feature which came in ES6. Here we can embed variables and other expressions inside of the string using the ${…} syntax. This will print out Hello John Smith.

Boolean

A boolean is a logical type which is either true or false:

isFalse = false;
isTrue = true;
Arrays

Arrays are a list of values. These values can have types like those we have already covered:

let colors = ['red', 'white', 'blue'];
let numbers = [5, 23, 55];
let mixedArrays = [3, "hello", true];

Arrays are defined in square brackets. Notice that an array can contain different types. This might be something you aren’t used to if you are coming from another programming language.

JavaScript is a dynamically typed language. This means a variable implicitly has a type, but you also have the option to change the type later in runtime:

let variable = "Hi";
variable = 26;

This is perfectly legal in JavaScript.

Objects

JavaScript objects are a bit different than the other types. An object often has multiple key-value pairs. For instance, you can have a person object. That person object can contain properties like the person’s name, age, occupation, etc.

The most common way to declare an empty object is like this:

let person = {};

You can then later assign properties like this:

person.name = 'John';
person.age = 28;
person.occupation = 'Developer';

Notice that we use a dot(.) notation, where the left side of the dot is the objects name which we have defined. On the right side is the property name.

We can also assign the properties at the same time as we declare our object like this:

let person = {
    name: 'John',
    age: 28,
    occupation: 'Developer'
}

The properties we can have in our objects are not just limited to simple types. We can have properties with another object. We can even have properties that are functions.

4. Operators

There are quite a lot of operators in JavaScript. Here I will list the most commonly used.

Assignment

This is where you assign a value using the = operator

let result = 5;
Arithmetic

These are your typical math operators where you add, subtracts, etc.

let a = 6;
let b = 3;
a + b; // Addition - returns 9
a - b; // Subtraction - returns 3
a * b; // Multiplication - returns 18
a / b; // Division - returns 2
a % b; // Modulus (remainder after division) - returns 0
String

With the + operator you can concatenate strings

"Hello " + "World"; // Returns "Hello World"
"4" + 5;  // Returns "45";

Beware the last line here. If one of the types is a string, then JavaScript will concatenate them as a string.

Logical

Logical operators determine the logic between different variables or values if the result is true or false.

The OR (||) operator returns true if either of the values is true.

true || false; // Returns true
true || true; // Returns true
false || true; // Returns true
false || false; // Returns false

The AND (&&) operator returns true if both values are true.

true && false; // Returns false
true && true; // Returns true
false && true; // Returns false
false && false; // Returns false

5. Functions

A function is a block of code that performs a specific task. This way you can organize your code into logical chunks which keeps your application readable and easy to maintain. A function can also be reused. If you have logic in multiple places which does the same thing, it is a good practice to create a function and call that function instead of duplicate the code. That way, if you need to change the logic, you only need to change it one place.

Function declaration
function add(a, b) {
    return a + b;
}

You start with the function keyword. Then the name, in this case, add. Lastly, you might have parameters which you later can pass into the function.

Inside the curly braces is where you have the actual logic. Here you can have multiple statements. In our case, we have just a simple return statement which adds our two parameters.

Execute the function

You execute the function by writing the function name and parentheses with the parameters if your function accepts it.

In our add function, we would execute it like this:

let result = add(5, 4); // Returns 9

Here the code will be executed. The addition which is done within the function will be returned to the result variable.

Using anonymous functions

Anonymous functions are simply functions which do not have a name.

let addFunction = function (a, b) {
    return a + b;
}

Here we assign an anonymous function to a variable. Now we are free to execute that function through the addFunction variable any time we choose, like this:

addFunction2(4,5);

6. Commenting

You can add comments to your code to describe or explain what your code does. Comments will be ignored by the browser and will not have any effect on your program.

To comment a single line of code you can use //. For multiline comments /**/ is used.

// This is a single line comment

/* 
    This is how you
    create a comment
    over multiple lines
*/

7. Conditionals

When you are writing code, you want to execute different logic based on a scenario. For example, if you have an animal which is a dog, you might want to do different things than if the animal is a cat.

This is what we call the flow of the application, and can be controlled in different ways:

  • If
  • Else
  • If else
  • Switch statements
How the if statement works
if (animal === "Dog") {
    console.log('Bark');
}

Here we have an if statement. The code within the curly braces will only run if the animal is a dog. Otherwise, the code will continue on the next line after the ending curly brace.

Note that we don’t need the curly braces as long as the executing code inside the if statement only consists of one line of code. But it is considered best practice to use curly braces anyway for consistency and to avoid unexpected behavior.

How the else statement works

If you have an else statement right after the if statement, the else statement will get executed when the if statement is false.

if (animal === "Dog") {
    console.log('Bark');
}
else {
    console.log('Grunt');
}

So in this case, as long as the animal is not a dog, the console will print out Grunt.

How the if else statement works

If your first statement is false, you can have a second if statement. You can do this by having an if else statement.

if (animal === "Dog") {
    console.log('Bark');
}
else if (animal === "Cat") {
    console.log('Purr');
}
else {
    console.log('Grunt');
}

If the animal is not a dog, we do another check if the animal is a cat. If that is false too, the else statement will be executed.

How the switch statement works

The switch statement is another way to steer the flow of your application. Let us look how the last example we did with the animals can get translated to a switch statement.

switch (animal) {
    case "Dog":
        console.log('Bark');
        break;
    case "Cat":
        console.log('Purr');
        break;
    default:
        console.log('Grunt');
        break;
}

This has the exact same functionality as the last if example.

After the switch keyword we take the variable we want to check against. In this case animal.

With the case keyword, we enter a value which we check against the animal variable. If these are the same, we run the code within the current case.

The break keyword will just exit the switch statement altogether. Which means we won’t check further against the other cases.

The default keyword works the same as the else keyword. This means if none of the cases match, the default block of code will be executed.

8. Loops

Often we will need to run a block of code multiple times until it reaches a certain condition.

The “for” loop
for (let i = 1; i <= 10; i++) {
    console.log(i);
}

In this example, we are running the code inside the loop ten times.

The first statement let i = 1 is the initiation of the variable we use in the loop. We start with the value 1.

The second statement is i <= 10. This means as long as the variable i is less or equal to 10, the loop will execute.

The third and last statement i++ means we increment the variable with 1 after each iteration.

After running the for-loop the console will look as follows:

1
2
3
4
5
6
7
8
9
10
The “while” loop

In a while-loop, the loop will continue to iterate while a condition is true. Let us look at an example where we write the numbers 1 to 10 in the console as the last example.

let i = 1;
while (i <= 10) {
    console.log(i);
    i++;
}

Here we set a variable to 1 before the while loop. The condition for the while-loop is that i is less or equal to ten.

Inside the while loop we write the value of i to the console, and then we increment i. The code inside the while-loop will continue to run until i has a higher value than 10.

The “Do…While” loop

This loop is similar to the while-loop. The difference is that we run the code inside the do-block before we evaluate the condition. We usually use this kind of loop if we want to execute the code at least once.

let i = 1;
do {
    console.log(i);
    i++;
} while (i <= 10);

The code inside the do-block will be executed. Then we check the condition. If it is true, we continue with the loop. If it is false, we break out of the loop.

 

Similar Posts