JavaScript

The DOM & DOM Manipulation

It’s time to talk about how can we use JavaScript in the browser to make it interact with the web page.

Technical term for that is: DOM Manipulation, which simply means use JavaScript to interact with the webpage.


What is DOM?

  • DOM stands for Document Object Model.
  • It’s a strucured representation of an HTML document.
  • The DOM is used to connect webpages to scripts like JavaScript.
  • We can say that each HTML element (such as section, a, body, img) can be represented by a box.
<body>    
  <section>
  <p>A paragraph with <a>link</a>.</p>
  <p>Another second paragraph.</p>
  </section>
  <section>
  <img src="pig.jpg">
  </section>
</body>
  • The DOM is a fully object-oriented representation, so for each HTML box (such as the body box, section box, img box), there is an object in the DOM that we can access and interact with using our JavaScript code.

JavaScript => DOM
<=
Interation/
Manipulation

They are two different things.

So far we have just used JavaScript without any interaction with the web page, we only printed value to the console. So now we are going to use some JavaScript methods with allow us to change the DOM and therefore interact with the webpage.

Noticed that we said JavaScript “methods” instead of functions?
This means they are functions attached to an object, and that object is exactly the document object.

Document Object is the object that gives us access to the DOM.

Once again, the HTML webpage content is stored in the DOM, which can then be accessed and manipulated by JavaScript.

Standard
JavaScript

JavaScript – ‘this’ keyword

The creation of the execution context has two phases:

  • creation phase
  • execution phase

We are at the last step of the creation phase, which is determining and setting the value of ‘this’ variable.


‘this’ variable is a variable that every execution context gets. It is stored in the execution context object. So what does ‘this’ variable (keyword) point to?

  • In a regular function call: the this keyword points at the global object (in case of the browser is the window object), this is actually the default.
  • In a method call(a function that is attached to an object): the this keyword points to the object that is calling the method.

Note that, ‘this’ keyword is not assigned a value until a function where it is defined is actually called.

Which means even ‘this’ appears in the object where methods are defined, technically, it is only assigned a value as soon as an object calls a method.

That’s because the ‘this’ keyword is attached to an execution context, which is only created as soon as a function is invoked (called).


The ‘this’ keyword in practice.

console.log(this); //window 

This means, ‘this’ keyword in the global execution context refers to the window object. That’s because the window object is the default object.

calculateAge(1995); 

function calculateAge(year) {
console.log(2018 - year);
console.log(this);
}
//23 Window (object)

This is a regular function call, not a method, so ‘this’ keyword points to the global object, which by default is the window object. This actually makes sense, because the object that this function is attached to is the global object.

var john = {   
name: 'john',
yearOfBirth: 1990,
//function expression, not function declaration in objects calculateAge: function() {
  console.log(this);
  }
}

john.calculateAge();
//
{name: "john", yearOfBirth: 1990, calculateAge: ƒ} calculateAge: ƒ () name: "john" yearOfBirth: 1990 __proto__: Object

‘this’ keyword now refers to the object that calls the method, which is john in this case.


Now let’s add a function inside the calculateAge()

var john = {   
name: 'john',
yearOfBirth: 1990,
calculateAge: function() {
console.log(this);
console.log(2018 - this.yearOfBirth);
function innerFunction() {
  console.log(this);
  }
  innerFunction();
}
}
john.calculateAge();

Now when we call the calculateAge method on john object, not only the console.log will place take but also the innerfunction() as we declared and invoke it afterwards.

What ‘this’ is going to be ?

{name: "john", yearOfBirth: 1990, calculateAge: ƒ} 28 Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} 

‘this’ keyword now refers to the window object again, it actually makes sense as in a regular function call, ‘this’ always refers to the global object. (in browser then it refers to the window object)
The method is calculateAge() and although innerFunction() was written inside a method, it is still a regular function.


Method borrowing

Let’s create a new object and borrow john’s calculateFunction() to use it on the object.

var john = {  
name: 'john',
 yearOfBirth: 1990,
calculateAge: function() {
  console.log(this);
  console.log(2018 - this.yearOfBirth);
  }
}

john.calculateAge();

var tom = {
 name: 'Tom',
 yearOfBirth: 1980,
};

tom.calculateAge = john.calculateAge;
tom.calculateAge();

//
{name: "john", yearOfBirth: 1990, calculateAge: ƒ}
28
{name: "Tom", yearOfBirth: 1980, calculateAge: ƒ}
38

Noted that we don’t need () for method borrowing as that will be calling the method, now we simply treat the method here as a variable (property). So tom object now will have a new property which stores calculate();
=> this proves that: ‘this’ variable is only assigned a value, when the object calls the method, if it’s not the case, then ‘this’ variable will always be john object as it is in fact attached in the john object.

