JavaScript course – ż­·˘k8Ć콢Ěü Kolejna witryna oparta na WordPressie Tue, 03 Oct 2023 13:40:10 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 Part 10 JavaScript course from Beginner to Advanced in 10 blog posts /javascript-course-for-beginners /javascript-course-for-beginners#respond Wed, 10 Nov 2021 13:10:12 +0000 /?p=19249 This is part 10 and the last part of the JavaScript blog post series that will take you from beginner to advanced. Without further ado, let’s get started with the final tutorial.

JavaScript course – table of contents:

  1. JavaScript topics we’ve covered
  2. JavaScript basics and setting up the coding environment
  3. JavaScript best practices
  4. Variables and constants
  5. Basic data types in JavaScript
  6. Loops in programming
  7. Arrays and functions
  8. JavaScript objects
  9. Highly common concepts in JavaScript
  10. Where to go from here?

Wow! You finally made it here! Most people do not follow up on their passions and drop the courses they take after only a few tutorials, and this is only the case if they start acting on it!

JavaScript topics we’ve covered

JavaScript_course

Throughout this JavaScript course we have started from the very basics of JavaScript and moved up our way to pretty advanced concepts.

The first step of getting started with JavaScript was to actually understand why do we learn JavaScript in the first place. There are multiple main reasons why you may want to get started with JavaScript but the most prominent applications of JavaScript are usually in one way or another in web development. JavaScript started as a front end only language and spread to the backend servers and started dominating there as well.

No matter why you are learning JavaScript it is probably a good idea to take a quick look over this JavaScript course again.

This way you can see your progress and see the parts where you understand really well, which may have intimidated you at first, as well as catching the parts that you may have ignored or missed.

JavaScript basics and setting up the coding environment

After seeing why JavaScript is so popular and what you can actually do with it we started out with some Hello world! examples. We set up our coding environment inside Google Chrome, and started using the JavaScript Console to write some code. Initially, the code we wrote started out as really simple and every line we wrote had a simple purpose, without being interconnected to other lines. As the complexity of our code started increasing, we have upgraded our coding environment to Google Chrome Console. With the Console, we started being able to comfortably write multi-line code that started getting gradually more complex advanced over the whole JavaScript course.

JavaScript best practices

Throughout the series we have also incorporated a lot of coding best practices. These best practices make your life easier when you are just starting out, and they even become more valuable when you start working or collaborating with other people. And exactly for that reason, there are even standards and sayings like “All code should look like it is written by one person, no matter how many people have collaborated.” This is exactly why, one of the very first concepts, we have seen was commenting our code. Doing this, not only makes you a better programmer in the future, but it also allows you to have a better coding experience when you are starting out as well.

Variables and constants

Next, we have seen that we can store data in what is called variables and constants. When deciding which one to choose for a new data, we should keep in mind that if we don’t anticipate changing the data, we want to use the “const” keyword. If we think that we will need to modify that value, we then have to use the “let” keyword. These are the current best practices, but we also saw that prior to ES6, the only way to use variables was to declare it with the “var” keyword. After seeing the potential issues caused by the flexibilities that come with the var keyword, in 2015, with the ES6 standard, the new and modern way to write JavaScript became using the “const” and the “let” keywords.

Basic data types in JavaScript

After that we have talked about the basic data types in JavaScript. The main point here is to understand that different data types are good at doing different things. That’s why it is important to understand what kind of data types we’re working with. Later on, we have seen that by using if else statements we can start having control over our code. Starting with those, we learned to partially ignore our code in order to adapt it to certain specific conditions. We learned about different control structures we can use to have more precise control over our code and data. This way, our code could adapt to different inputs with more accurate answers.

Loops in programming

Next, we discovered loops in programming. We saw that with using loops we can start avoiding repeating ourselves in code. This basically allowed us to partially start being DRY. This stands for Don’t Repeat Yourself.

Generally speaking, we do not want to write code more than we have to, to complete the task. Because every time we write more code, we introduce more opportunities for errors in code. It takes more time and effort to write more code, introduces potential errors, it is usually not efficient since now you have to save the same code maybe 10 times. And overall it can significantly decrease the coding experience. This is why starting with the while loops and for loops, we started cutting out potentially repetitive code.

Arrays and functions

We’ve also seen other fundamental concepts, topics and best practices in JavaScript. We have seen that arrays are really good at grouping related data, such as months of the year, some related numbers we need to store and so on. Next, we have seen that functions are really powerful and we can use functions to really modularize our code and have many benefits. Some of those benefits of grouping our functionalities inside different functions are that we create a much more modular, relatively easily testable code. We also significantly decrease our chances of repeating ourselves.

We have seen that there are two main kinds of functions. One of them being pure functions, the other type being impure functions. Generally speaking, whenever we can, we should aim to use pure functions compared to impure functions. This way, the pure functions we write will behave the same way and will give us the same results, no matter where we run the code, or when we run the code.

JavaScript objects

Next, we have seen objects. We learned that objects are good at storing highly associated data that can have many dimensions. We started with the simplest way to create objects and moved our way up to creating blueprints for the objects and then creating multiple objects from that blueprint. Using these blueprints allows us to make sure that the fields in objects follow the same guidelines and have the same fields. This way at the end of the day we can be sure that we have a much more uniform database to work with. It also allowed us to write significantly DRY code.

Highly common concepts in JavaScript

Next up, we have seen highly common concepts and topics in JavaScript. A vast majority of them were based on further optimizing functions, one way or another. By using map and filter methods we were able to skip some for loops and if statements. Using the arrow functions, we were able to vastly decrease the size of our functions. We’ve seen many features in this JavaScript course, including the arrow functions introduced with the ES6 or ES2015, which are the largest recent changes in the JavaScript standards.

Where to go from here?

Depending on what you want to achieve, you can take different routes. If you just wanted to remind yourself the basics of JavaScript because you have to work with it soon, hope this JavaScript course provided you with a comprehensive guide. Maybe you were already good at another language, such as Python, but you also wanted to see JavaScript. If that is the case, I hope I made it relatively easy for you to get started with the syntax and concepts. Or maybe you are just getting started with web development and you knew that JavaScript is pretty popular.

In either case I hope this JavaScript course gave you some value. If you know a friend that would find this series helpful, consider sharing the first tutorial of this series with them, so that they can start with their JavaScript journey as well.

]]>
/javascript-course-for-beginners/feed 0
JavaScript methods and more. Part 9 JavaScript course from Beginner to Advanced in 10 blog posts /javascript-methods /javascript-methods#respond Tue, 09 Nov 2021 13:42:42 +0000 /?p=19223 This is part 9 of the JavaScript blog post series that will take you from beginner to advanced. This time we’ll explore the following topics: JavaScript methods, default parameter values, the Date object in JavaScript and the arrow function. By the end of this series, you will know all the basics you need to know to start coding in JavaScript. If you haven’t read the previous blog post about JavaScript objects you can do it here. Without further ado, let’s get started with the ninth tutorial.

JavaScript methods and more – table of contents:

  1. Default parameter values
  2. The Date object in JavaScript
  3. Map() method
  4. Filter() Method
  5. Arrow function

Until now we have seen many concepts and topics in JavaScript, but there are still some commonly used ones that we did not discover. In this tutorial, we will see what they are all about. The first one is the default parameter values in JavaScript.

Default parameter values

Functions are used extremely commonly in programming, and when something is used this often there are not only frameworks like React that leverage JavaScript functions, but there are even further optimizations developed to even get more out of JavaScript functions. One of the major features we have in functions is called default parameter values. Default parameters allow us to write safer codes that can make safe presumptions about the user input. This also benefits the user by providing them a default setting that can make it easier to choose from their options as well. Let’s see some examples to that.

// assume you are developing a website for a coffee shop
// and most people want to get a medium size americano
// knowing this you want to make it easir for people to
// order their coffee with less hustle
function orderCoffee(typeOfCoffee="americano", sizeOfCoffee="medium", numberOfCoffee=1){
    return (numberOfCoffee + " " + sizeOfCoffee + " size " + typeOfCoffee + " is being prepared. ");
}
console.log("Default order:");
console.log(orderCoffee());
// this way, when an average customer orders online, 
// it will be much easier for them to order their daily coffee
// so much so that they will be able to order it with a single button
// alternatively people can also customize their coffee
// by changing the inputs
console.log("Custom order:");
console.log(orderCoffee("latte", "large", 2));
console.log("Another custom order:");
console.log(orderCoffee("macchiato", "small", 1));
// it is also possible to change only part of the inputs
// and leverage the default parameters 
// for the rest of the input fields
console.log("Partially customized order:");
console.log(orderCoffee("iced coffee"));

Running the code above give us the following output:

javascript_methods

The Date object in JavaScript

The Date object in JavaScript is pretty commonly used, especially in web development. We can use the Date object to perform time-sensitive functions such as changing the display settings to dark mode, light mode or any other mode the user might prefer. We can also use the date information as needed inside the project we are working on. Here are some examples of the Date object in action:

// the first step is to create a date object instance
// we cna do this by writing the following and 
// setting it to a variable or constant of our choice
let today = new Date();
console.log("We are at year: " + today.getFullYear());
console.log("We can also get month in number:");
console.log(today.getMonth());
console.log("Also we can get the hour of the day like this:");
console.log(today.getHours());
console.log("We can also get the exact minutes along with the seconds");
console.log(today.getMinutes());
console.log(today.getSeconds());
// once we have these numbers we can use them as we like
// if we want we can display them or make decisions based on them.
// if we want to display month with a name 
// rather than a number, we can also achieve that
// with the following
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
console.log("We are at the month of " + months[today.getMonth()]);
// what we just did was to create an array to store month names
// and then choose the correct month using an index value
// provided by the .getMonth() method.
// if we wanted to turn on dark mode after 8 pm,
// we could do that with the following code
// one of the first thing we should remember is that
// hours are given in the 24 hour format
// that means 8pm will mean 20 as hours
// we can also use a short hand way 
// and combine the new date object creation
// with the get hours method
let timeOfDay = new Date().getHours();
if (timeOfDay >= 20) {
    console.log("Turning on Dark Mode...");
} else {
    console.log("Do not turn on the Dark Mode");
}
// since current time is over 8pm,
// in this case we expect to get turn on Dark Mode.
// which is also the reuslt we get as we can see from
// the console output.

Running the code above will give us the following console logs:

javascript_methods

Map() method

The map method is a highly useful method that can save you many lines of code, and depending on how you use it can make your code much cleaner. It essentially replaces using a for loop when you use it to loop over an array. Here are some examples to map() method.

