Learning Javascript as a first step to get into coding

It's been a week since I posted about learning to code as a side business and, the more I get into the world of code, the more I like it. It's not that I'm good at it - I'd say I'm fairly ok so far - but more because I am learning so much at a very fast pace. I knew I had to give my all to this project (that is rapidly becoming a life project) in terms of hours spent learning, hours spent watching videos and reading a lot, but mostly because if I want to get proficient at this fast, I have to give it my all and a little bit more.

image.png

I said I would keep a timeline of my learning, both to keep track of how much time I've invested on it, and also to later on write "how long does it take to..." kind of articles, so:

ConceptTime spent
Researching Howto8 hours
Downloading programs2
Learning Javascript19 hours (so far)

I could say 19 hours are enough to keep in a bootcamp I researched about, or at least that's what I thought after I finished the 6 homeworks of the prep course and read all the files, solved all the puzzles and watched all the videos... but when I signed up for the test that would allow me to begin the bootcamp, I realized I was nowhere ready. Out of 16 questions/problems I was only able to answer (or code) 2; I began to get frustrated because apparently the homeworks gave the applicant the tools to solve the test but, as it turns out and after I asked around in the slack, the average time spent studying by an average student in order to pass the test, is 120 hours.

So what I did was sign up to the test on September 24 and right now I am preparing for it, watching YT videos, solving more problems and so on.

By the way, do you know any kind of channel or website where I can learn to apply everything I know about Javascript and perhaps keep learning? So far I've found several channels, the best of them is "Whatsdev" on Youtube but maybe you can recommend me some others.

So, out of my progress, I've compiled a "How to Guide to learning JS basics", and I want to share it with you in case anyone is interested:

JS #3: Conditionals & Control Flow (if Statements, Logical Operators)

If statements are used to check condition, if it is true, it performs a specific action, if it’s not, well, it doesn’t.

Basic example:

var num = 20; // (the variable is called num.)
if (num > 0) {
console.log(“The number is a positive”) // console.log means to print it.
}

Whatever is inside the parenthesis has to evaluate to true for the statement to print.

var num = 20;
if (num > 0) {
console.log(“The number is a positive”)
console.log(“Random statement”) // Will also print because the if is true.
}

Then we can add if statements after that one, but if the first statement is true, then the loop stops there, if the first one is not true, then it keeps checking the next statements.

var num = -4;
if (num > 0) {
console.log(“The number is a positive”)
console.log(“Random statement”)
}
if (num < 0) {
console.log(‘The number is a negative”)
}

But we can also write the same code in a cleaner way by not having the two if statements:

var num = 7;
if (num > 0) {
console.log(“The number is a positive”){
} else {
console.log(“The number is a negative”)
}

But what if the number is a 0? We have to add a statement for that, by combining the statements.

var num = 5;
if (num > 0) {
console.log(“The number is a positive”){
} else if (num < 0) {{
console.log(“The number is a negative”)
} else {
console.log(“The number is a zero”)
}

So, it keeps reading the code and the statements until the statement is true, if the number would be 0, it would keep reading it until the last statement.



Now we want to take this to the next level, to a more interactive way of coding.

If we use alert instead of console.log we get a pop-up with the result of the if statement, the code would look like this and it gives the user a more interactive way of browsing the website.

var num = 14;
if (num > 0) {
alert(“The number is a positive”){
} else if (num < 0) {{
alert(“The number is a negative”)
} else {
alert(“The number is a zero”)
}

Then, we can use the prompt tool to open up a box telling the user they have to enter a number so the code can run, after the user types the number, the pop-up alert will pop on the user’s screen, basically the prompt gives you an input to the user:

var num = prompt(“Enter a number, please!”);
if (num > 0) {
alert(“The number is a positive”){
} else if (num < 0) {{
alert(“The number is a negative”)
} else {
alert(“The number is a zero”)
}



var isRaining = prompt(“Is it raining?”);
if (isRaining === “yes”) { // *
alert(“Go take an umbrella!”);
} else {
alert(“It’s ok. You don’t need anything.2)
}

In here, we are already giving the user answers depending on their input, and we can keep going and going adding if statements.

*Whenever you compound two things, you can’t use one equal sign but two or three.

In Javascript there are two equality operators, the == and the ===, I’ll know what they mean later on but for right now, I’m just using ===. Both are for comparisons or equality checking, one equal sign is for assigning values to a variable.



"" Logical Operators


&& (AND)
|| (OR)
! (NOT)

They are used to combine conditions. We want to be able to add many conditions to the statements so we can have more complex statements.

true && true =0 true
true && false == false
false && true == false
false && false == false

true || true == true
true || false == true
false || true == true
false || false == false

!true == false
!false == true

The next example will make it clear:

var name = “Eric”;
var age = 32;
var collegeDegree = true;

Let’s say Eric is looking for a job at Walmart, and the job requirements are that the applicant is over 25 and to have a college degree.

if (age >= 25 && collegeDegree === true) {
alert(“You are eligible to apply for this job.”)
} else {
alert(“You are not eligible to apply to this job”).

Javascript #4: For Loops

Loops

Loops are to avoid typing things manually way too many times.

In any kind of loop you have three statements:

Initializer - The starting point, where you want your loop to start.
Endpoint - The condition where your loop should end, for how long you want your loop to continue for.
Incrementor or decrementor - The loop continues up or down

Each statement is separated by a semicolon.

for (var i=0;i<=15; i++) { // This could also be written as i+=1
console.log(i);
}

Where i is the name of the variable.
Where <= also includes 15

This loop says, as long as i is less than or equal to 15, keep going.
The loops begins, and then it keeps reading from right to left, checking the result, then running the increment, then checking the condition to see if it still has to run. The loop keeps running until it reaches 15.

The incrementor works as follows:

What is actually happening in every loop is:
i = i +1 // i = 0 + 1 so then, i = 1 ||| Then i is still less than 15, so it runs again
i = i + 1 // i = 1 + 1 so then i = 2
i = i + 1 // i = 2 + 1 so then i = 3
i = i + 1 // i = 3 + 1 so then i = 4

And it keeps doing that until it reaches 15 by asking, is i >= to 15? If it is not, the loop stops.

We don’t really need to print i, it is just for my learning experience.

If I wanted to make the loop have different increments, it would look like this:

for (var exampleOfLoop= 5; exampleOfLoop <= 30exampleOfLoop += 5){
console.log(exampleOfLoop);
}

Check how I changed the ++ for a += because if we remember, the ++ adds only 1 to the starting point variable.

For another example of a working code we have:

We want to add the numbers from one to ten:

var total = 0; // This variable is out of the loop. This total is a collector.
for (var num = 1; num <= 11; num++){
total += num; // We are incrementing by num ( total = total + num )
}

Every single cycle or loop, we are going to add our current number to total, then at the end after it has added all the numbers from one to ten to total, we will print that:

console.log(“The total is: “ + total); // After the loop

As another example, we can use names of anything:

var animals = [“Dog”, “Cat”, “Bird”];
for (var pets = 0; pets < 3; pets++){
console.log(animals[pets]);
}

What we did is not printing the index, but printing the names.
This code will only work for our animals array and it will only print the first 3 because our condition was pets < 3, but we can tweak the code so it logs all the array, no matter how long it is or how many indexes it has by:

var animals = [“Dog”, “Cat”, “Bird”];
for (var pets = 0; pets < animals.length; pets++){
console.log(animals[pets]);

That way we can add more animals and it will print every one of them. That’s why dynamic lengths are so usefukl.

Now we’ll learn how to loop through an object.

var data = {
name: “Eric”
male: true
age: 32
}

for (var element in data) { // I use element, but you can call it anything you want.
console.log(element); // This goes through all of the properties.
}

This code would give the result:

name
male
age

Because the “element” changes every time, it becomes every property, it gives you the three properties.

But if we also want the value and not just the property,

var data = {
name: “Eric”
male: true
age: 32
}

for (var element in data) {
console.log(element, data[element]); // We use the brackets to access each value
}

If I wanted to access the data of only one of the properties, the code would look like this:

var data = {
name: “Eric”
male: true
age: 32
}
console.log(data[“male”) // It goes with quotes, the properties are strings and when you call them, you need to put quotes.

Loops that go from top to bottom:

for (var num = 10 >= ; num--){
console.log(num);
{

Another example:

var total = 0;
for(var num = 100; num >=0; num--){
total += num; // total = total + num (The same but shortcut
}

console.log(total)

This is the loop version to access an object. Objects don’t have index or order, we access them by their properties. This way is easier than the index version but it’s more common to use the indexed version.

Javascript #5: While Loops

For objects we use for loops.

You need an initializer, a condition (for when your loop should end), an incrementor (or decrementor, It is pretty much the same concept as for loops but the syntax is a little different.

Let’s print numbers from 1 to 10:

We have the initializer outside the parentheses:

var num = 0 // The initializer
while (num < 10) { // The condition
console.log(num); // The call of result
num++; // The incrementor
}

Another useful example:

// The point of this code is to add num to sum
var sum = 0 // Where we store the addition of numbers (The final value
var num = 0 // (it could be i) = 0

while (num < 10) // While the value of
sum += num; // This is how we add num to sum
num++;
}
console.log(sum); // The result would be 45

My number starts at 0 (num) and it goes, “if num is less than 10, run everything inside the curly braces”, so it add sum and num, then adds num++ (1), and it keeps reading the condition until it reaches 10, then the condition won’t be true, so the loop stops.

How to loop through Arrrays with while loops

                 This is an array because [ stuff inside with commas ]

var Stuff = [“apple”, 3.2414, 999, true, false, undefined, [“apple”, “ball”, “cat”], 3, 2, “last”];
string numbers booleans another array

var randomStuff = [“apple”, 3.2414, 999, true, false, undefined, [“apple”, “ball”, “cat”], 3, 2, “lastObject”];
console.log(randomStuff)

We run the code and we get
[“apple,
3.414,
999,
true,
false,
undefined,
[“apple”, “ball”, “car”],
3,
2,
“lastObject” ]

Now we want to loop through that, we’ll do:

When we use i we mean index and it goes through all the items of the array

var randomStuff = [“apple”, 3.2414, 999, true, false, undefined, [“apple”, “ball”, “cat”], 3, 2, “lastObject”];

var x = 0;

while (x < randomStuff.length) // this makes it a dynamic length, no matter how many items the array has or if we change it, it will always go through all of them. IT means, as long as its less than randomStuff.length, we want to print the items in randomStuff.

 console.log(x);        // We will print what X is
 x++;           // We have in incrementer because we want X to go up

}

If we run this code, we’ll get:
0
1
2
3
4
5
6
7
8
9

Because x is the beginning of the index and we have 10 items in the array, and the x++ ads one to that x, so we have the index printed out, but we actually want to loop through the array and print the items of the index, so we have to call the array items:

var randomStuff = [“apple”, 3.2414, 999, true, false, undefined, [“apple”, “ball”, “cat”], 3, 2, “lastObject”];
var x = 0;
while (x < randomStuff.length); {
console.log(randomStuff [x]; // we want to access the indexes to access each item in the array
x++;
}

If we run the code, the result would be:

apple
3.2414
9999
true
false
undefined
[“apple”, “ball”, “cat”]
3
2
lastObject

We can also do a backwards loop using the same logic:

var otherStuff= [“apple”, 3.2414, 999, true, false, undefined, [“apple”, “ball”, “cat”], 3, 2, “lastObject”];
var num = otherStuff.length; // We are calling the index “num”. We have ten items on this array, so otherStuff.length counts ten, and it makes the console log below use the num value of ten, but we don’t have an item indexed as 10, we have the last one as 9, because the list begins at 9, remember?
while (num >= 0); {
console.log(otherStuff [num];
num--; // Because we are going down
}

So that code above would give an undefined as the first item. What we have to do is use the length of the otherStuff array minus one:

var otherStuff= [“apple”, 3.2414, 999, true, false, undefined, [“apple”, “ball”, “cat”], 3, 2, “lastObject”];
var num = otherStuff.length -1;
while (num >= 0); {
console.log(otherStuff [num];
num--;
}

The last object is always one less than the length of the array. The “lastObject” lives on the index of 9, not 10. In the example, the index 10 doesn’t exist, that’s why it is undefined.

Let’s make one more example:

var cars = [“lambo”, “bmw”, “tesla”];
var num = 0
while (num < cars.length) { // As long as num is less than cars.length, run the console.log and then it logs lambo at first then it checks the ++ and adds one, so num hits one, so it would log bmw, then num hits 2 and it logs tesla, then num hits three and since 3 is more than the array length, the loop stops.If you don’t have an incrementer the condition will always be true.
console.log(cars[num]);
num++; // If we don’t add this line of code (it’s easy to forget in while loops) we would always get lambo infinitely.
}

When to use the for loop and when to use the while loop

As a general rule of thumb, whenever you know how many times you want to loop for, you want to use for, whenever you don’t know how many times you want to loop or when to stop, you use a while loop.

Javascript #6: Functions

Let’s talk about variables first. We use variables because we can use them several times, example:

var people = [“joe”, “john”...”peter”];

If we need to refer to this array we don’t have to keep writing this array, we just use…

console.log(people)
}

If we need to refer to a person in this array, we…

for (var person of people) {
console.log(person)
}

Functions store specific tasks, they work as variables but in a more complex way. Think of it as variables being nouns and functions being verbs.

Example of a function:

This the function definition:

function catGreeter() { // All the function logic goes inside this parentheses
console.log(“Hey Cat” You are cute!”)
console.log (“Meow”!)
}

Then we invoke, execute, call or run the function.

catGreeter() // This is how we execute the function, calling it

Let’s say we want to make a more personalized function

function specialGreeter(name) { // We can input in the function inside the parentheses using whatever (x, dog, y)
console.log(“Hey ” + name + “! You are cool.”);
}

Then we have to call this function.

specialGreeter(“Eric”)

Functions can also take multiple inputs or parameters:

function adder(a, b, c, d) { // We have 4 parameters
console.log(a + b + c + d)
}

We have four parameters (inputs), so we have to pass in four arguments so they match and the function runs.

adder(3, 2, 1, 4)

When you write a function they are called parameters but when we are passing or calling the function, they are called arguments. # of parameters = # of arguments.

Let’s work with arrays now

We want the next function to loop through the animals and then print it out

function printerArray(arr) { // We can call it anything we want, in this case arr
for (var i = 0, i < arr.length; i++ ) // arr.length because we want to loop through however many items arr has)
console.log(arr[i]); // Goes through each element of arr and prints it out
}
}

We call the function by

printerArray([“cat”, “dog”, “cow”])

The function will print like this:

cat
dog
cow

About the console.log statement

We can also use return (it’s cooler than console.log) to print the results.

function adder (num1, num2) {
return num1 + num2;
}

adder (2, 4)

Both console.log and return do the same thing in this function but when things get busy, the difference is noticeable.

We use return statements in functions because when we use it, the function is actually giving you an output. When we use console.log we call something that doesn’t really require an answer.

Everything is about input and output. A function takes an input and returns an output. If we do console.log it’s because we are not outputing anything with a function, but we are actually just printing something.

In functions we use return

For another example of return

Let’s do a function where we have a problem that takes in two parameters:

    the first is an array, the second one is a number

function doesExist (nums, num) {

}

doesExist([1, 3, 5, 7], 2) // False, because 2 does not exist in the array

But if we use

doesExist([1, 3, 5, 7], 1) // True, because 1 does exist in the array

So now we give the function some logic

function doesExist (nums, num) {
for (var i = 0; i < nums.length; i++) { // nums.length because that’s the array
if (num === nums[i]) === num // if at any point one of the items in the array equals the num, let’s return true;
}
}
return false; // Outside of the loop

}

doesExist([2, 2, 5, 7], 8) // We call the function, outside of the function

What you’re saying is, if at any given loop, the number equals the second parameter (num) then return true, and if the loop is done and it didn’t equal (num exist inside the array), then return false.

H2
H3
H4
3 columns
2 columns
1 column
2 Comments
Ecency