Standard
JavaScript

JavaScript – Scope Chain and Scoping

Scope chain is the second step in the execution context creation phase.

What is Scoping?

Scoping answers the question “where can we access a certain variable or function?”

In JavaScript, each new function creates a scope: the space/environment, in which the variables that it defines are accessible. In some programming languages, scope can also be created by if/for/while blocks, but not in JavaScript.

In JavaScript, the only way to create a new scope is to write a new function.

Lexical scoping: a function that is lexically within another function (written in another function) gets access to the scope of the outer function (aka parent function).
Lexical just means where something is written in the code, so it’s about the position of something within our code. It also gets access to variables and functions that the parent function defines.

Global Scope: scope that is accessible from everywhere, all functions.

  • Global Scope [VOglobal]
var a = 'Hello!';
first();

function first() {
  var b = 'Hi!';
  second();

  function second() {
  var c = 'Hey!';
  console.log(a + b + c);
  }  
}

Just like the global execution context, we can think of the global scope as the default scope. So in this scope, we have access to variable ‘a’ as well as the first function.

  • first() scope [VO1] + [VOglobal]
var b = 'Hi!';    
second();

function second() {
  var c = 'Hey!';
  console.log(a + b + c);
}

Here we have the scope of first function where defines variable b and the second function, and this is a local scope, not global scope. Remember lexical scoping? Thanks to lexical scope, this scope also has access to its parent scope as well as the variables and functions that it defined, which in this case is the parent scope.

Lastly, the scope of the second function. In there we have a console.log statement which attempt to print our a, b and c.

second() scope [VO2] + [VO1] + [VOGlobal]
var c = 'Hey!';        
console.log(a + b + c);

These variables are not defined in this function except for c, but as mentioned before, a scope has access to another scope of the function where it sits lexically.

When we run the code, the JavaScript engine will not find variable b in this current scope, so it will go up to the scope of its parent function and uses b, the same happens for variable a, it will go up even until the parent scope.

This is what we refer to as the scope chain.

Only if the JavaScript Engine cannot find the variable anywhere, then it throws an error and stops execution.

It’s important to note that this does not work backwards.

This means the global scope will never ever have access to variable c or b, unless we return the values from the functions. Thus, locally scoped variables are not visible to their parent scope.

How does this work behind the scenes?

Remember the execution context object?
In the creation phase, each execution context object will get an exact scope chain, which is basically all the variable objects that this execution context has access to. Because the variable object is what stored all the defined variables and functions. So in this example, in the second scope, we have access to the variable object of the second function, the first function and the global variable object.

Let’s see some examples.

var a = 'Hello!';
first();

function first() {
  var b = 'Hi!';
  second();
 
  function second() {
  var c = 'Hey!';
  console.log(a + b + c);
  }
}
//Hello!Hi!Hey!

Why does this work?
–> because of the scoping chain.
Thanks to the scoping chain, the second() has access to the variable of the first() and the variable of the global scope.

This is becuase second() is written inside the first() which in turn is written inside of the global scope. That’s why we call it lexical scoping.


Let’s related all these concepts.

Execution stack vs. scope chain

We know that the scope chain for each execution context is stored in execution context object. However, it’s important to note that the execution stack is different from the scope chain.
When a function is called, a new execution context is put on top of the execution stack.

Scope chain is a little bit different.
The global scope contains the a variable as well as the first() and third(), then the scope of the first() contains second().

Basically, execution stack is the order in which functions are called.

But, scope chain is the order in which functions are written lexically.

(the order in which functions are written in our code).

So the order in which function is called does not determine the scope of the variables within these functions.
What determines the scope of the variable, is

where the functions are written.

Since the third() is not in the scope of the second(), of course it cannot access variables b and c, it can only access the global variable a because the function is written in the global scope.
Therefore its execution context that stores the scope chain of each function in a variable object, but they do not have an effect on the scope chain itself.

var a = 'Hello!';
first();

function first() {
  var b = 'Hi!';
  second();
  function second() {
  var c = 'Hey!';
  third()
  }
}

function third() {
  var d = 'John';
  console.log(c);
}

What will happen in this case?

In the global scope we have a variable a, function first() and function third() all in the global scope, or in the global execution context.

Inside the function first(), we have b variable and second function call and the function second(), due to hoisting, we can call the second() before its declared below.