// lets create an array we will use for mapping
let someNumbers = [1, 2, 3, 4, 5];
// lets also create the functions we will 
// provide to the map method
function doubleNums(num1){
    return num1 * 2;
}
function squareNums(num1){
    return num1 * num1;
}
function add100(num1){
    return num1 + 100;
}
console.log("Doubled numbers array:");
console.log(someNumbers.map(doubleNums));
console.log("Squared numbers array:");
console.log(someNumbers.map(squareNums));
console.log("100 added to each of the element in the umbers array:");
console.log(someNumbers.map(add100));
// map() method will loop over each of the
// items in a given array and apply the 
// provided function
// note that we do not include paranthesis
// after the function names, this would call the function
// instead we pass the function name, 
// and map() method calls them when it needs to

Running the code above will give us the following console logs:

javascript_methods

Filter() Method

The filter() method, together with the map() method are both pretty common JavaScript methods. They are very similar to the map() method we have just seen. With the map() method we can pass in any function, and that function is being applied to each of the elements in an array. With the filter() method, we will pass in an filter criteria and the filter method will loop over all the items in an array and it will return a new array with only the items that pass the criteria will remain. Let’s see some examples to that:

// lets first create an array 
// to apply the filter() method
let someNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
function checkEven(num1){
    if (num1 % 2 == 0){
        return num1;
    }
}
function checkOdd(num1){
    if (num1 % 2 == 1){
        return num1;
    }
}
function over13(num1){
    if (num1 > 13){
        return num1;
    }
}
function divisibleByFive(num){
    if (num % 5 == 0){
        return num;
    }
}
console.log("Even numbers from the list:");
console.log(someNumbers.filter(checkEven));
console.log("Odd numbers from the list:");
console.log(someNumbers.filter(checkOdd));
console.log("Numbers over 13 from the array:");
console.log(someNumbers.filter(over13));
console.log("Numbers divisible by 5 from the array:");
console.log(someNumbers.filter(divisibleByFive));
Running the code above will give us the following console logs: javascript_methods

Arrow function

Remember when we said that functions are extremely common in and there are many optimizations are made to them to even get more performant or clean code? Well, arrow functions are one of them. Arrow functions are sometimes also referred to as the fat arrow. They essentially provide a much shorter way to write your functions. They are also very commonly used with the JavaScript methods that we have just seen. Let’s see them with some examples:

// JavaScript provides multiple levels of 
// code shortening with arrow functions depending on your exact code
// Essantially the longest way we can write a function is 
// the way we always write them without using the arrow functions
// lets start with an array to apply the arrow functions
let someNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
console.log("Original Array:");
console.log(someNumbers);
// in the previous examples we have applied many functions
// after creating them as regular named functions
// In this example we will apply the exact transformations
// so that you can see the both extremes in code lenght
// double every number in the array:
console.log("Double every number in the array:")
console.log(someNumbers.map(num => num * 2));
// square every number in the array:
console.log("Square every number in the array:")
console.log(someNumbers.map(num => num * num));
// add 100 to every number in the array:
console.log("Add 100 to every number in the array:")
console.log(someNumbers.map(num => num + 100));
// Only keep the even numbers in the array:
console.log("Only keep the even numbers in the array:")
console.log(someNumbers.filter(num => num % 2 == 0));
// Only keep the odd numbers in the array:
console.log("Only keep the odd numbers in the array:")
console.log(someNumbers.filter(num => num % 2 == 1));
// Only keep the numbers that are evenly divisible by 5:
console.log("Only keep the numbers that are evenly divisible by 5:")
console.log(someNumbers.filter(num => num % 5 == 0));
// Only keep the numbers that are over 13:
console.log("Only keep the numbers that are over 13:")
console.log(someNumbers.filter(num => num > 13));

Running the code above will give us the following console logs:

javascript_methods

In the next tutorial we will have an overview of what we have seen and see what is next.

]]>
/javascript-methods/feed 0
JavaScript objects. Part 8 JavaScript course from Beginner to Advanced in 10 blog posts /javascript-objects /javascript-objects#respond Mon, 08 Nov 2021 12:30:41 +0000 /?p=19194 This is part 8 of the JavaScript blog post series that will take you from beginner to advanced. If you haven’t read the previous blog post about JavaScript functions, you can check it here. By the end of this series you will know all the basics you need to know to start coding in JavaScript. Without further ado, let’s get started with the eighth tutorial.

JavaScript objects – table of contents:

  1. JavaScript objects
  2. Object constructor functions

JavaScript objects

JavaScript objects hold an important role. Although it is relatively a large topic it can also be relatively easy to develop an understanding of them. One of the most common ways to understand objects is to think of it as you are re-creating a car in code. We will have two main concepts when we are dealing with objects. They will have properties and methods. Properties are the things that javascript objects have and the methods are the things that objects can perform. Let’s see that with some examples.

// let's define multiple objects to have a better understanding
const plane = {
    numberOfWings: 2, 
    canFly: true, 
    takeOff: function(){return "Plane starts taking off..."},
    land: function(){return "Plane starts landing..."} 
    }
const car = {
    brand: "Tesla",
    isElectric: true,
    numberOfDoors: 4,
    moveForward: function(){return "The car moves forward..."},
    smartSummon: function(){return "The car starts driving itself to you..."}
}
// we can access and console log the properties they have:
console.log("The properties for the plane:");
console.log("Can fly: " + plane.canFly);
console.log("Total number of wings: " + plane.numberOfWings);
// we can also make the plane perform actions
console.log(plane.takeOff());
console.log(plane.land());
// if you take a closer look, you can see that 
// we do not directly console.log the actions inside the methods
// instead we return them from the functions
// and in this case we are console logging them
// this way if we want we can also give the user an alert
// that tells the plane is taking off
alert(plane.takeOff());
// we can also learn about the properties the car has 
// and console log them as well for additional practice
console.log("Is it an electric car? " + car.isElectric);
console.log("What is the brand of the car: " + car.brand);
console.log("How many doors does it have? " + car.numberOfDoors);
console.log(car.smartSummon());
console.log(car.moveForward());

When we run the code above we should get the following output:

javascript_objects javascript_objects

We have just seen two main examples of javascript objects: one with a plane and one with a car. Just like planes and cars have different properties and different things they can do, different objects we create can do different things and have different properties. If you take a closer look you can start seeing a pattern in the way we define objects, properties, and methods.

We start defining objects just like we are defining variables or constants, in this case, it is usually sufficient to use constants when defining javascript objects. But rather than simply assigning that constant to a value, just like we did with regular constants, now we open and close a set of curly braces and essentially provide the data in key-value pairs. Note that defining properties and methods are pretty similar. The main difference is that when defining properties, we assign the names to a value that we will retrieve later on. However, when we define a method, we have to provide a function that we will later on run. This difference is also reflected in how we call them later on. For example:

// when we retrieve a property we do not use brackets at the end
console.log("Can fly: " + plane.canFly);
// when we retrieve methods, 
// we also run them by adding brackets after them
// methods here are essentially functions that 
// belong to a specific object
console.log(plane.takeOff());

It is important that we add the parenthesis after the methods, just like we did with regular functions. Otherwise, we will just have the function itself rather than executing the function.

// in order to execute the object method we should
// add the parenthesis right after the method name
// otherwise we will get the method definition 
// like in this example
alert(plane.takeOff);
javascript_obcject

The displayed result is exactly what we defined while creating the method. You can also see that we are defining a function on the go. In this case we are defining the function without a name, which is possible in JavaScript. This is not always preferable, since giving the function a name makes it more clear when we see it being displayed. In this case however, we are not using the function anywhere else outside the object definition, we do not directly have to give the function a name. Instead, we can refer to the function from within the object with the method name we assign it.

Another thing you should know about retrieving properties or methods from an object is that there is more than one way to achieve that. We used one of the most common practices in the examples above, which is to use dot notation. But there is also another commonly used way of achieving the same result that you should know about. This second notation uses square brackets and quotation marks.

// both of them are equally valid and 
// give us the same results
console.log(plane.numberOfWings);
console.log(plane["numberOfWings"]);
// check out the JavaScript console for the results
javascript_objects

It is great that we can store many detailed properties and actions we can perform using objects, but what if we needed to use objects, not just for 1 car, but let’s say for 20 cars, 100 cars, or even 1,000,000 cars each with a unique ID and varying property values. Would we have to type that whole code from scratch for each car? The answer is no. Instead, we can leverage something called the object constructor function.

Object constructor functions

Object constructors can massively speed up your coding process and can significantly make your code more DRY. With object constructor functions we essentially define a blueprint for the object. Once we have a blueprint for the object, we can create as many of that object instance in a much more clear way, with much less repetition. Let’s see that with some examples.

// this is how we define a blueprint for the objects
function Car(id, color, isElectric, numberOfDoors){
    this.id = id;
    this.color = color;
    this.isElectric = isElectric;
    this.numberOfDoors = numberOfDoors;
}
// this is how we can instanciate the 
// javascript objects we want to create from 
// the blueprint we defined above
// in this case we create 3 car objects 
// with diffent values for the properties
const car1 = new Car(1, "white", true, 4);
const car2 = new Car(2, "black", true, 2);
const car3 = new Car(3, "red", false, 4);
// we can access object properties just like we did before
console.log("Color of first car is: " + car1.color);
console.log("Color of second car is: " + car2.color);
console.log("Color of third car is: " + car3.color);

Running the code above would give us the following code output:

javascript_objects

As you can see from the code above, once we have a blueprint, we can simply pass different values to create different javascript objects from the initial blueprint. One thing you probably noticed is that the naming convention for object constructor is to have the first letter capitalized. In this case, rather than defining it as “car”, we named it “Car”. If we were to create a plane class, we would name it “Plane”.

When we want to create objects from our defined blueprint, we use the keyword “new” and then write the name of the object constructor function we want to use. After the name, we open and close a set of parenthesis and pass in the arguments we want to create our object with. Note that we do not repeat the parameter names, we just pass the values in the same order as the parameters. You may also noticed that when creating the blueprint we are using a keyword called “this”. For now, what you should know is that the “this” keyword allows referring to the object itself, and it is part of the boilerplate code we should write when we are creating the blueprint for the object.

When you are learning to code you may hear the term “boilerplate code”, this is actually pretty common, especially in web development. It basically means that there are parts of code that we write to get certain setups in place. Even though there is not a unique solution we provide with code, we do have to write out those parts to have a functioning code. Depending on the boilerplate code, some IDEs provide even shortcuts for providing those boilerplate codes.

The javascript objects we just learned about are a large topic and have many details as we dive deeper. But at a fundamental level, you should know that we can mimic real-life objects with code using objects. Those javascript objects can have different properties and methods we can access and perform.

In the next tutorial we will discover more topics and concepts that are quite important and commonly used in .

]]>
/javascript-objects/feed 0
JavaScript functions. Part 7 JavaScript course from Beginner to Advanced in 10 blog posts /types-of-javascript-functions /types-of-javascript-functions#respond Thu, 04 Nov 2021 13:56:56 +0000 /?p=19139 This is part 7 of the JavaScript blog post series that will take you from beginner to advanced. By the end of this series you will know all the basics you need to know to start coding in JavaScript. Without further ado, let’s get started with the seventh tutorial.