Uncaught ReferenceError: c is not defined    
  • Why can second() even call third() ?
    Due to scoping. The second() has access to third() becuase of the scope chain.
  • Why we got this error even though it was second() who called third()?
    The order in which the functions are called does not matter, what matter is that function third() is in a different scope than second() so it cannot access variable c. It can only access variable a & d.
Standard
JavaScript

JavaScript – Execution Contexts in Detail: Creation, Execution Phases and Hoisting

MacBook on table near mug

As mentioned in the previous note, we can associate an execution context with an object: execution context object.

This object has three properties:
(Recap: properties are variables stored in objects)

  • Variable Object(VO): a special object contains  function arguments/ parameters, inner variable, and function declarations.
  • Scope chain: contains the current variable object as well as the variable objects of all its parents.
  • “this” variable

 


How is the execution context actually created?

When a function is called, the execution context is put on top of the execution stack, this happens in two phases.

  1. Creation Phase
  • Creation of the Variable Object(VO)
  • Creation of the scope chain
  • Determine value of the ‘this’ variable. (the ‘this’ variable is determined and set)

So basically, the three properties of the execution context object are defined.

Then in the execution phase, the code in the function that generated the current execution context is ran line by line. And all the variable are defined. If it’s the global context, then it’s the global code that is executed.


Variable Object (VO)

  • In the creation of the variable object, the argument object is created, containing all the arguments that were passed into the function.
  • Code is scanned for function declarations: for each function, a property is created in the Variable Object, pointing to the function.
    -> this means, all the functions will be stored inside the Variable Object, even before the code start executing. This is important!!
  • Lastly, the code is scanned for variable declarations: for each variable, a property is created in the Variable Object, and set to undefined.
    The final two points are commonly referred to Hoisting.

Hoisting: functions and variables are hoisted in JavaScript which means that they are available before the execution phase even starts.

However, they are hoisted in different ways though, the difference between functions and variables is that functions are actually already defined before the execution starts while variables are set to undefined.
And will only be defined in the execution phase.

The execution phase takes place right after the creation phase.

Recap: each execution context has an object which stores many important data that the functions will use while it’s running, and this takes place even before the code is executed.

 


Hoisting for Functions

Let’s write some simple functions.

function calculateAge(year){
  console.log(2018 - year);
}

calculateAge(2000);
//16

We’ve been declaring and calling functions like this, however, there exists another ways.

calculateAge(2000);

function calculateAge(year){
  console.log(2018 - year);
}

//16

This is actually Hoisting.

In the creation phase of the execution context, which in this case is the global execution context, the function declaration calculateAge is stored in the Variable Object and even before the code is executed.

This is why when we then enter the execution phase, the calculateAge() function is already ready for us to use. So that’s why we don’t need to first declare and then use it but we can first use it and only later in our code, declare it.

This only works for function declarations.

Remember Function expressions?

  1. declare a variable
  2. assign the function to it
var calRetirement = function(year) {
  console.log(65 - (2018 - year));
}

calRetirement(2000);
//47 yrs left for retirement

What will happen if we call the function before the function expression?

calRetirement(2000);

var calRetirement = function(year) {
  console.log(65 - (2018 - year));
}
//Uncaught TypeError: calRetirement is not a function

This is because hoisting only works for function declarations.


Hoisting for Variables

var age = 23;
console.log(age);

//23

What will happen if we use the variable before declaring it ?

console.log(age);
var age = 23;

//undefined

This is exactly how hoisting works with variables.
In the creation phase of the variable object, the code is scanned for variable declarations and then the variable is then set to undefined.

console.log(age);
// Uncaught ReferenceError: age is not defined

In this case, JavaScript does not even know this variable.

But in the case below, JavaScript knows that there will be an age variable, simply don’t have the value yet. And that’s also the reason why it is defined as undefined. (Variable does not have a value yet will always have a data type undefined)

console.log(age);
var age = 23;

//undefined

One more example:

console.log(age);
var age = 23;

function foo() {
  var age = 60;
  console.log(age);
}

foo();
console.log(age);

//
undefined
60
23

Why would this happen?

var age = 23;

The age variable is stored in the global execution context object, (to be more precise: is stored in the variable object of the global execution context object)

So this variable is declared in the global execution context object.

The foo function gets its own execution context object in which we can also store an age variable in the variable object with the same name as there are completely two different variables.

function foo() {
  var age = 60;
  console.log(age);
}

the age variable above is defined in the variable object of the execution context object of the function foo(), while

var age = 23;

is defined in the variable object of the global execution context object.

Each execution context object gets its own variable object so we have two different variables and when we print it to the console, the results are different.

 


Please note that this is my study notes that I took while taking the complete guide to JavaScript course on Udemy, if you are interested in understanding the language better, I highly recommend you to purchase the course 🙂 !

Standard
JavaScript

JavaScript – Execution Contexts and the Execution Stack

 

Execution Contexts

All JavaScript code needs to run in an environment, and these environments are called execution contexts.

We can think of execution contexts as a box, a container, or a wrapper which stores variables and in which a piece of our code is evaluated and executed.

The default execution context is always the global context (Global Execution Context).

Remember that an execution context is where the code is executed ?

In a global context, all the code that is not inside of any function is executed and this is very important.

The Global Execution Context is for variables and functions that are not inside of any function.

We can also think of an execution context as an object.

So the global execution context is associated with the global object, which in case of the browser, it’s the window object.

Therefore, anything we declare in the global context automatically gets attached to the window object in the browser.

For example:

firstName === window.firstName
//true

Declaring a variable called firstName, or window.firstName is the exact same thing.

It’s like firstName is the property of the window object.

As we mentioned earlier, properties are just variables attached to objects.


Global execution context is for code that is not inside any function, then what about code that is inside functions?

Each time when we call a function, it gets its own brand new execution context.

var name = 'Jane'; // <- not in any functions so it is in the global execution context, so this variable is stored in the global object.

function first() {
  var a = 'Hello!';
  second();
  var x = a + name;
}// <- this function declaration is also in the global execution context, so until here we are still in the same execution context which is global.


function second() {
   var b = 'Hi!';
   third();
   var z = b + name;
}// <- same 


function third() {
  var c = 'Hey!';
  var z = c + name;
} // <- same 

first(); // where the fun part begins!

We call our very first function at the last line of the code, so it will get its own new execution context,  this new execution context will be placed beyond the global execution context which will form an execution stack.

[execution context first()]
一一一一一一一一一一一一一一一一
=> [global execution context]
一一一一一一一一一一一一一一一一
Execution Stack

Hence, for the duration of the first() function call, the execution context for that function, becomes the active context in which the code is executed.

=> [execution context first()]
一一一一一一一一一一一一一一一一一一
[global execution context]
一一一一一一一一一一一一一一一一一一
Execution Stack

Now let’s get inside the first function,  the ‘a’ variable will now be stored in the execution context for this function, and not anymore in the global context.

Now we call the second(), then a new execution context will be created and put on top of the first() execution context of the execution stack.

[execution context second()]
一一一一一一一一一一一一一一一一一

=> [execution context first()]
一一一一一一一一一一一一一一一一一一
[global execution context]
一一一一一一一一一一一一一一一一一一
Execution Stack

And it will become the active context.

=>[execution context second()]
一一一一一一一一一一一一一一一一一

[execution context first()]
一一一一一一一一一一一一一一一一一一
[global execution context]
一一一一一一一一一一一一一一一一一一
Execution Stack

Now variable b is stored in this new second() execution context, and then we call third(), again, a new execution context will be created and added to the top of the execution stack.

=>[execution context third()]
一一一一一一一一一一一一一一一一一

[execution context second()]
一一一一一一一一一一一一一一一一一

[execution context first()]
一一一一一一一一一一一一一一一一一一
[global execution context]
一一一一一一一一一一一一一一一一一一
Execution Stack

Now in this execution context, we only have two variable declarations and nothing more, so once the function finishes all its work, we say the function returns, then what will happen to its execution context?

It just gets removed from the top of the execution stack.

=>[execution context second()]
一一一一一一一一一一一一一一一一一

[execution context first()]
一一一一一一一一一一一一一一一一一一
[global execution context]
一一一一一一一一一一一一一一一一一一
Execution Stack

So now the context of second() function which called third() function becomes the active context, then we will go back to the second function. (at line var z = b +name;) where z variable is stored in the current active context.

After the function returns, this contexts also pops off the stack.

Then we will back to the first() function now.

=>[execution context first()]
一一一一一一一一一一一一一一一一一一
[global execution context]
一一一一一一一一一一一一一一一一一一
Execution Stack

Similarly, when the function is done, it returns and so we exit it, and the execution context pops off the stack.

=>[global execution context]
一一一一一一一一一一一一一一一一一一
Execution Stack

We executed all three functions, created three execution contexts and pop them off the stack when the function returns.

Finally, how are all these execution contexts actually created?

Move on to the next note if you want to understand this concept in detailed.


Please note that this is my study notes that I took while taking the complete guide to JavaScript course on Udemy, if you are interested in understanding the language better, I highly recommend you to purchase the course 🙂 !

Standard
JavaScript

JavaScript – Execution Contexts in Detail: Creation, Execution Phases and Hoisting