JavaScript functions – table of contents:

  1. Types of JavaScript functions
  2. Pure functions in JavaScript

Until now we have seen pretty major aspects of JavaScript along with some of the most common coding best practices we should follow. These so called practices are there for a reason and as we use them they will save us a lot of errors and frustration that we would face otherwise. One of the best practices we have seen was to follow the DRY principle, which basically said: Don’t Repeat Yourself. One way we applied this principle was to use loops in our program, more specifically “for loops” saved us a lot of time and code. In this tutorial we will see another major building block in programming, and it is called “functions”.

Types of JavaScript functions

Functions are extremely common in programming, and this includes JavaScript as well. In fact, they are so common that some JavaScript frameworks such as React, was built around leveraging JavaScript functions as a fundamental building block for creating the front end of the websites. And they did this for a good reason. JavaScript functions provide a high flexibility, while providing highly predictable and modular code. And that results in much clear code with less repetitions and much less errors. One of the first things you should know about functions is that there are two main kinds of functions. They are namely “pure functions” and “impure functions”. Generally speaking we will want to use pure functions where we can, as much as possible. Pure functions provide multiple advantages that make them much easier to work with compared to impure functions. Let’s see pure JavaScript functions first and then dive into impure functions as well.

Pure functions in JavaScript

Pure functions are essentially functions that follow certain rules. And because they follow those rules they are highly predictable, easier to debug in a larger system, modular along with some other advantages.

A pure function receives some input and returns and some output. It does not modify the inputs directly or it does not interact with the environment in any other way. That said it does not send you alerts, give you a statement while doing something else, or it does not interact with its environment in any other way.

This way when you are working with a pure function you know that no matter where you are running your code or when you are running your code, as long as you give the same inputs, you will get the same outputs. Let’s see that with some examples.

// double the initial number
function double(num){
    return num * 2;
}
// triple the initial number
function triple(num){
    return num * 3;
}
// add 100 to the initial number
function add100(num){
    return num + 100;
}
// add two numbers
function addTwoNums(num1, num2){
    const sum = num1 + num2;
    return sum;
}
// multiply two numbers
function multiplyTwoNums(num1, num2){
    const total = num1 * num2;
    return total;
}

All of the javascript functions above are pure functions. At a closer look you may have seen the pattern we use when creating pure functions. First step is that we write the keyword “function” to tell JavaScript that we want to define a function.

Next we give the function a name, preferably this name should be short, yet descriptive enough for someone coming along to understand what the function is doing. For example if we are adding 100 to a number, we can name the function as “add100”, if we are doubling a number, we can name the function as “double” and so forth.

Once we named the function appropriately, the next step is to give it some inputs. We provide the inputs inside parentheses and if we have multiple inputs we separate them with a comma. Just like we did at the “multiplyTwoNums” function. (Also, as a side note, numbers are commonly referred to as “nums” for short in programming, so if when we are naming a function we can use that common knowledge to have short yet descriptive function names.)

The inputs we provide to the function are also commonly referred to as “parameters”, when we create the javascript functions we decide how many parameters the function will have. When we decide the use the function we provide those parameters with “values”. Those values we provide when using the function are also commonly referred to as “arguments”. So when we provide an input for the function, this process is also referred to as “passing arguments” to a function. Let’s see some examples of that.

// first let's define the function that takes a number 
// and multiplies it by 10
function multiplyBy10(num1){
    return num1 * 10;
}
// now let's call that function
// save the result into a constant
// and display the results
const bigNum = multiplyBy10(3);
alert(bigNum);
// num1 is here is the parameter.
// we passed the value 3 as an argument to the function.
// we saved the results of the function
// to a constant called bigNum.
// we displayed the constant called bigNum to the user.
pure functions in JavaScript

As you saw in the above code, even when we want to display something to the user, we keep the function separate from the alert function. If we were to display the results to the user inside the function, this would require the function to interact with other parts of the computer and would make our function impure. So generally speaking, we want to use the functions to give them input and expect a returned value. When we get that returned value, then we can actually display it or perform other javascript functions with it depending on our needs, but the point is that keep the concerns of displaying the results and calculating the results separately.

So until now we have seen that we can use the “function” keyword to start declaring the function, then we name the function appropriately, then we open and close parentheses and tell the function the parameters it will require, then we open curly braces and tell the function what we want it to do, once we come to a result we return that result with the “return” keyword. And then we close the curly braces. all of these steps were required to define a pure function. Now that we have a function we can use a function in other parts of our program. Using a function is commonly referred to as “calling a function”.

Calling a function is much simpler than declaring the function. To call a function we can use it’s name, open parentheses, pass it some arguments, and close the parentheses. When we do this, the function will return us the return value that we defined. Depending on what we want to perform with that returned value we can assign it to a variable or a constant, we can perform even more calculations with it, we can send it to other computers, or we can directly display the results as well. Let’s see some examples of that.

// let's start with a function that takes two arguments
// multiplies them and return the result.
// we can either directly return the result,
// or we can temporarily create a constant 
// and return that constant as well.
function multiplyTwoNums(num1, num2) {
    const total = num1 * num2;
    return total;
function multiplyTwoNumsSecondVersion(num1, num2){
    return num1 * num2;
// two functions above will give us the exact same result
const result1 = multiplyTwoNums(3, 5);
const result2 = multiplyTwoNumsSecondVersion(3, 5);
// we can check the equality of the function results 
// with another function
function checkEquality(number1, number2){
    return number1 === number2;
// if the results of both functions are the same,
// the checkEquality function will return "true" 
// as a boolean data type
const isEqual = checkEquality(result1, result2);
// now we can use that boolean value to display a message
if (isEqual){
    alert("Both give the same result!");
} else {
   alert("They are not the same thing!");
}

Running the code above in Chrome Snippets would give us the following result:

javascript_functions

Until now we have worked with pure functions, and this is usually what we aim to code for most of the time. But that does not mean that you will only work with pure functions. Once you have an understanding of the pure functions, impure functions are relatively easier. When we define a function, or declare a function, after using the function name, we actually do not have to pass it any parameters. In that case, we will leave the parentheses empty, we also do not have to return something from the function.

Even more so, since we can write any code inside the curly parentheses of a function we can interact with the outside world, send and receive data, modify existing data, display alerts, and so on. Doing all of this is not prohibited, and adding console.log statements during the code development process can be actually really helpful. That’s why we do not directly stay away from impure functions, but since they can cause a lot of friction and errors in code, including making your code harder to test, we will aim to separate tasks into pure javascript functions as much as possible. Even when we use to make our functions impure by adding alert or console.log statements, we usually want to remove them from our code either by deleting them or commenting them out.

Let’s see some examples of that.

// greet user with an impure function
// it takes no arguments and gives no return
// it also interacts with the outside world by 
// displaying an alert
function greet(){
    alert("Hello User!");
}
// note that the results will not show 
// unless we call the function
greet();
// make some calculations and console log them
function squareNum(num1){
    const result = num1 * num1;
    console.log(result);
}
// this will show the result in the JavaScript console we have below
// The console we just used is highly used in programming
// including in JavaScript.
// console.log statements can be really helpful 
// in telling you what is happening inside your program
// this way if something unexpected happens 
// you can see exactly where and when it happens
squareNum(7);
function multiplyTwoNums(num1, num1){
    console.log("First number is " + num1);
    console.log("Second number is " + num2);
    const result = num1 * num2;
    console.log("The resulting multiplication is " + result);
}
// lets call the function above with two numbers we choose
// and check our JavaScript console for console logs
multiplyTwoNums(5, 7);

Running the code above would result in the following:

javascript_functions

As you can see from the output, we have the alert statement displaying from inside the first function we run. We have the resulting number of 49 logged out in the JavaScript console. Right after that, we have more detailed output in the console about the third function. Making console.log statements is pretty common in programming, depending on the programming language you use the exact name may change, but the idea remains the same. With console.log statements, we can take an inside look into our program and understand our code better. This is especially a useful tool when something goes wrong in your program and you try to figure out where exactly did you make a mistake.

In the next tutorial we will see another important topic in called objects. Before moving on to the next tutorial it is a good idea to review this part once again for the concepts to sink in. I also highly recommend typing the examples we worked on and experiencing them firsthand. When you are ready, we will continue with the objects in JavaScript in the next tutorial.

]]>
/types-of-javascript-functions/feed 0
Java array. Part 6 JavaScript course from Beginner to Advanced in 10 blog posts /java-array /java-array#respond Wed, 03 Nov 2021 14:03:14 +0000 /?p=19105 This is part 6 of the JavaScript blog post series that will take you from beginner to advanced. By the end of this series you will know all the basics you need to know to start coding in JavaScript. Without further ado, let’s get started with the sixth tutorial.

Java array – table of contents:

  1. Arrays – basic information
  2. Adding items to a java array
  3. Removing items from an array
  4. Finding out length in arrays
  5. Sorting arrays
  6. Reversing elements in arrays
  7. For each
  8. Includes in arrays

This tutorial assumes that you have a coding environment already set up. If you have been following the previous tutorials you should already have it open. If for some reason you have closed your setup, you can find the full set up instructions at the Part 4 of these series. In that tutorial we walk through how to set up your Google Chrome Snippets environment for coding.

If you are somewhat comfortable using Google Chrome, here is a quick way to get set up for this tutorial, otherwise you can check out the Part 4 for the full set of step by step instructions on how to set up your coding environment.

If you are on a Mac, the keyboard shortcut to open up the console is to press “Option + Command + J”, after you open up Chrome. If you are using a Windows device, you can use the keyboard shortcut of “Control + Shift + J”, to open up the JavaScript Console, once you open up Chrome. Or you can also go to the menu at the top and go to View -> Developer -> JavaScript Console. Once you Console open, you can click on the “Sources” tab, which is right next to “Console”. Now you show be seeing Snippets. You can either continue coding in a snippet you already started using before, or you can create a new Snipped by clicking on the “+ New snippet” button. As long as you have a coding set up for this tutorial where you can practice, you are good to go.

Java array- basic information

Arrays are highly used in many programming languages and JavaScript is no exception. And it is for a good reason. But you might be wondering what is an array to start with? Arrays are essentially a collection of related data that can be accessed and manipulated with certain defined methods. Let’s see some examples for an array to have a more complete understanding.

const numbersUntilTen = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const testAnswers = [true, true, false, false, true];
const pets = ["dogs", "cats", "birds", "fishes"];

We can use a java array to store multiple different kinds of data. For example, in the code above we have stored some numbers, booleans as well as string data type.

We can create a java array just like creating other variables, with either const or let keywords on the left side and the contents of the arrays on the right side of the equations. One thing you should be paying attention is that when we are creating arrays we use the square brackets to surround the items, just like we did in the code above. We also separate each item with a comma in between, regardless of their data type.

In this tutorial we will write code in a way that you can copy and paste everything in this tutorial, sequentially, or type everything out, into a JavaScript snippet in Chrome, and it would work as expected given that you follow the order. For example, what this means for you is that, if we are defining a variable with the const keyword once in the tutorial, normally you cannot define another variable with the exact same name again. Thats why if you are going to partially copy and paste some of the code, it is a good idea to make sure that you define those variables on your code as well. This should not be an issue if you are following the tutorial in the order it is presented.

One of the first things you should know about a java array is that, once you create an array, you need to access its elements. Arrays have something called “numbered indexes”, and what this means for you in practice is that every element that you create in JavaScript, there is a number that is associated with it from left to right, from zero to the length of the java array minus one.

For example, in the above code for pets, we can access the first element of “dogs” by writing down the name of the variable, open up square brackets, put in the index of the item we want to access and close the square parenthesis:

alert(pets[0]);
java_array

Similarly, putting in higher numbers will trigger displaying other elements in the alert box we are displaying.

alert(pets[1]);
alert(pets[2]);
alert(pets[3]);
java_array java_array java_array

Since we had 4 elements in the pets array, and we started the indexes from 0, the last item in the array is accessed with pets[3], which is 1 less than the total length of the array. At this point you might be wondering, now that we can create an array and access an item from that array, how about making modifications to that array? How about adding new items, changing existing items or deleting items? Well, lets take it step by step and start with adding new items to an array.

Adding items to a java array

There are multiple ways we can add different items to an array. If we know that we want to add the new item to the end of the array, then we can use the “push” method. This is also called pushing a new item into the array. Note that the pushed item will come to the end of the array. For example:

pets.push("snakes");
// lets verify that we have snakes as the last item
// by displaying the array contents
alert(pets);
java_array

If we know that we specifically want to add an item to the java array as the first element we can use the keyword “unshift”. Lets see that with an example:

//running this code will shift all the values
// to one side and will add the first pet of dragon
pets.unshift(“dragons”); 
//lets verify this by displaying the contents of the array
alert(pets);
java_array

It is great that we can add items to the end of the array or to the beginning of the array, but what if for some reason I want to inject items to the array to specific positions. Let’s say I want to add turtles to the third position. Is that even possible? Yes, it is. In order to inject an item to an array we can define it just like creating that part of the array and assigning a value to the specific part of the array. Also do not forget to use the index values while inserting values. From a practical standpoint it looks like this:

pets[2] = "turtles";
// lets verify that we have turtles as the third item
// by displaying the contents of the array
alert(pets);
java_array

Removing items from an array

At this point you might be wondering, how about removing items from an array? Well there are multiple ways for that as well. Probably the most famous one is to use the “pop” method. This will, in a way pop off your last item from an array. // this will remove the last item in the array pets.pop(); // let’s verify the results by displaying the array contents alert(pets); java_array

As you can see, with the pop method, we have removed the last pet item of snakes from our pet array.

Another way you can remove items from a java array is to use the “shift” keyword. When we use shift, the first element will be deleted and the rest of the index values will adapt to them. For example:

// this will delete the first item
// and will shift the other items into their new index values
// which will be one lower than the previous index values
pets.shift();
// let's also verify this by displaying the array
alert(pets);
java_array

The name “shift” actually comes from how the memory allocation works in computer memory. So if it comes relatively unintuitive at first, thats perfectly fine as well. For now you should know that, using the shift method we can remove the first item from an array.

Finding out length in arrays

When we are dealing with arrays in real life there can be alot of times where we want to count the number of array items. This can be needed in a variety of places including in to do lists, participant lists at school or work, and so on. To achieve just that, we have an builtin array property called “length” and it will tell us the total length of the array. For example:

alert(pets.length);
java_array

Sorting arrays

Sorting arrays is a pretty common operation in JavaScript. There are different specific implementations to sorting items in JavaScript. These specific implementations in general are called sorting algorithms. Different sorting algorithms can bring different advantages and disadvantages. For example a sorting algorithm might be chosen over another one because it is simply much easier to implement in code, compared to another one, even though they may show slightly better performance. You may have heard about different sorting algorithms for optimized performance.In this tutorial we will utilize the built in sorting method provided by JavaScript. Sorting is a pretty common problem especially in web development. For example, if you are building an e-commerce website you need to implement different sorting situations for your user to choose from. Although there are no strict rules on what options and capabilities you should provide your audience, there pretty common standards that are expected from you as a website builder. For example, as the user, there is a high chance that you may want to list some store items in both ascending price and descending price. When implementing the sorting for those tasks you should keep in mind how to implement it given that the user can also limit the search results to certain other categories as well, such as t-shirts, hats, bags and so on. We can sort an array by adding “.sort()” to the end of it.

pets.sort();
alert(pets);
java_array

Reversing elements in arrays

Reversing an array is probably more common to combine with sorting. In this case, because we are also executing these codes from top to bottom, we are also applying the reversing after sorting the array. We can reverse and array by adding “.reverse()” to the end of it. pets.reverse(); alert(pets); java_array

Because we have ordered the array in the previous step, you can see that now we have an array that is both sorted and reversed.

For each

When we are working with arrays, JavaScript provides us a convenient way to loop over the array items with “.forEach()”. If we really want to we can still use a regular for loop to loop over an array. In fact lets first see how to construct a for loop to loop over an array, then we will see using forEach().

// this will alert us 4 times to feed our pet
for (let a = 0; a < pets.length; a++) {
    alert("Time to feed my pet");
}
java_array

We can also achieve the same result by using forEach.

pets.forEach(alert("Time to feed my pet"));
java_array

When we compare using for loops or For each, depending on your preferences and your specific situation you may prefer to use one of them over the other. In essence they both achieve the same outputs with different styles in code. ForEach can be relatively easier and save you a line of code to read and write but it will ultimately be your choice. You do not have to make such a choice right now and stick to it either. As you are writing code you can experiment with solving the same problem using different approaches as you are moving in your programming journey.

Includes in arrays

We can also check whether an item exists inside a java array. One example to a real life use of this method would be whether a private event includes a persons name on the invitation list. The actual implementation is pretty straight forward as well. We first write the name of the array, in this case we are working with the pets array. Then we put a dot, to access different array properties and methods, then we write “includes”, then open and close parentheses, and type the name of the item we want to check inside. Here is an example that checks an item we know exists in the array:

alert(pets.includes("dogs"));
java_array

If we also try to same thing with an item we know that does not exists in the java array, we expect to receive false as an answer. Let’s also see that case with an example:

alert(pets.includes("puppy"));
java_array

Since we had no puppy in the pets array, we get false as we expected. In the next tutorial we will see another major concept in both the programming world and in JavaScript.

]]>
/java-array/feed 0
While loops and for loops. Part 5 JavaScript course from Beginner to Advanced in 10 blog posts /while-loops-and-for-loops /while-loops-and-for-loops#respond Fri, 29 Oct 2021 13:48:51 +0000 /?p=19022 This is part 5 of the JavaScript blog post series that will take you from beginner to advanced. By the end of this series you will know all the basics you need to know to start coding in JavaScript. Without further ado, let’s get started with the fifth tutorial.

While loops and for loops – table of contents:

  1. Control Structures (continued)
  2. While loops
  3. For loops

This tutorial assumes that you have followed the 4th tutorial in the series, both in terms of the set up and knowledge wise. We will continue with the setup we have in the 4th tutorial, so if you closed it for some reason you can checkout the previous tutorial for the full step by step instructions. As a result we will have our Google Chrome open, and more specifically the snippets part open to write and execute our code. If you have that ready, you are good to go with this tutorial.

Control Structures (continued)

In the previous tutorial we have seen the use of if, else if and else to control the flow of our code. It is great that we now have more control over our code, but if you notice, we can only execute everything once. For example, if you wanted to say “Hello, there!” ten times, you would need to write 10 different lines of code that says the exact same thing. Isn’t there a better way to achieve this? Do you really need to repeat yourself in code that many times? The answer is no, not at all.

As a programmer you want your code to be DRY. DRY here stands for Don’t Repeat Yourself. Yes, you might occasionally repeat some parts of the code if it makes sense at the time, but as a general goal you should aim to have DRY code. This way most of the times you will have cleaner code with less possibility of errors.

In order to not repeat ourselves in code, we will use loops. More specifically “while loops” and “for loops”. Let’s start with while loops and what it is all about.

While loops

While loops follow a simple logic. And it goes as the following:

Execute the given code inside the parenthesis, while the condition is true.

That said we should also be careful with the code we write with while loops, because if the condition never becomes false, that code inside the paranthesis will run forever unless the execution is stopped. Thats why we will want to implement some kind of change that will trigger the why loop to stop. Let’s see that with an example.

let hungry = true;
while (hungry) {
    alert("Eat food");
    hungry = false;
}
while_loops_and_for_loops

In the example above, we will execute the alert code that tell us to eat only once. This is because at the beginning we set the hungry to true, so we will start executing the code inside the while loop. But while executing the code, one line set the hungry state to false. So after the first execution we now have the hungry state set to false, and in this we know that the while code will not be executed again. Now let’s see another example where the code is executed multiple times.

let targetNumber = 10;
let currentNumber = 0;
while (currentNumber < targetNumber) {
    alert("Hello User!");
    currentNumber++;
}
while_loops_and_for_loops

What do you think will happen with this code? Are going to show the user any alerts? If so, how many alerts are we going to show to user?

If you guessed that we will alert the user 10 times in total, then you guessed it right! If not think again and see if you get it this time. What we do in this code is to start with a currentNumber to track how many times have we displayed the alert to the user. Each time we display the alert to the user we will also increment it by one. The ++ symbol if you remember is used to increment a given number by one. At the beginning we have not yet displayed the user any alerts so we start with zero, and we continue until we reach a display number of 10.

One thing you should pay attention here is that because we are checking for a number smaller than 10, the code inside the parenthesis will not be executed when the current number reaches 10, as it no longer satisfies the condition of being smaller than the targetNumber.

Although we increased the number by one at the end of the each loop, there is no rule that says you can only increase it or decrease it inside a while loop. And this is a major advantage of using while loops. They are used in places where you do not necessarily know how may times are you going to run the code. For example, you can create a game and you can keep a player in the game, as long as they don’t loose the game. During this game session the user can gain points or loose points for an indeterminate time period and you can end the game when they go below a certain point such as zero.

Every now and then there might be also times where you want to run the code inside the parenthesis at least once inside a while loop. For example, imagine a scenario where you first have a snack and they decide whether you are hungry or not. You know that you want to eat somethings but you do not necessarily know for long. In cases like these, we can use a flavour of while loop called “do while loops”.

let reallyHungry = false;
do {
    alert("Eat some food.");
} while (reallyHungry);
while_loops_and_for_loops