white steel chair in front round table on white rug

As mentioned in the previous note, we can associate an execution context with an object: execution context object.

This object has three properties:
(Recap: properties are variables stored in objects)

  • Variable Object(VO):  also known as activation object that is composed of all the variables, function declarations, and arguments defined inside the execution context.
  • Scope chain: contains the current variable object as well as the variable objects of all its parents.
  • “This” variable.

 


How is the execution context actually created?

When the function is called, and the execution context is put on top of the execution stack, this happens in two phases.

  1. Creation Phase
  • Creation of the Variable Object(VO)
  • Creation of the scope chain
  • Determine value of the ‘this’ variable. (the ‘this’ variable is determined and set)

So basically, the three properties of the execution context object are defined.

Then in the execution phase, the code in the function that generated the current execution context is ran line by line.

And all the variable are defined. If it’s the global context, then it’s the global code that is executed.


Variable Object (VO)

  • In the creation of the variable object, the argument object is created, containing all the arguments that were passed into the function.
  • Code is scanned for function declarations: for each function, a property is created in the Variable Object, pointing to the function.
    -> this means, all the functions will be stored inside the Variable Object, even before the code start executing. This is important!!
  • Lastly, the code is scanned for variable declarations: for each variable, a property is created in the Variable Object, and set to undefined.
    The final two points are commonly referred to Hoisting.

 

Hoisting: functions and variables are hoisted in JavaScript which means that they are available before the execution phase even starts.

However, they are hoisted in different ways though, the difference between functions and variables is that functions are actually already defined before the execution starts while variables are set to undefined, and will only be defined in the execution phase.

The execution phase takes place right after the creation phase.

Recap: each execution context has an object which stores many important data that the functions will use while it’s running, and this takes place even before the code is executed.

 


Hoisting for Functions

Let’s write some simple functions.

function calculateAge(year){
  console.log(2018 - year);
}

calculateAge(2000);
//16

We’ve been declaring and calling functions like this, however, there exists another ways.

calculateAge(2000);

function calculateAge(year){
  console.log(2018 - year);
}

//16

This is actually Hoisting.

In the creation phase of the execution context, which in this case is the global execution context, the function declaration calculateAge is stored in the Variable Object and even before the code is executed.

This is why when we then enter the execution phase, the calculateAge() function is already ready for us to use. So that’s why we don’t need to first declare and then use it but we can first use it and only later in our code, declare it.

This only works for function declarations.

Remember function expressions?

  1. declare a variable
  2. assign the function to it
var calRetirement = function(year) {
  console.log(65 - (2018 - year));
}

calRetirement(2000);
//47 yrs left for retirement

What will happen if we call the function before function expression?

calRetirement(2000);

var calRetirement = function(year) {
  console.log(65 - (2018 - year));
}
//script.js:11 Uncaught TypeError: calRetirement is not a function

This is because hoisting only works for function declarations.


Hoisting for Variables

var age = 23;
console.log(age);

//23

What will happen if we use the variable before declaring it ?

console.log(age);
var age = 23;

//undefined

This is exactly how hoisting works with variables.
In the creation phase of the variable object, the code is scanned for variable declarations and then the variable is then set to undefined.

console.log(age);
// Uncaught ReferenceError: age is not defined

In this case, JavaScript does not even know this variable.

But in the case below, JavaScript knows that there will be an age variable, simply don’t have the value yet. And that’s also the reason why it is defined as undefined. (Variable does not have a value yet will always have a data type undefined)

console.log(age);
var age = 23;

//undefined

One more example:

console.log(age);
var age = 23;

function foo() {
  var age = 60;
  console.log(age);
}

foo();
console.log(age);

//
undefined
60
23

Why would this happen?

var age = 23;

The age variable is stored in the global execution context object, (to be more precise: is stored in the variable object of the global execution context object)

So this variable is declared in the global execution context object.

The foo function gets its own execution context object in which we can also store an age variable in the variable object with the same name as there are completely two different variables.

function foo() {
  var age = 60;
  console.log(age);
}

The age variable above is defined in the variable object of the execution context object of the function foo(), while

var age = 23;

is defined in the variable object of the global execution context object.

Each execution context object gets its own variable object so we have two different variables and when we print it to the console, the results are different.


Please note that this is my study notes that I took while taking the complete guide to JavaScript course on Udemy, if you are interested in understanding the language better, I highly recommend you to purchase the course 🙂 !

Standard
JavaScript

How JavaScript Works Behind the Scenes

MacBook Air on chair

JavaScript is mostly hosted in some environment, and that is most typically a browser, such as Google Chrome, Firefox, Safari etc.