In this case even though we were not really hungry we had some food first, and then decided whether to eat more or not. This is something we can do with the do while loops. Note that because we do not have a mechanism to tell the computer when we are full this code would want to run forever if we turned the reallyHungry into true. Thats why it is still a must to implement some kind of stopping mechanism inside our code block. This can be anything from giving hunger a level so that we can increase it or setting it to “true ” somewhere in our code.

While loop is especially great for conditions where we do not know how many times we have to run our code. But there are a lot of times where we do actually know for exactly how many times we should execute a piece of code. For those times we will generally use “For Loops”.

For loops

For loops are very similar to while loops but they have certain characteristics that make them more preferable in many cases. For loops introduces certain boundaries that you have to set from the beginning and these boundaries can make your code safer to run. With for loops we tell the computer exactly how many times we want to run a piece of code. This way we know that our code will not turn into an infinite loop that wants to run forever.

// greet the user 5 times, or 5 users once!
for (let numberGreeted = 0; numberGreeted < 5; numberGreeted++){
    alert("Hello User!");
}
while_loops_and_for_loops

In the code above we greet the user for 5 times. If you take a closer look at for loop, you can see that it is almost a specialized while loop that is more defined and safer to execute. For example, with a while loop we can achieve the exact same output with the following code:

let numberGreeted = 0;
while (numberGreeted < 5) {
    alert("Hello User!");
    numberGreeted++;
}

As you can see, with a for loop we almost carry some parts of the code into inside the parenthesis that defines the for loop conditions. So that we know that the variables we want to use definitely exists, we know that the value we are checking is incremented, and we know that the execution will stop before it reaches the target number.

We have seen that we can start with a number to use inside a for loop and increment it by one. But what if you want to increment it by 5? or what if you actually need to decrement it by one? Could we also achieve those with for loops? Well, yes we can. When defining a for loop, as long as you start with an initial condition and ends with another condition in a controlled way, we have a functioning for loop. For example we can create a count down that starts from 5:

for (let countDown = 5; countDown > 0; countDown--){
    alert(countDown + "!");
}

Note that for decrementing numbers to work we need to start off with the large number in the first place. When we start executing this code, one of the first things that will happen is that we will have a countDown variable created for us, and the value of that variable will be set to number 5. The next step is to check the condition provided regarding the variables. After creating the variable at the initial loop iteration, the iteration rule we place will be applied at the end of every iteration.

In the last example we have set “countDown — ” as the “What will change at the end of every iteration?”. In this case we are decrementing the number one. And before starting each new iteration the condition we set is also checked. The condition we set in the last example was:

“countDown > 0”, which means that this for loop will continue to run the code we provide as long as the countDown variable is greater than 0.

We can also increment the number by more than one, in either positive or negative direction. For example we can start with a small number and increase it a rate we want:

for (let someVariable = 0; someVariable < 15; someVariable = someVariable + 5){
    alert(someVariable);
}

Running this code will result in alerting the user with: 0, 5, and 10.

while_loops_and_for_loops while_loops_and_for_loops while_loops_and_for_loops

These are the main characteristics of for loops. You have just seen the two major loop types, namely the while loop and for loop. Both of them are pretty commonly used both in programming in general and in We will use these loops depending on our needs, so it is important to understand the basics of them. If you think you are somewhat comfortable with these topics, in the next tutorial we will see another major concept in JavaScript.

]]>
/while-loops-and-for-loops/feed 0
Snippets and control structures. Part 4 JavaScript course from Beginner to Advanced in 10 blog posts /snippets-control-structures /snippets-control-structures#respond Thu, 28 Oct 2021 11:42:44 +0000 /?p=18983 This is part 4 of the blog post series that will take you from beginner to advanced. By the end of this series you will know all the basics you need to know to start coding in JavaScript. Without further ado, let’s get started with the fourth tutorial.

Snippets and control structures – table of contents:

  1. Upgrading our coding set up to snippets
  2. Control structures

In this blog post we will continue with where we left from the third blog post. At this stage you should have your Google Chrome browser open and more specifically have your JavaScript console open. If you for some reason closed them, it would be a good time to open them back up.

If you are on a Mac, the keyboard shortcut to open up the console is to press “Option + Command + J”, after you open up Chrome. If you are using a Windows device, you can use the keyboard shortcut of “Control + Shift + J”, to open up the JavaScript Console, once you open up Chrome. Or you can also go to the menu at the top and go to View -> Developer -> JavaScript Console.

Upgrading our coding set up to snippets

Until this point in the course, we could have written everything line by line and executed it line by line. It wouldn’t be the most convenient way to run things, but it would work nonetheless. Starting with this tutorial, we will write code that takes multiple lines of code to create a complete set of instructions. In order to achieve that we will use something called “snippets” in Google Chrome. Without further ado, let’s upgrade our setup from JavaScript console to Chrome snippets.

Currently you should have your console open, and if you followed the previous tutorials you should have a screen that looks like this:

snippets

When you look at this screen, or your screen for that matter, you should see: Elements, Console, Sources, Network, Performance, Memory, Application and so on written next to each other at the top bar of the dark area. If you are seeing them in lighter colors, that’s completely fine too. It means that you are using the light mode, which can be the default mode for day time. The screen that I show currently uses the color scheme for dark mode in Chrome console settings. If you see the Elements, Console, Sources, Network and so on showing up, in either color scheme, you are good to go.

If you take a closer look at the top bar of the console, you can see that the writing of “Console” looks slightly at a different color. Go ahead and click “Sources” right next to it.

snippets snippets

Once you click on sources you should be looking at a screen that somehow looks like this.

One difference you might expect if that you probably won’t see the “notes.js” file, as I have created it previously. Other than that it should look pretty similar to this. To create a new file click on the “+ New snippet”. Once you click on it, it will create a new JavaScript file for you and you can name it however you like. In this tutorial we will name it “index.js” as it is a common practice to name the first or the primary file as “index.js”.

If you want to follow this tutorial word to word, after clicking on “+ New Snippet”, you can enter the name “index.js” and hit the enter key on your keyboard. Now we can click inside the opened file on the major area that opened up, to start coding JavaScript.

Let’s start with something that we already know that works. And that is:

alert("Hello, World!");

You can either write it out yourself for extra practice or copy and paste the code part to the file we created. I highly recommend typing it out yourself as this is how you learn it in many cases. Once you type it, if you hit the enter key, you will see that the code is not executed. Instead your cursor will just go to the next line, as with any other text editing area. There are two main ways we can execute our code. First one is to click on the play button that is located at the bottom right corner.

snippets

If you click on that play button, it should execute our code and display us the results.

snippets

Once you click “OK”, let’s also run our code using the other main way. The second main way to run your code, or run your snippet is to use the keyboard shortcut. As we can see, it already shows us the shortcut when we click on the run button. That keyboard shortcut is “Command + Enter”. To do that, we can press the Command key and then hit the Enter key. Doing that will also run our code and give us the same results as clicking on the play button.

snippets

And with that, now you know the two ways to execute our JavaScript code in the Chrome snippets.

If you want to create new files to maybe takes notes about JavaScript, or to practice some JavaScript code, you can always create new files by clicking the “+ New snippet” and name your files as you like. Now that we have our new coding set up ready, lets see some more JavaScript.

Control structures

When we write code, we have to account for many scenarios and actions the user can take. This preparation for different scenarios can come from different sources such as the device our code runs, screen size to be displayed, different types of browser the user might have and so on. But how do we make sure we can be prepared for different scenarios? If you write different codes one after another, would executing all of them makes sense to the user? To answer all of that and more, we will use control structures.

Control structures allow us to guide the execution of the code, so that our code can adapt to different conditions. There are multiple common elements used for control structures. In this tutorial we will start with the simplest one and move from there. The first one we will see uses If, else, else if statements to control the execution of the code.

If, else and ±đ±ô˛ő±đĚýľ±´Ú

This is the simplest control structure to get started with. What it allows us to do is to execute some piece of code if a certain condition is true, and execute another piece of code if another condition is true. Let’s see that with an example. Let’s assume that, if it rains outside, I will take my umbrella with me. Otherwise, I won’t take an umbrella. We can translate the exact logic and reasoning to code as follows:

(Before writing this code we will comment the code from the previous code we have in the file by placing two forward slashes in front of it, so it does not get executed, but you still have a copy of it. After adding the forward slashes it should look like this:)

// alert("Hello, World!");
let rainy = true;
if (rainy){
   alert("Take an umbrella");
} else {
   alert("No need for an umbrella");
}

Running this code would give us the following output:

control_structures
// alert("Hello, World!");
let rainy = false;
if (rainy){
   alert("Take an umbrella");
} else {
   alert("No need for an umbrella");
}

Whereas running this version of the code that says there is no rain, would give the following output:

control_structures

When you are typing out the code to make changes to the code file, if you take a closer look at the file name, you will see that it will have an asterisk before the file name. This means that the code file we write is not fully saved. This may not make a large difference if you are writing only couple lines of code that you can always write, but more often than not you will want to save your code, so that you can reuse or review it later on. We can save this code file the same way we save other files, so that would be “Command + S” on Mac and “Control + S” on Windows.

control_structures

In our case, because we are executing our code right after writing it, it automatically saved our file when we execute the code. So if you are going to write some code and leave it for hours, it is good idea to save your code every now and then to make sure you are not losing any significant progress.

It is great that we can have our code adapt to a binary condition using an If and an else statement, but what it we have multiple things to consider, which will most likely be the case in real life. For example, what if it is cold and you need to get a hoodie when it is cold. One way we could do that would be an “else if” statement and we can do it as follows:

// alert("Hello, World!");
let rainy = false;
let cold = true;
if (rainy){
   alert("Take an umbrella");
} else if (cold) {
    alert("Get a hoodie with you, not an umbrella");
} else {
   alert("No need for an umbrella");
}

The output of this code would look like this:

control_structures

So if a certain condition is true, the first code that is in between the parentheses will be executed. In our case, since the first condition checks for rain, we will alert the user that they should take an umbrella. If that condition is false, meaning that there is no rain, we will keep checking for other conditions by using an “else if” statement. One thing that is significantly different from the “else if” statement is that, we can check for as many condition as we like with else if statements.

The important thing to remember here is that, your code will be checked from top to bottom, for correctness or trueness. Meaning that with the current code, if the weather is both rainy and cold, it will not recognize the cold weather, since the first statement is correct. We can also verify this by changing the code to have both rainy and cold conditions.

// alert("Hello, World!");
let rainy = true;
let cold = true;
if (rainy){
   alert("Take an umbrella");
} else if (cold) {
    alert("Get a hoodie with you, not an umbrella");
} else {
   alert("No need for an umbrella");
}
control_structures

Now you may be wondering, how can I solve this? Which one is more important, the weather being cold, or being rainy? Should you pick one condition and sacrifice the other condition? Do you even have to make such a choice? Well, not really. This is a very common problem and it has a very common and relatively simple solution. We can use an “and” expression to cover multiple scenarios. To tell JavaScript that we want to use an “and” to connect our programming logic, we will use two of this symbol: “&”. And because our code is checked from top to bottom, we will use the most comprehensive option to the first if statement. The updated code then, looks like this.