This is where JavaScript runs.

There may also be another host such as the node.js web server, or even some applications that accept JavaScript input.

However, here we’ll just focus on browsers.


When we write JavaScript code and actually want to run it, there is a lot of stuff happen behind the scenes.

What happens is that the host where JavaScript is hosted, has some kind of JavaScript Engine that takes our code and executes it.

Our code –> JavaScript Engine

Simply put, a JavaScript engine is a program that executes JavaScript code.

There are many engines out there such as Google V8 engine which is used in Google Chrome, but there are others such as Spider Monkey etc.

The first thing that happens inside the engine is that our code is parsed by a parser, which basically reads our code line by line and checks whether the syntax of the code we gave it is correct.

This implies that the engine knows the JavaScript rule, and how it has to be written in order to be correct/ valid.

When we make some mistakes, it will throw errors and stop the execution, if everything is correct, then the parser produces a data structure known as Abstract Syntax Tree, which is then later translated to machine code.

So this code is no longer JavaScript code, but a set of instructions that can be executed directly by the computer’s processor.

When our code is finally converted to machine code then it will actually run and do its work.

A broad overview:

Our code -> parser -> no errors then parser produces abstract syntax tree -> converts it to machine code -> done conversion -> code runs

 


Please note that this is my study notes that I took while taking the complete guide to JavaScript course on Udemy, if you are interested in understanding the language better, I highly recommend you to purchase the course 🙂 !

Standard
JavaScript

JavaScript – Loops & Iteration

opened book showing girl illustration

Besides the if/else statement, there are more control structures.

So here we have, Loops.

Loops are an very important aspects to any programming language.

If you want to solve a very repetitive task, you won’t want to write the same function multiple times.

So basically, we can automate repetitive task using loops.


For loop

console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
console.log(6);

==> we can transform this into a for loop.

for(initial value of the counter; condition that is evaluated before each iteration; counter will update after each iteration)

  1. Declare a counter called i.
  2. Only if the condition turns out to be true, the code block will be executed.
  3. Counter updates, in this case, increases i by 1.
for(var i = 0; i < 10; i++ ) {
  console.log(i);
}

//
0 
1
2
3
4
5
6
7
8
9

Let’s break it down to see what happened in each iteration.

  1. i = 0, 0 < 10 true, log i to console, i++
  2. i = 1, 1 < 10 true, log i to console, i++
  3. i = 9, 9 < 10 true, log i to console, i++
  4. i = 10, 10 < 10 false, exit the loop;

That’s why we stop at 9.
Instead of i++, we can also increase i by 2.

for(var i = 1; i <= 20; i += 2) {
  console.log(i);
}

//i += 2 same as i = i + 2

Using for loop with arrays

var jane = ['Jane', 'Smith', 1989, 'signer'];
console.log(jane[0]);
console.log(jane[1]);
console.log(jane[2]);
console.log(jane[3]);
//
Jane
Smith
1989
signer

If we have 20 items in the array then we’ll need to create 20 lines of the same code.

Let’s use for loop to solve this.

Note that we have to start at 0 since array is 0 based.

var jane = ['Jane', 'Smith', 1989, 'signer'];

for(var i = 0; i < jane.length; i++){
  console.log(jane[i]);
}

jane.length = 4 while array is 0 based, so the loop will exit when 4 < 4 -> false.


While Loop

Let’s turn the for loop above into a while loop.

var jane = ['Jane', 'Smith', 1989, 'signer'];
var i = 0;
while(i < jane.length){
  console.log(jane[i]);
  i++;
}

Continue & Break Statement

Break statement is used to break out all of the loop.
Continue statement is used to quit the current iteration of the loop and continue with the next one.

For example, we only want to log element that is a string, so the logic will be: if it’s not a string, then it will quit the current iteration and then continue with the next one.

var jane = ['Jane', 'Smith', 1989, 'signer', false];

for(var i = 0; i < jane.length; i++) {
  if(typeof jane[i] !== 'string') continue;
  console.log(jane[i]);
}

//
Jane
Smith
signer

note: !== is the strict different operator, means if it’s different from string in this case.

If the if statement only has one line of code then it can be inlined without {}.


Break

The difference between break and continue is that break exits the current iteration and the entire loop.

var jane = ['Jane', 'Smith', 1989, 'signer', false];

for(var i = 0; i < jane.length; i++) {
  if(typeof jane[i] !== 'string') break;
  console.log(jane[i]);
}

//
Jane
Smith


Small exercise: Looping backwards

How to revert the order while we logged the jane array using the for loop?

var jane = ['Jane', 'Smith', 1989, 'signer', false];

for(var i = jane.length - 1; i >= 0; i--) {
  console.log(jane[i]);
}

//
false
signer
1989
Smith
Jane

The loop will be executed so long as the condition evaluates to true, which means untIl i hits -1 > 0 false ( i = 0 will still work).


Please note that this is my study notes that I took while taking the complete guide to JavaScript course on Udemy, if you are interested in understanding the language better, I highly recommend you to purchase the course 🙂 !

Standard
JavaScript

JavaScript – Objects and Methods

turned-on silver LG laptop on whit table

One of the most important features in JavaScript.


Objects and properties

In objects, we define key-value pairs which means each value has a name which is called the key.

Objects are like containers which can store variables called properties.

One fundamental differences between an object and an array is that in array order matters a lot while in object it does not matter at all.

Steps

  1. Declare a variable
var john =
  1. The easiest way to create a object is the so called object literal.
var john = {};
  1. Start defining key-value pairs. In this case, name is the key and ‘john’ is the value. So we call it a key-value pair. We also say that firstName is a property of the john object. We separate properties using coma just like an array.

We can put all types of data types here, such as an array or even place an object inside another.

var john = {
  firstName: 'john',
  lastName: 'Smith',
  birthYear: 1998,
  familyMembers: ['Jane', 'Mark', 'Emily'],
  job: 'teacher',
  isMarried: false
};

console.log(john);

firstName, lastName, birthYear, familyMembers, job, isMarried are all properties of john object, so how can we access these properties?


Methods to read/ access object’s properties = retrieve data from an object

  1. Dot notation
var john = {
  firstName: 'john',
  lastName: 'Smith',
  birthYear: 1998,
  familyMembers: ['Jane', 'Mark', 'Emily'],
  job: 'teacher',
  isMarried: false
};
console.log(john.firstName);
//john
  1. Use the [key name]
var john = {
  firstName: 'john',
  lastName: 'Smith',
  birthYear: 1998,
  familyMembers: ['Jane', 'Mark', 'Emily'],
  job: 'teacher',
  isMarried: false
};
console.log(john['lastName']);
//Smith
We have to use single quote as key names are actually strings

or

var john = {
  firstName: 'john',
  lastName: 'Smith',
  birthYear: 1998,
  familyMembers: ['Jane', 'Mark', 'Emily'],
  job: 'teacher',
  isMarried: false
};

var x = 'birthYear';
console.log(john[x]);
//1998

Object Mutations

var john = {
  firstName: 'john',
  lastName: 'Smith',
  birthYear: 1998,
  familyMembers: ['Jane', 'Mark', 'Emily'],
  job: 'teacher',
  isMarried: false
};

john.job = 'designer';
john['isMarried'] = true;

console.log(john);

//{firstName: "john", lastName: "Smith", birthYear: 1998, familyMembers: Array(3), job: "designer",&nbsp;…}birthYear: 1998familyMembers: (3)&nbsp;["Jane", "Mark", "Emily"]firstName: "john"isMarried: truejob: "designer"lastName: "Smith"__proto__: Object

There is another to initialize an object.

var jane = new Object();
jane.name = 'Jane';
jane.birthYear = 1988;
jane['lastName'] = 'Smith';
console.log(jane);

In summary, there are two ways to create objects.

  1. Object literal { }
  2. new Object() syntax

 

 


Methods

Objects can hold different types of data, including arrays, objects etc.

In fact, we can also attach functions to objects, and these functions are called methods.

To create a method for an object, firstly

  1. Define the key
  2. Define the value, and the value here is basically a function expression where the function doesn’t have a name, we pass in an argument and later we assign this function to a variable which in this case called calculateAge.
var john = {
  firstName: 'john',
  lastName: 'Smith',
  birthYear: 1998,
  familyMembers: ['Jane', 'Mark', 'Emily'],
  job: 'teacher',
  isMarried: false,
  calculateAge: function(birthYear){
    return 2018 - birthYear;
  }
};

The way we call the function is the same as accessing the properties and normal function calls.

console.log(john.calculateAge(1998));

//20

Recall that in the previous note we reviewed some methods that can be applied to arrays.

 In fact, arrays are also objects and that’s the only way they can have methods.

Only objects can have methods.

However, the age (1998) that we pass in as the argument is already defined in the object itself.

Hence, instead of passing it to the method again, how can we access the birthYear property right inside this object ?

In every object, JavaScript gave us a special keyword called this.

Therefore, instead of passing birthYear again to the calculatedAge, we can simply say