// alert("Hello, World!");
let rainy = true;
let cold = true;
if (rainy && cold) {
    alert("Wear a hoodie and take an umbrella with you.")
} else if (rainy){
   alert("Take an umbrella");
} else if (cold) {
    alert("Get a hoodie with you, not an umbrella");
} else {
   alert("No need for an umbrella");
}

Running this code would give you an alert that looks like this:

control_structures

Much better. Now we can combine multiple different scenarios, including different combinations of these scenarios. But what if we want to consider a scenario that is not cold but rainy. And assume that we want to tell the user to not to get a hoodie specifically, and to only get an umbrella. To do just that, we can use the logical “not”, we can use it in our code with the exclamation mark before the condition we want to specify. Let’s add that condition to our code so it is more complete.

// alert("Hello, World!");
let rainy = true;
let cold = true;
if (rainy && cold) {
    alert("Wear a hoodie and take an umbrella with you.")
} else if (rainy && !cold){
   alert("Take an umbrella, but not a hoodie.");
} else if (rainy){
   alert("Take an umbrella");
} else if (cold) {
    alert("Get a hoodie with you, not an umbrella");
} else {
   alert("No need for an umbrella");
}

When we are adding a new condition to an if else tree, as long as it is the more comprehensive condition we can place it somewhere at the top. This way, we have much less chance for errors compared to the opposite approach. One side affect of injecting new code to existing code is that some of the code may become redundant or may not work in the most efficient way. We will not heavily focus on the efficiency part, but for now we can see that we cover both the cold and not cold conditions for a rainy weather, so we can optionally remove the condition that just checks for “rainy” condition. Doing this code adjustments is also called “Code Refactoring”, in the refactoring process the point is the make code incrementally more clean and efficient.

// alert("Hello, World!");
let rainy = true;
let cold = true;
if (rainy && cold) {
    alert("Wear a hoodie and take an umbrella with you.")
} else if (rainy && !cold){
   alert("Take an umbrella, but not a hoodie.");
} else if (cold) {
    alert("Get a hoodie with you, not an umbrella");
} else {
   alert("No need for an umbrella");
}

When we want to check for an either condition to be true, we can use the “or” operator, which is the pipe symbol used twice on your keyboard and looks like this “||”.

Let’s see an example to that with another example. To add more examples to the same file without interfering with the new commands, we can comment out the previous code we used by wrapping the previous code inside these symbols that we have seen before:

/* 
*/

Which is a forward slash an asterisk and the same symbols in the opposite order to close of the commented part. Let’s wrap our current code inside these symbols so that they do not interfere with the new code to be come. Now your code file should look like this:

// alert("Hello, World!");
/*
let rainy = true;
let cold = true;
if (rainy && cold) {
    alert("Wear a hoodie and take an umbrella with you.")
} else if (rainy && !cold){
   alert("Take an umbrella, but not a hoodie.");
} else if (cold) {
    alert("Get a hoodie with you, not an umbrella");
} else {
   alert("No need for an umbrella");
}
*/

From now on we will focus on the new parts we are adding to the file, so that we can focus on learning one thing at a time. You can optionally keep the previous code in the commented mode, move them to a new file for your references, or if you don’t want to see it any longer, you can delete it for a cleaner file.

Let’s continue with our example to an “or” case. Consider a scenario where you visit your fridge for food and drinks every time you feel hungry or thirsty. How would the code work for that?

let hungry = true;
let thirsty = false;
if (hungry || thirsty) {
    alert("Go to the fridge and check what you have in there.");
}

Executing this code, as you also probably have guessed it, would give us the following result:

snippets

Until now the examples we used came from close to real life scenarios, but a lot of the time you will be dealing with numbers in code. You have seen numbers previously in this series, but we did not talk too much about the comparison or the operations we could do with them. Now that we learned about if else statements, let’s see some more about numbers.

When we are dealing with if, and else if statements we are checking for trueness of a statement. But can we also make a meaningful if statement if all we have is numbers? For example, what if I want to get an umbrella if there is more than 50% chance of rain, can we achieve that with code? Yes we can, and here is how it would go.

let chanceOfRain = 70;
if (chanceOfRain >= 50) {
    alert("Get an umbrella.");
}
Snippets and control structures. Part 4 JavaScript course from Beginner to Advanced in 10 blog posts 14 1

When we are dealing with numbers, we need a way to convert it to some kind of trueness or falseness for the if statement to work. There are multiple ways we can achieve that depending on our use case.

For example, we can check if two numbers are exactly equal to each other with three equal signs like this:

let a = 10;
let b = 10;
if (a === b) {
    alert("They are the same.");
}

This would give us the alert that says “They are the same.”.

We can also check for not being equals with the following code:

let a = 10;
let b = 5;
if (a !== b) {
    alert("They are not the same thing!");
}

Running the code above will give us the alert that says “They are not the same thing!”.

We can also check for specifically which one is greater, greater equal, smaller or smaller equal. You can find a summary of the signs for your convenience.

// === checks for equality
// !== checks for not equality
// > greater than
// >= greater than or equal to
// < smaller than
// <= smaller than or equal to

Lets also see couple more of them for extra practice and code exposure. Here are couple of example codes that will all display the alert they have inside the if statements:

Greater than:

let a = 10;
let b = 5;
if (a > b) {
    alert("a is greater than b");
}

Greater than or equal to:

let a = 10; let b = 5; if (a >= b) { alert(“a is greater than or equal to b”); } [/code]

Another example to greater than or equal to:

let a = 10;
let b = 10;
if (a >= b) {
    alert("a is greater than or equal to b");
}

Smaller than:

let a = 5;
let b = 10;
if (a < b) {
    alert("a is smaller than b");
}

Smaller than or equal to:

let a = 5;
let b = 10;
if (a <= b) {
    alert("a is smaller than or equal to b");
}

Another example to smaller than or equal to:

let a = 10;
let b = 10;
if (a <= b) {
    alert("a is smaller than or equal to b");
}

Using a combination of these comparison or equality signs, we can create complex codes that can adapt to different conditions.

Arithmetic operations

When we are dealing with numbers another thing we want to perform is arithmetic operations. Most of the arithmetic operations should be pretty familiar but there are also programming specific arithmetic operators that might be less familiar.

Here is a summary of the arithmetic operations we use in JavaScript with their meaning for your convenience:

// * multiplication
// / division
// + addition
// - subtraction
// % modulo operation, gives us the remainder after division
// ** exponentiation

The first four will work as you expect:

let a = 12;
let b = 5;
let c = a * b;
// c will be 60
c = a / b;
// c will now be 2.4
c = a + b;
// c will now be 17
c = a - b;
// c will now be 7

The modulo operation will give us the remainder after dividing the first number to the second number. If we continue with the previous a, b and c code:

c = a % b;
// c will now be 2
c = 18 % 5;
// c will now have the value of 3
// because 18 divided by 5 will give us the remainder of 3

The exponent operator performs exponentiation in JavaScript. It is represented with two asterisks sign and takes the first element to the power of second element.

c = 2 ** 3;
// c will now have the value of 8
// because 2 * 2 * 2 equals 8

This was a relatively long tutorial, and you made it! We have upgraded our coding setup and learned quite a lot in this tutorial. In the next tutorial, we will continue with more ways to control the flow of our code!

]]>
/snippets-control-structures/feed 0
JavaScript basics. Part 2 JavaScript course from Beginner to Advanced /learn-javascript-basics /learn-javascript-basics#respond Fri, 22 Oct 2021 13:11:40 +0000 /?p=18806 This is the second part of the JavaScript blog post series that will take you from beginner to advanced. By the end of this series you will know all the basics you need to know to start coding in JavaScript. Without further ado, let’s get started with the second tutorial.

JavaScript basics – table of contents:

  1. JavaScript basics
  2. Line by line execution
  3. Two ways to end instructions
  4. Comments

In this blog post we will continue with where we left from the first blog post. At this stage you should have your Google Chrome browser open and more specifically have your JavaScript console open. If you for some reason closed them, it would be a good time to open them back up. Let’s start learning JavaScrip basics

If you are on a Mac, the keyboard shortcut to open up the console is to press “option + command + J”, after you open up Chrome. If you are using a Windows device, you can use the keyboard shortcut of “Control + Shift + J”, to open up the JavaScript Console, once you open up Chrome. Or you can also go to the menu at the top and go to View -> Developer -> JavaScript Console.

JavaScript basics

JavaScript, like all other programming languages, is a language you use to communicate with computers. Like a natural language has grammar and known words to form proper sentences, programming languages also has certain rules you should follow to effectively communicate with the computer.

For example certain words mean certain things to the JavaScript engine that runs our code, such as the “alert” keyword we used in the previous tutorial had meaning of display an alert to the user with the specific words that they put inside the parentheses rigth after. In our case, we wrote “Hello, World!” so we got an alert that said “Hello, World!”.

There are also other reserved keywords in JavaScript that we should be aware of so that we can effectively communicate with the computer using the right words and grammar. Also just like the grammar we have in natural language, there is also a grammar in programming languages. That grammar is commonly called the “syntax” in programming languages and JavaScript is no exception to this. That’s why it is a good idea to understand the main keywords and the grammar we have in JavaScript as we start learning about JavaScript basics. Let’s see some of the main things we should know about JavaScript.

Line by line execution

When it comes to JavaScript basics, one of the first thing you should know ais that the code you write will be executed line by line, from top to bottom. This style of code execution is also referred to as JavaScript being an “interpreted programming language”.

On the contrary some programming languages are “compiled programming languages”. Some examples to compiled languages would be: C, C++, C#, Swift, Java and so on. The main difference is that with compiled programming languages, all the code you write will be “compiled” and will be executed in one piece by the computer. Thats also why it can be harder to start learning a compiled programming language as it can be harder to spot where you made an error in your program.

Some examples to interpreted programming languages would be JavaScript, Python, Bash and Matlab. With interpreted programming languages you have the inherent benefit of seeing what line you made the error, for example forgetting a semicolon or not matching parentheses in your code. Having this characteristic may mot make a large different in certain applications, but when we are trying to load a website with a slow internet connection, you prefer to have every single line of JavaScript to be executed as fast as possible.

Two ways to end instructions

A computer program at the end of the day is a bunch of instructions to the computer. But where does one program ends where does the next instruction starts? There are different approaches to this problem. JavaScript uses two main things, the semicolon and brackets.

Depending on the type of instruction we write, we will generally use either one to end or package a set of instruction. We will use different type of parentheses for different functionalities and data types. For example, in the alert(“Hello, World”); code that we previously executed, the parentheses that surround the hello world writing tells the computer what the alert should say, and the semicolon at the end of the instruction tells the computer that, this instruction ends here, you can move to the next instruction. This is very similar to how we use a period “.” to end the sentences in English.