var john = {
  firstName: 'john',
  lastName: 'Smith',
  birthYear: 1998,
  familyMembers: ['Jane', 'Mark', 'Emily'],
  job: 'teacher',
  isMarried: false,
  calculateAge: function(){
    return 2018 - this.birthYear;
  }
};

console.log(john.calculateAge());

//20

‘this’  in this case refers to the john object.

So basically,

‘this’ means the current object.

 return 2018 - this.birthYear == 2018 - john.birthYear 

Ok, so what if we want to store this result into the john object ?

var john = {
  firstName: 'john',
  lastName: 'Smith',
  birthYear: 1998,
  familyMembers: ['Jane', 'Mark', 'Emily'],
  job: 'teacher',
  isMarried: false,
  calculateAge: function(){
    this.age = 2018 - this.birthYear;
  }
};

john.calculateAge();
console.log(john);

//
age: 20
birthYear: 1998
calculateAge: ƒ ()
familyMembers: (3) ["Jane", "Mark", "Emily"]
firstName: "john"
isMarried: false
job: "teacher"
lastName: "Smith"
__proto__: Object

we can also set/add a property to an object using ‘this’ just like the case above.

this.age = 2018 - this.birthYear;

 //age: 20

 

 


Please note that this is my study notes that I took while taking the complete guide to JavaScript course on Udemy, if you are interested in understanding the language better, I highly recommend you to purchase the course 🙂 !

Standard
JavaScript

JavaScript – Arrays and Useful Methods

Arrays are like collections for variables that even have different data types.

There are multiple ways to create arrays, the simplest way it through

var names = [];

var names = ['John', 'Mark', 'Jane'];

or calling the Array() with the new keyword

var years = new Array();

var years = new Array(1990, 1969, 1948);

Arrays are zero based, which means that the first element is element number 0.

We can access the element in the array by writing

[0] 
// [index]

Example:

var names = ['John', 'Mark', 'Jane'];
console.log(names[0]);
//John

 


To get the length of the array (number of elements)

console.log(names.length);
//3

Mutate array

var names = ['John', 'Mark', 'Jane'];
names[1] = 'Ben';
console.log(names);
//
["John", "Ben", "Jane"]

Add data to the array, we can even access position that is not even there.

var names = ['John', 'Mark', 'Jane'];
names[1] = 'Ben';
names[5] = 'Mary';
console.log(names);
//(6)&nbsp;["John", "Ben", "Jane", empty × 2, "Mary"]

If we want to add ‘Mary’ to the last position of the array, we can use a property .length like this:

var names = ['John', 'Mark', 'Jane'];
names[names.length] = 'Mary';
console.log(names);
//(4)&nbsp;["John", "Mark", "Jane", "Mary"]



Arrays can also store different data types.

var John = ['John', 'Smith', 1998, 'teacher', false];

So now we have different data types all in one data structure which is this array.
They are some functions that can be applied to arrays.

These functions are called methods that are specific to arrays.


Examples:

push()

var john = ['John', 'Smith', 1998, 'teacher', false];
john.push('blue');
console.log(john);
//(6)&nbsp;["John", "Smith", 1998, "teacher", false, "blue"]

The push method will add the element to the end of the array.

unshif()

var john = ['John', 'Smith', 1998, 'teacher', false];
john.unshift('Mr.');
console.log(john);
//(6)&nbsp;["Mr.", "John", "Smith", 1998, "teacher", false]

The unshif method adds the element to the beginning of the array.

pop()

var john = ['John', 'Smith', 1998, 'teacher', false];
john.pop();
console.log(john);
//(4)&nbsp;["John", "Smith", 1998, "teacher"]

The pop method removes the element at the end.

shift()

var john = ['John', 'Smith', 1998, 'teacher', false];
john.shift();
console.log(john);
//(4)&nbsp;["Smith", 1998, "teacher", false]

The shift method removes the first element.

indexOf()

var john = ['John', 'Smith', 1998, 'teacher', false];
console.log(john.indexOf(1998));
//2 

The indexOf return the position of the argument we passed into this method.
If the argument we pass in does not exist in the array, it will return -1.

var john = ['John', 'Smith', 1998, 'teacher', false];
console.log(john.indexOf(23));
//-1

So this method is very useful to test whether the element is present in the array.

var john = ['John', 'Smith', 1998, 'teacher', false];
var isDesigner = john.indexOf('designer') === -1 ? 'John is a designer' : 'John is not a designer.';
console.log(isDesigner);
//John is not a designer

 

 


Please note that this is my study notes that I took while taking the complete guide to JavaScript course on Udemy, if you are interested in understanding the language better, I highly recommend you to purchase the course 🙂 !

Standard