Comments

Adding comments to the code is an essential part of programming. It may be easy to understand what code you write as you are writing it, but depending on the complexity of the code you may have very little idea six months down the line, when you get back to the code.

Adding comments not only makes it much easier to understand your code for the future you, but it also makes it much easier for anyone that you work with to understand the code as well. It can also help you better develop your understanding about the problem you are working with, since usually it is much easier to solve problems by dividing them into smaller bite size chunks. The commented parts of your code will be ignored by the interpreter and will not be executed.

There are two ways you can add comments is JavaScipt. First one is to add a simple “single line” comment with two forward slashes like this:

// this is a comment

This way whatever you write after the two forward slashes will be ignored on the specific line that you put the forward slashes. You can repeat this as many times to have multiple lines covered with comments like this:

// this is a comment.
// this is another comment.
// you can keep commenting like this.

Another reason why we use comments is to comment out a piece of code to experiment with code. For example you can write the same functionality in multiple ways and you may want to comment one version of the same code to compare their individual performance or results. Let’s see that with an example as well.

Go ahead and copy and paste the following code to your JavaScript console you opened at Chrome.

// greet user
alert("Hello, User!");
alert("Hi, User!");

If you want extra practice writing the whole code yourself you can do that as well. One thing you should know about writing multiple lines of code in the console is that to get to the next line without executing it you can press “shift + enter” to do that. Otherwise after writing a single line of code, if you hit just enter, it will run that line of code. In this example, this is not a big issue and it is actually fine to execute it line by line as well, because we have a simple example that can also work in that style.

After either copying and pasting it or writing the code yourself, go ahead and hit “enter” to run the code. The result should give you two separate alerts. Also to dismiss the alerts you can click “OK”, in this case they wont do anything because this is a simple alert and it does not trigger anything after showing the message we want to display.

javascript_basics javascript_basics

When we executed the code like this, we are executing the same functionality twice. But what should you do if you want to see only one implementation at a time? Well, you know exactly what to do in this case because we already talked about it. Go ahead and comment out one of the lines after pasting or writing out the code so that only the second implementation of “Hi, User!” gets executed.

Once you complete the challenge, or if you get stuck during the challenge you can see the solution code to the challenge below. Before taking a look at the solution, I always highly recommend trying it out yourself as you will learn the best when you really practice it out. If you completed the challenge successfully you should be looking at a screen like this:

javascript_basics

Note that when you comment out a line of code it turns into the same color as the previous commented line. This color difference is here does not actually makes a difference to the computer, but it is a rather helpful feature for us when we are writing code. This way it is much easier if you mistakenly comment out a line of code as the colors will make it obvious.

Another way of commenting code is with the use of the forward slash and the asterisk character. This way we can create single line or multiline comments in our code.

/* a single line comment */
/* the commenting starts when we put a forward slash and an asterisk
and the commented areas ends
when we close of the comment with an asterisk and the forward slash
like this */

Now you know the JavaScript basics. In the next tutorial, we will see an extremely common concept in programming called “variables” along with basic data types in JavaScript.

]]>
/learn-javascript-basics/feed 0
Variables and data types in JavaScript. Part 3 JavaScript course from Beginner to Advanced in 10 blog posts /variables-and-data-types-in-javascript /variables-and-data-types-in-javascript#respond Tue, 26 Oct 2021 12:57:53 +0000 /?p=18855 This is part 3 of the JavaScript blog post series that will help you explore the topic of variables and data types in JavaScript. By the end of this series you will know all the basics you need to know to start coding in JavaScript. Without further ado, let’s get started with the third tutorial.

Variables and data types in JavaScript – table of contents:

  1. Variables
  2. Basic data types in JavaScript

In this blog post we will continue with where we left from the second blog post. At this stage you should have your Google Chrome browser open and more specifically have your JavaScript console open. If you for some reason closed them, it would be a good time to open them back up.

If you are on a Mac, the keyboard shortcut to open up the console is to press “Option + Command + J”, after you open up Chrome. If you are using a Windows device, you can use the keyboard shortcut of “Control + Shift + J”, to open up the JavaScript Console, once you open up Chrome. Or you can also go to the menu at the top and go to View -> Developer -> JavaScript Console.

Variables

Variables in JavaScript or any other programming language are extremely common. And it is for a good reason. Variables have a very critical role in programming. In a nutshell, variables allow you to store some data to move the data around, modify it, update or delete it in your program. It is such an important concept in fact that there are 3 ways you can create variables. The programming lingo for creating variables is called “declaring variables”, which basically means that we are declaring a variable in computers memory.

To create the variables we will use one of the 3 keywords and they are: “var”, “let” and “const”. One of the first things you should know about these 3 keywords is that until 2015, only the “var” keyword was used and the “let” and “const” keywords were introduced with a JavaScript standard called ES6 or ES2015.

If you have no idea what ES6 or ES2015 here is what you should know about it. When JavaScript first came out different companies implemented different versions of JavaScript, and there had to be a standard, for your code to run predictably and reliably in all the major browsers. So an organization called ECMA, (European Computer Manufacturing Association) came up with a set of JavaScript standards that browsers should implement. So that as long as you are following those standards when you are writing JavaScript, your code should run predictably according to those standards. This standard is called EcmaScript and they have been releasing the updated standards since 1997. And since 2015, they have been releasing these standards annually, and hence the latest released standard is called ES2021 as of writing this blog post.

But not all releases are the same, some version differences are not as large, while some introduce pretty major changes to the language. The last major changes happened with ES2015 also called the ES6 as it was the release of the version six of the ECMAScript standardization. One of the significant changes came to the variable declarations.

Before ES6, only the “var” keyword was used and it was the only way to declare variables, hence the name “var”. The var keyword came with flexibilities that could cause unwanted issues. Because it was significantly flexible in use, it was easier to make mistakes with variables if you were less careful than you should be. For example if you declared a variable called “user1”, you cannot re-declare a variable called user1 with the new “let” and “const” kywords, but you could do that with the “var” keyword. And if you forget that you already have a user1 in your program, the second time you declare the user1 with another users information, you would be overriding the actual first user’s information, which would effectively delete the first user’s information.

// this can cause confusion
var user1 = "John";
var user1 = "Jack";
// if you try to do the same thing 
// with let or const you will get an error
let user1 = "John";
let user1 = "Jack";
// likewise you will also get an error
// if you try to do the same thing with the const keyword
const user1 = "John";
const user1 = "Jack";
variables_and_data_types_in_javascript

But it is not like you won’t see the “var” keyword being used anywhere, you will certainly see it especially some beginner level JavaScript courses. Especially if they are couple years old, there are a lot of tutorials that will still show you the old way of writing JavaScript. But the reality is that, it is just not the best practice to use that anymore. Instead, the best practice is to use “let” or “const” keywords when declaring variables, depending on your needs. But what needs are we talking about? In a nutshell, if you are planning to change the value inside a variable you will want to use the “let” keyword, if you know that you won’t change the value in a variable, you will want to go with “const” instead. Let’s see some examples to variable declarations using both let and const.

// we can use "let" when we want to track the game level of the user
// because we know that it will change
let gameLevel = 1;
gameLevel = 2;
gameLevel = 3;
// we can use the "const" keyword when declaring user ID
// because we know that we won't change it
const userId = 1010101999;

If you also noticed from the above code, with the latest best practices, we only write the declaring keywords once, and we do that when we are first declaring the variable. When we want to change the value inside the variable later on, we don’t use any keyword before the variable name.

When we want to access the data that these variables or constants hold, we can simply use their name. For example, If we want to show the user their game level and their user id, we that with the following code:

// we can add the userID to the end of the sentence with a plus sign
// we will explain this later on in the tutorial
alert("Your user ID is: " + userId);
// we can also show the user their game level like the following
alert("Your current game level is: " + gameLevel);
// alternatively we can directly display 
// the contents of the variables by showing them inside an alert
alert(userId);
alert(gameLevel);

Running the last two blocks of code would provide the following outputs:

variables_and_data_types_in_javascript variables_and_data_types_in_javascript variables_and_data_types_in_javascript variables_and_data_types_in_javascript

How to name your variables?

When naming your variables there are certain rules and conventions you should consider. The first consideration is that what characters can use to name your variables? Can they start or end with a number? Is there a common unspoken truth to naming your variables? Let’s answer all of that and more.

Different programming languages have different conventions for naming variables. In JavaScript the convention is to name them with what is called “camel casing”, and goes like this. If the variable name has only one word, then you just write that word in all lowercase. If there are multiple words in the variable name, then you write the first word with all lower caps and you capitalize all the subsequent words and you write them without any spaces or other signs. For example, if we are making a game, we could name the variables as such:

// a single word variable
let strength = 50;
// a descriptive name that includes multiple words
let numberOfArrowsLeft = 145;

On top of using alphabetical characters, we can also use numbers, the dollar sign and the underscore sign in the variable names. It is important to note that you cannot start the variable name with a number, but you can end it with a number.

let some$$ = 100;
let another_$ = 20;
let car1 = "Tesla";

Note that just because it is possible, we don’t want to name our variables with unclear names or with symbols. And that is another topic by itself. When naming variables, the convention is to have clear and descriptive names. For example, if we are going to name a variable to denote how many arrows left in an archers bag, we should use a descriptive name such as the one we used in the example above. If we were to use just:

let x = 145;

This name would tell us nothing about the what value it holds. And even couple days after writing this code we would have to read the surrounding code to understand what that variable might mean. Thats why, both for your own clarity when writing the code, and to your future self who might review the code, it is really important that you get used to naming your variables in a clear and descriptive way. This will also become even more important when you start working with other people and show them your code.

At this point you maybe thinking that: Its great that we can move the data around and can even change it using variables. But what data are we talking about here? Why did we put parts in quotations and some parts are not in quotation? To answer all of that and more, let’s see the basic data types in JavaScript.

Basic data types in JavaScript

Different data types are good at doing different things. In this basic data types in JavaScript tutorial we will see the most basic 3 types of data which are commonly used in JavaScript. Later on in the series we will learn about other data types in JavaScript. Once you learn these first 3 basic data types, it will be much easier to learn the other data types. The 3 data types we will see in this tutorial are: Strings, Numbers and Booleans. Without further ado, let’s start with the first one.

Strings

If you have been following along with the tutorial from the beginning, you already worked with the string data type! When we wrote an alert that said “Hello, World!” that was using the string data type to store the text we wrote. In JavaScript there are 3 ways to represent strings. First one is to surround your text with the double quotation marks. Second one is to surround your text with single quotation marks. And the third one is to surround your text with back ticks. All three of them looks like this:

const string1 = "Some text here.";
const string2 = 'Some text here.';
const string3 = `Some text here.`;

As you can see, the one with the “back ticks” looks pretty similar to single quotation, but it is slightly laid back. The use of back ticks to create strings is a feature that is introduced with ES6, to make it easier to work with textual data. It provides multiple advantages over the previous other two. By convention you may see the either the double quotes or the back ticks being used more often. You can find the back ticks on the left key of number 1, in your keyboard.

Use of double quotes look more familiar and it is easier to understand at the first look, but back ticks come with more advantages overall. In this example all 3 of them function the same way as it is a simple example. To display all three of them at the same time, or even in the same line, one thing we can do is to write their names and use the plus sign in between them, in a way adding the strings to each other.

alert(string1 + string2 + string3);
variables_and_data_types_in_javascript

As you can see all 3 of them are displayed right after one of them ends. This is because just told the interpreter to add the strings to each other. If we want to add spaces in between them we can always add that space with another string.

alert(string1 + " " + string2 + " " + string3);
variables_and_data_types_in_javascript

We can also check the data of a variable by writing “typeof” in front of it. For example:

alert(typeof string1);
variables_and_data_types_in_javascript

Numbers

When we are working with numbers in JavaScript we are generally using the “Number” data type. It is the most simple one to get started with and comes with almost no learning curve.

When type out a number, it is represented in the number type. And if we assign that number to a variable or a constant they will also have the data type of number.

let someNumber = 5;
const score = 90;
alert(typeof someNumber);
alert(typeof score);
variables_and_data_types_in_javascript Variables and data types in JavaScript. Part 3 JavaScript course from Beginner to Advanced in 10 blog posts i 1

On top of regular numbers we have, JavaScript also provides other features that can help us write safer and more predictable code. For example, in JavaScript we can have something called “Infinity”, and it is exactly what it sounds like. Moreover it can be positive infinity and negative infinity. Let’s see what is looks like with an example.

// we can divide by zero and that does not throw an error
// instead it returns Inifinity
alert(13 / 0);
variables_and_data_types_in_javascript
// similarly we can also get negative infinity
alert(-25 / 0);
variables_and_data_types_in_javascript

As you have already seen with couple examples, we can also do arithmetic operations with numbers. From the basic addition, subtraction, multiplication, division to even more programming specific arithmetic operations. We will learn more about them in the next tutorial.

Booleans

Booleans are extremely common in programming. Most of the time we will not explicitly use their names, but we will use their simple property under the hood. A boolean can have two values: “true” and “false” and they are exactly what they sound like. A lot of time you will find yourself writing code to make a comparison and a conclusion based on the result of that comparison.

A lot of the time these comparisons are rooted from real life scenarios, and they follow a simple logic. Is the light on or off? Is there rain outside? Are you hungry? Is this number bigger than the other number? Is this paragraph longer than the next one? Is the user on a large screen?

There are many times where you don’t just want to have a number value or string value to things, but you actually want a yes or no answer. In a nutshell, at those times, we will be using the boolean data type.

// is the first number bigger than the second one
alert(13 > 12);
variables_and_data_types_in_javascript
// check the variable type
let isRainyOutside = true;
alert(typeof isRainyOutside);

Running this code would give us the following output:

variables_and_data_types_in_javascript

Now you know about variables and data types in JavaScript. In the next blog post we will use these data types to start making decisions in our code and so much more!

If you like our content don’t forget to join !

]]>
/variables-and-data-types-in-javascript/feed 0
How to start coding in JavaScript? Part 1 JavaScript course from Beginner to Advanced /start-coding-in-javascript /start-coding-in-javascript#respond Thu, 21 Oct 2021 12:51:23 +0000 /?p=18780 In this series we will go from Beginner to Advanced in JavaScript in 10 blog posts. By the end of this series, you will know all the basics you need to know to start coding in JavaScript.

How to start coding in JavaScript? – table of contents:

  1. Who is this course for?
  2. What can you actually do with JavaScript?
  3. Why JavaScript is so popular?
  4. Where can you write and execute JavaScript code?
  5. How to start coding in JavaScript?

Who is this course for?

This course is for you if you are someone who wants to start coding in JavaScript, or you are someone who wants to refresh their knowledge in JavaScript. I also recommend bookmarking this tutorial for your future reference. Any time you want to have a quick re-introduction regarding the concepts or maybe just to remember the syntax used in JavaScript would be a good time to review this series in the future.

What can you actually do with JavaScript?

Before diving into JavaScript it is a good idea to know what can you actually do with JavaScript. You may know JavaScript as the language that dominates the web. And you would be completely right! JavaScript, started as a front-end language to add behavior to websites, is now used in every aspect of the websites.

It is commonly used in front end web development usually along with other JavaScript frameworks and libraries such as React. It is also the most common language used in the backend web development thanks to Node.js that allows you to run JavaScript on the web servers. But that’s not where it stops at all. JavaScript is used in all kind of places including creating Progressive Web Applications, to desktop apps. It also recently started being used in Machine Learning using TensorFlow.js. Thanks to Node.js again, it can also be used in controlling drones, robots as well as IOT devices. 

Why JavaScript is so popular?

JavaScript is currently the most popular programming language and it is for a good reason. There are multiple main factors that makes JavaScript what it is today. These include wide availability of running environments, code version safety thanks to Babel and wide adoption in the community. Let’s see what they are one at a time.

Wide Availability

JavaScript dominates the web, front to back. If you are reading this article to refresh your JavaScript knowledge you probably know that there are new javascript frameworks popping up every few months, especially regarding front end web development as there can be many approaches to optimizing it. 

As we will see later in the article you don’t need to install any special software to start writing and executing your JavaScript code, because you already have the necessary tools in your browser. This alone lowers the barrier to start learning the language as most programming languages will require you to install and set up coding environments to even get started.

Version Safety

The whole purpose of writing a code is to actually run it when it is supposed to run. And in doing that the last thing you want is to have half of your website not working in a significant amount of users. But what can you do if your code has to run on 1000 different device and browser combination? For who are you going to optimize and who are you gonna let go from being a user? Do you even have to make such a choice? If half of your users have old devices and the other half has brand new devices, who are you going to optimize your code for, and who are you going to ignore as your customer? The answer is, hopefully none, thanks to Babel.

Babel is a software that makes sure your code runs even at the very old browsers that use a very old version of JavaScript. This way you don’t have to make a choice that will lead you to ignore half of your customers. To be clear, you do not write code with Babel, or it is not a flavour of JavaScript. But is an extremely commonly used software that takes your already written and working JavaScript code, and converts it to the version of JavaScript that other browsers understand even if they have very old version of JavaScript in their browsers.

Huge Community Adoption

Whenever you are writing code, it is inevitable that you will come across problems. And at those times, whatever programming language you are working with, it can be extremely helpful to see your problem already being answered by someone helpful on the internet. That’s where the community support steps in, and hence the StackOverflow. 

If you don’t know what StackOverflow is, it is basically the largest programming forum that people use to ask and answer programming questions. It is not the only place where you will find the answers, there are definitely places that will be very helpful in answering your specific questions, but chances are you will find a majority of your answers there. I am not suggesting you to just go to StackOverflow and just search for your problems there either. Usually a Google search will give you the best results. 

And you may not be expecting this as much, while learning to code, but a major part of software development includes knowing what to search on Google to find your answers more effectively. 

That’s why lot’s of people want to start coding in JavaScript – having JavaScript as the most popular programming language definitely helps you work with the language both in the short and the long run. Whenever you are writing

JavaScript, just imagine thousands of people coding JavaScript with you, at the same time. Some posting questions, some answering questions. 

When you are coding JavaScript, you are not alone.

Where can you write and execute JavaScript code?

There are multiple places you can use to start coding in JavaScript. You can technically write JavaScript anywhere, including a simple notebook or text editor. But you also need a JavaScript engine to actually execute your code. But how do you get hold of one. Well, if you remember the beginning of the article, you know that you already have it in your browser. 

In this blog post series we will use Google Chrome as the browser, as it is one of the most common browser used in web development. And it is for a good reason, Chrome provides some of the best tools that makes your life so much easier when performing with web development. Chrome has a JavaScript engine called the V8 Engine, that takes your JavaScript code and executes it. This JavaScript engine is also used in the development of Node.js, the software that allows you to take the JavaScript out of the browser. Node.js is also the reason why we can use JavaScript in all kind of places including from a web server to a drone. 

When you want to start coding in JavaScript it’s good to know that you need a JavaScript engine to execute your code, and now you know that you already have one that comes with your browser. You also know that if you want to run JavaScript out of the browser, you will want to download and install Node.js for that. But when it comes to actually writing the code and executing it, what does it all mean for your coding experience? Usually you will want to use some kind of an IDE (Integrated Development)

Environment) to write your code. This way, as you can guess from the name, it comes with many more tools that makes it easier for you to work with code for the long run. These may include anything from a text completion for less typing, to a debugger. Because a lot of people work with these IDEs there are also very common extensions that allow you to customize your coding environment, including colourizing brackets in the code to make it easier to see which opening parentheses matches with which closing parentheses. If you have no ideas about what parentheses do, for now do not worry about and we will see them with all the details you have to know in these blog series.

Currently some of the most popular IDEs include Visual Studio Code, Atom and Sublime Text. But for this we will start with the simplest option we can start with, which is actually using the Chrome browser itself to write and execute the JavaScript code. 

Now that you have some background information about JavaScript, let’s actually set up our coding environment and start with a “Hello, World!” code.

How to start coding in JavaScript?

In order to start coding in JavaScript we need to set up the coding environment.

As we also mentioned previously, we will be using Google Chrome as our browser throughout this blog post series. If you already have Chrome installed, great! If you don’t, then first step is actually to install Google Chrome. To download Chrome you can simply search for “Google Chrome download”, to download it from its website or here you can find a link for your convenience to download Chrome:

start_coding_in_javascript

Now you can go ahead and click on the “Download Chrome” button to start the download. Once it is downloaded, you can go ahead and double click on it and go through the installation process, as you would with any other application you download from the internet. It may also ask you to sign in to one of your Google accounts, which you can do so.

Once you have Chrome installed, double click on it to open a window. Now you should be looking at the classical Google search screen:

start_coding_in_javascript

In order to start coding in JavaScript the next step is to open up the actual place where we will write and execute the code inside the Chrome browser. From the top menu, Go to: Menu, then Developer, and then click on JavaScript Console. You can also use the shortcut for Mac, which is “option + command + J”.

start_coding_in_javascript

Right after doing that you should see the JavaScript console opening up, which should look something like this:

start_coding_in_javascript

If you made it this far, awesome! It’s time for a meaningful step that will let you start coding in JavaScript. Let’s start your JavaScript journey with a hello world. Go ahead and type the following:

alert("Hello, World!");

After typing that, let’s run our code by pressing “Enter” or “Return” key on your keyboard!

Now you should see an alert popping up that looks like this:

start_coding_in_javascript

And with that, you just wrote your first “hello world” code! Now you know how to start coding in JavaScript.

In the next blog post, you will see the basics of JavaScript with coding examples.

]]>
/start-coding-in-javascript/feed 0