0% found this document useful (0 votes)
168 views

Javascript Language Basics

The document provides an introduction to JavaScript, covering basic concepts like variables, data types, operators, and comments. It explains how to add JavaScript to HTML pages, internally or externally, and introduces common JavaScript functions like console.log() and alert().

Uploaded by

George
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
168 views

Javascript Language Basics

The document provides an introduction to JavaScript, covering basic concepts like variables, data types, operators, and comments. It explains how to add JavaScript to HTML pages, internally or externally, and introduces common JavaScript functions like console.log() and alert().

Uploaded by

George
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

4. Section intro.

In this section we will learn the basics of the js language - things like variables, data types, objects,
arrays, etc.

We will also learn the fundamentals of programming in general.

For now we’re getting a quick overview of how the language works and getting some hands-on coding
experience.

5. Download the code.

Have installed VSCode along with suggested add-ons and edited settings.json to match the
recommended functionality.

6. Let’s start coding.

There are 2 ways to add JS to a website - either with inline scripts or with an external JS file within
which we can add all of our JS code.

To do an inline script, we write <script></script> and can add our script in these tags.

We add an inline script console.log(‘text’) - this logs our text to the developer console on our
webpage.

To add an external script, we created a script file - namely “script.js” here, and switched our inline to
<script src=”FILEPATH”> to designate the filepath we’re pulling the script from. Our script is in the
same folder so we’re happy to use script.js but if it was in a different folder, I.e. js, we would have to
set <script src=”js/script.js”>

We will typically use our script.js file as it’s typically best to have our javascript and HTML code in
separate files.

N.B.: Editing a script and refreshing webpage with developer console open will automatically refresh
developer console.

7. A brief introduction to JavaScript

What exactly is JavaScript?

By definition, JS is a lightweight, cross-platform, object-oriented programming language.

JavaScript, HTML and CSS are the three core technologies of web development.

JS has traditionally only been used in the browser (client-side).


Now, thanks to node.js, we can use JS server-side as well. (NOT COVERED IN THIS COURSE)

JS has made modern web development possible by allowing us to add dynamic effects and
interactivity to web pages as well as allowing us to develop complex modern web apps that we can
interact with, similar to phone/PC apps.

There are now modern frameworks/libraries such as React, Angular, jquery, which are all based on
JavaScript and allow us to develop complex apps even quicker and more easily than before. These are
100% based on JS so you need to be competent with JS to use these apps.
HTML, CSS and JS work together to create websites. HTML is responsible for the content of the page -
I.e. texts, images, buttons; CSS is responsible for presentation - e.g. styling, laying out elements; JS is
the real programming language that allows developers to add dynamics such as interactive effects
and manipulation of the web page content.

HTML DEALS WITH CONTENT, CSS DEALS WITH PRESENTATION, JS DEALS WITH DYNAMIC
EFFECTS/PROGRAMMING.

One way of thinking about this is via the noun-adjective-verb paradigm.

For example:
HTML - <p></p> is a “paragraph” - HTML denotes the “noun”;
CSS - p {color: red;} - means “the paragraph text is red” - CSS adds the adjective;
JS - p.hide(); - means to “hide the paragraph” - so JS is doing something, it’s adding the verb.

There are different versions of JS: ES5 -> ES6/ES2015 -> ES7/ES2016 -> ES8/ES2017

We will work in ES5 for now and then cover the differences between these types at the end of the
section.

8. Variables and data types.

Variables are a fundamental concept of all programming languages.

A variables is like a container in which we store a value to use repeatedly in our code instead of
having to write the value repeatedly.

To declare a variable, we use the KEYWORD var, then the NAME OF THE VARIABLE, then =, then the
VALUE WE WANT TO ASSIGN TO THE VARIABLE.

F.e. var firstName = ‘John’;

We can use double or single quotes, “”, ‘’, to declare variables, but we tend to use singles. Some
languages/terminals demand specific options, f.e. JSCode doesn’t accept single quotes.

JS uses 5 different data types - NUMBER, STRING, BOOLEAN, UNDEFINED and NULL.

These are primitive (I.e. non-object) data types.

1. Number: Floating point numbers, for decimals and integers.


2. String: Sequence of characters, used for text.
3. Boolean: Logical data type that can only be true or false.
4. Undefined: Data type of a variable that does not have a value yet.
5. Null: Also means ‘non-existent’.

Undefined is the data type automatically assigned to a variable that doesn’t have a value yet; basically
means ‘non-existent’.
Null also means ‘non-existent’ but is slightly more specific.

JS has a feature called dynamic typing which means that we DO NOT NEED to manually assign a data
type to each variable, it will interpret the data type based on the assigned value of a variable. This can
be very useful but take care as it can also cause difficult-to-find bugs.

Booleans and numbers do not need quotes when assigned to variables, unlike strings.
It is best practice to give our variables meaningful names so that other people can interpret our code
when they need to read it. Conventionally, we use camelcase notation such as thisVariable, where we
are using capital letters to signify the start of the next word.

Variables cannot start with numbers or symbols, except for the dollar sign, $, or an underscore, _. The
same applies to using symbols in THE MIDDLE of a variable name. This is why we tend to use the
camelcase notation.

We also CANNOT USE JS KEYWORDS AS VARIABLE NAMES, I.e. var function = 23; WILL NOT WORK.
Any word that JS already uses in its language will not work as a variable name.

9. Variable mutation and type coercion.

In all programming languages in the world, we can add comments.

In JS, there are two types of comments - single-line comments and multi-line comments.

Single line comments look like the following:


// this is a comment
The double forward slash signifies our comment.

To add multi-line comments, we use the following syntax:


/*
Comment line 1
Comment line 2
3rd line of comments
*/

Everything between our asterisks and slashes reads as a comment.

We can use comments to basically “comment out” pieces of code that we don’t want to execute while
we work on other things.

When we connect things, I.e. console.log(firstName + “ “ + age);


We receive an output such as “John 28”.
This works through a feature called TYPE COERCION. This is when JS automatically converts types
between one another as needed. In this case, we’ve converted the number from the age variable so
that it can join our two other strings and output one full string.

Joining strings is just one feature of type coercion that we will encounter in this course.

We can declare multiple variables on one line and assign values to them below, such as:
var job, isMarried;
job = "teacher";
isMarried = false;

We can then produce outputs such as


console.log(firstName + " is a " + age + " year old "
+ job + ". Is he married? " + isMarried)

which end up reading “John is a 28 year old teacher. Is he married? false”


Here JS is converting our boolean to a string.

Variable mutation basically means changing the value of a variable.


If we input
age = "twenty eight";
job = "driver";
then we mutate our variables, we can then use a new function

alert(firstName + " is a " + age + " year old "
+ job + ". Is he married? " + isMarried)

This alert function raises a pop-up when the page is loaded which reads “John is a twenty eight year
old driver. Is he married? false” and the page won’t load until we’ve clicked clicked OK on this pop-up.

Alert is an alternative to console.log. We can also use a command called “prompt”. We can use this
like so:
var lastName = prompt("What is his last name?")
console.log(firstName + " " + lastName);

This causes the initial pop-up to be followed by a pop-up asking the user to input a last name. When
this is added, it is assigned to the variable last name and we see that this works properly as the
combination of names is printed in the console log.

Inputting a different name when we reload the page edits the firstName lastName output in the
console.

10. Basic operators

Operators are like functions that are written in a special way in JS. We can use basic mathematical
operators in JS.

The test script


var yearJohn = 2018 - 28;

console.log(yearJohn);
Defines a variable “yearJohn” - John’s year of birth, and calculates this by taking the year of
publication and subtracting John’s age then printing the output to the console.

We can go on to define the current year as a variable and produce multiple year of birth outputs. We
can also perform intuitive basic mathematical operations on these numerical variables, like so:

var year, yearJohn, yearMark;
year = 2020;
yearJohn = year - 28;
yearMark = year - 33;

console.log(yearJohn, yearMark);
console.log(year + 2);
console.log(year * 2);
console.log(year / 10);

The outputs received here are: 1992, 1987; 2022; 4040; 202 - as we would expect.
We can also perform logical operations on our variables. If we replace our yearJohn/yearMark
variables with ageJohn/ageMark variables denoting the ages of these people (28 and 33,
respectively), then we can define a boolean operation which compares the two.

var johnOlder = ageJohn > ageMark;
console.log(johnOlder);
This prints the boolean result “false” since 28 is less than 33, hence ageJohn > ageMark is false.

Similarly, alternating our script to var johnOlder = ageJohn < ageMark returns the boolean value
“true” as the logical statement is true in this form.

There is also another operator - the “typeof” operator. This allows us to determine the data type of
our variables in the console.

console.log(typeof johnOlder);
console.log(typeof ageJohn);
console.log(typeof "Mark is older than John");
var x;
console.log(typeof x);
These lines of code produce the following simple console log outputs:
boolean, number, string and undefined - in accordance with the respective variables we have defined.

11. Operator precedence.

var year = 2018;
var yearJohn = 1989;
var legalAge = 18;

var isLegalAge = year - yearJohn >= legalAge;
console.log(isLegalAge);
Imagine we want to calculate if someone is of legal age for most age-restricted activities in Europe.
We can use the above and we are returned “true”, which makes sense. But we need to be sure that
“year - yearJohn” is calculated as a number before “yearJohn >= legalAge” is calculated as a boolean
and carried into a mixed-variable operation “year - [yearJohn >= legalAge]” subtracting a boolean
from a number.

So why does this work?

This works due to operator precedence. There is a table of operator precedence found here:
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

We can see that addition/subtraction has a precedence of 14, whereas ordering relations (<, >, etc.)
have a precedence of 12. Thanks to the higher precedence of the subtraction, the “year - yearJohn”
operation is carried out first and then the logical operation “yearJohn >= legalAge” is carried out
following that.

N.B. The equals sign is also an operator - the “assignment operator” - with precedence 3. This has
low precedence so that we produce our final output following our operations.

Say we want to calculate the average age of two people. Consider the following:
var ageJohn = year - yearJohn;
var ageMark = 35;
var average = ageJohn + ageMark / 2;

This won’t work, as we know from basic mathematical principles. If disobeys BODMAS and we can
confirm on our table of operator precedence that division/multiplication has a precedence of 15
whereas addition/subtraction has a precedence of 14.

We can fix this by using parentheses to group our addition - grouping is the operation with the highest
precedence. The first output results in 46.5 - which is clearly false as it is greater than either age!
However, if we instead use this:
var ageJohn = year - yearJohn;
var ageMark = 35;
var average = (ageJohn + ageMark) / 2;
console.log(average);

then the brackets work as intended and we receive the more reasonable output of 32!

We can also define multiple variables similarly, such as by using this:


var x, y;
x = y = (3+5)*4-6; //8*4-6 //32-6 //26
console.log(x);

This seems counter-intuitive. Our grouping and mathematical operators work as intended and the
desired output of 26 is indeed seen, but how can we set “x = y” at the start of our line where x and y
are undefined?

The reason this works is due to the mixed “associativity” of operations in JS. Most of our regular
mathematical operations are calculated left-to-right as expected, but it transpires that assignment is
calculated as right-to-left operation. Thus the code above calculates the sum normally, then assigns
26 = y and then finally assigns y (= 26) = x.

When performing lengthy combinations of operators, we need to consider both the operator
precedence and the associative properties of our operators. These can all be found in the operator
precedence table.

We can also use shorthand to perform operations on single variables. The following are two different
ways of performing the same process:
x = x*2;
x *= 2;
console.log(x);

x = x + 10;
x += 10;
console.log(x);
x = x*2 doubles x; but so does x *= 2, and similarly for x += 10.

We do NOT NEED to manually increment our variable, we can just use this shorthand “operation-
equals” notation. These are also different assignment operators.
Finally, to increment a variable, we can use any of the three following options:
x = x + 1;
x += 1;
x++;
These all increment our variable x by 1.

12/13. Coding Challenge 1.

The first coding challenge requests us to calculate and compare two BMI’s. My solution was the
following:

// CODING CHALLENGE 1

var massMark, massJohn, heightMark, heightJohn;
massMark = 75;
massJohn = 83;
heightMark = 1.68;
heightJohn = 1.76;

var bmiMark, bmiJohn;
bmiMark = massMark / (heightMark*heightMark);
bmiJohn = massJohn / (heightJohn*heightJohn);

var markHigherBMI = bmiMark > bmiJohn;

console.log("Is Mark's BMI higher than John's? " + markHigherB
MI);
console.log(bmiMark, bmiJohn);

And the output received was:


script.js:126 Is Mark's BMI higher than John's? false
script.js:127 26.573129251700685 26.794938016528928

14. If/else statements.

JS has a couple of control structures - features that allow us to execute only certain parts of our code
or to execute parts multiple times.

The first control structure we will consider is the if/else statement. This is a conditional which allows
us to make decisions using code.

Consider the following:


var firstname = "John";
var civilStatus = "single";

if (civilStatus === "married") {
    console.log(firstname + " is married!");
} else {
    console.log(firstname + " will hopefully marry soon!")
}

We write “if” followed by a boolean statement. The triple equals (===) here represents STRICT
EQUALITY, and if the Boolean statement is ‘true’ then we execute the code within the curly brackets,
here printing “firstName is married!” to the console log.

If the boolean results false, then we execute the code following “else” in the curly brackets.

If we already have a boolean variable defined, then we can rewrite our code without specifying the
value of the variable, like so:
var isMarried = false;
if (isMarried) {
    console.log(firstname + " is married!");
} else {
    console.log(firstname + " will hopefully marry soon!")
}

Here “if (isMarried)” represents “if isMarried = true”, using the implicit properties of boolean
variables.

We can use this to produce a more attractive output than a “true/false” value for the result of our
coding challenge 1, by changing our code to read something like this:

if (bmiMark > bmiJohn) {
    console.log("Mark's BMI is higher than John's.")
} else {
    console.log("John's BMI is higher than Mark's.")
}

This is the fundamental of conditionals in code.

15. Boolean logic.

Boolean logic is the next level of conditional coding.

Boolean logic works similarly to predicate logic and utilises truth tables.

Say we have two variables, var A and var B.

Then we have the three basic operators


AND denoted by && -> true if ALL boolean variables in our string are true.
OR denoted by || -> true is ONE of our boolean variables is true.
NOT denoted by ! -> INVERTS true/false values in the traditional manner of predicate logic.

This can be illustrated with some examples:

var age = 16;


age >= 20; // => FALSE
Age < 30; // => TRUE
!(age < 30); // => FALSE

Age >= 20 && age < 30; // => FALSE


Age >= 20 || age < 30; // => TRUE

We can use this with our if/else statements, like so:

var firstName = "John";
var age = 16;

if (age < 13) {
    console.log(firstName + " is a boy.")
} else if (age >= 13 && age < 20) {
console.log(firstName + " is a teenager.")
}
else {
    console.log(firstName + " is a man.")

Here we’ve used the AND operator to construct a “middle value” for age output.

Note that logical operators have lower precedence than mathematical operators so strings like these
are valid.

N. B. We can use these “else if” statements shown above to create NESTED IF/ELSE statements,
where we perform one action “if A holds”, or else we perform another action “if B holds”, or else we
perform a third action “if C holds”, or else… or else we perform a final action “if X holds”.

16. The ternary operator and switch statements.

The ternary operator, aka conditional operator, basically allows us to write an if else statement all on
one line.

var firstName = "John";
var age = 16;

age >= 18 ? console.log(firstName + " drinks beer.")
: console.log(firstName + " drinks juice.");

In this basic example, we can see the 3 operands in use, which gives rise to the name of the ternary
operator. The first operand is our condition “age >= 18”, which we follow with a question mark, then
our “if statement” which prints the first option, then a colon followed by our “else statement” which
is printed when our boolean condition is false.

We can similarly use the ternary operator to assign values to our variables, like so:
var drink = age >= 18 ? "beer" : "juice";

Here we define a variable, state a condition and then assign a value to the variable using the if/else
condition of the ternary operator. The ternary operator has a higher operator precedence than the
assignment operator so this works as intended. (Recall that assignment works right-to-left.)
The alternative code using a traditional if/else statement would look like this:

if (age >=18) {
    var drink = "beer"
} else {
    var drink = "juice"
}

Thus we can see how the ternary operator can be used to streamline our if/else statements.

There is also the switch statement which we can use to streamline large if/else clauses with multiple
intermediary else if statements.

var job = "designer";
switch (job) {
    case "teacher":
    case "instructor":
        console.log(firstName + " teaches kids how to code.");
        break;
    case "driver":
        console.log(firstName + " drives an Uber is Lisbon.");
        break;
    case "designer":
        console.log(firstName + " designs beautiful websites."
);
        break;
    default:
        console.log(firstName + " does something else.");
}

This is a switch statement. We choose a variable that we wish to assess to “make the switch”, and
then define various outputs based on the different cases. We can assign multiple values to the same
output as demonstrated at the top of the code. Once each output is designated, we add a “break;”
clause so that our code doesn’t keep searching and potentially printing multiple outputs. We finish
with a “default:” case that we print when the variable doesn’t take any of our specified values.

var firstName = "John";
var age = 16;

switch (true) {
    case age < 13:
        console.log(firstName + " is a boy.");
        break;
    case age >= 13 && age < 20:
        console.log(firstName + " is a teenager.");
        break;
    case age >=20 && age < 30:
        console.log(firstName + " is a man.");
        break;
    default:
        console.log(firstName + " is a man.");
}

Here is a more typical example of a functional switch statement. We are recreating our argument
from Boolean logic. We start with “switch (true)” so that our code will execute the case which reads
as true.

It is apparent how these two cases differ. When we’re switching over a string, we define specific string
values and outputs based on these. In the second case, we simply switch over true and define
multiple exclusive Boolean strings and print the output which returns the Boolean value true.

If/else statements, the ternary operator and the switch statement are all ways of writing conditional
code.

17. Truthy and falsy values and equality operators.

In JS, a falsy value is a value that is considered false when evaluated in an if/else statement condition.
In JS, these values are: undefined, null, 0, “ “ (empty strings), NaN (not a number). These statements
are all converted to false when evaluated in an if/else condition, hence the name.

We also have truthy values which are values that are considered true when evaluated in an if/else
statement condition. These are: all the values which are NOT falsy values.

var height;

if (height) {
    console.log("Variable is defined");
} else {
    console.log("Variable has NOT been defined.");
}

In this example, we have designated the variable height but not defined a value for it. Our output tells
us that the variable has NOT been defined. This is because our height variable is presently
“undefined” which is a falsy value, hence it outputs the else statement of our if/else clause.

THIS IS A USEFUL WAY OF CHECKING IF VARIABLES HAVE BEEN DEFINED.

If we assign a numerical value to our height variable, then our code returns “Variable is defined”
because all non-falsy values are truthy values. However, since 0 is also considered a falsy value but is
a valid option for this variable, we often have to tweak to allow for this specific case, like so:

var height = 0;

if (height || height === 0) {
    console.log("Variable is defined");
} else {
    console.log("Variable has NOT been defined.");
}

The additional OR statement here fixes this fringe case and shows our variable as defined even if it
has a numerical value of 0 which is a falsy value.

var height = 23;
if (height == "23") {
    console.log("The == operator does type coercion!")
}

Here we see the difference between the two operators == and ===. The traditional === represents
strict equality, so it searches for a complete match. However, the other operator == operates under
type coercion, so we can use it to define equality here where we have a string and a number, which
are different data types. In the above example, our result prints as if our if statement was true.

It is considered best practice to typically use the strict equality operator === to avoid any unexpected
situations or bugs in the code.

18/19. CODING CHALLENGE 2

var avgJohn = (89 + 120 + 103) / 3
var avgMike = (119 + 94 + 123) / 3
var avgMary = (97 + 134 + 105) / 3

if (avgJohn > avgMary && avgJohn > avgMike) {
    console.log("John's team had the highest average score of 
" + avgJohn)
} else if (avgMike > avgMary && avgMike > avgJohn) {
    console.log("Mike's team had the highest average score of 
" + avgMike)
} else if (avgMary > avgJohn && avgMary > avgMike) {
    console.log("Mary's team had the highest average score of 
" + avgMary)
} else if (avgMary === avgMike && avgMary > avgJohn) {
    console.log("Mary and Mike's teams had a joint average hig
hest score of " + avgMary)
} else if (avgMary === avgJohn && avgMary > avgMike) {
    console.log("Mary and John's teams had a joint average hig
hest score of " + avgMary)
} else if (avgJohn === avgMike && avgJohn > avgMary) {
    console.log("John and Mike's teams had a joint average hig
hest score of " + avgJohn)
} else if (avgJohn === avgMike && avgJohn === avgMary) {
    console.log("All three teams had a joint average score of 
" + avgJohn)
} else {
    console.log("No team had the highest average score.")
}

This is my solution. I initially tried using “switch (true)” and similar boolean arguments but my code
was outputting “x and y’s teams had a joint highest average score of true”. Upon rewriting, I believe
this was because my arguments were of the form
avgX = avgY && avgX > avgZ,
using the assignment operator rather than the strict equality operator which is in use in the updated
if/else version.

Grammatically, this should read “joint highest average” rather than “joint average highest” - my bad.

20. Functions

Functions are one of the most fundamental concepts in JS. If we want to run a piece of code lots of
times we can put it in a function instead of repeatedly typing it. A function is like “a container which
holds some lines of codes” and we can pass arguments through them to get results.

function calculateAge(birthYear, x, y) {

This is the basic form of a function. We use the function command, name our function, designate the
argument(s) for our function in the brackets and then write the code in the “function block” between
curly brackets.

Functions are core to one of the most important coding principles, known as don’t repeat yourself,
aka DRY. Instead of repeating our code, we can just throw it in a function. Consider our basic example
here:

function calculateAge(birthYear) {
   return 2018 - birthYear;
}

var ageJohn = calculateAge(1990);
var ageMike = calculateAge(1948);
var ageJane = calculateAge(1969);
console.log(ageJohn, ageJane, ageMike);

For a more complex example, we could calculate the remaining time until retirement for people of
various ages, using a function something like this:

function YearsUntilRetirement(year, firstName) {
    var age = calculateAge(year);
    var retirement = 65 - age;

    if (retirement > 0) {
    console.log(firstName + " retires in " + retirement + " ye
ars.")
} else {
    console.log(firstName + " is already retired.")
} }

YearsUntilRetirement(1990, "John");
YearsUntilRetirement(1948, "Mike");
YearsUntilRetirement(1969, "Jane");

Here we can see that we can even embed our first function into a later function to further streamline
the process. We also add an if/else statement to handle the case for a negative numerical output,
which doesn’t make too much sense. By optimising our coding like this, we are said to “keep our code
dry” - referring back to DRY - don’t repeat yourself.

21. Function statements and expressions.

We previously used function statements, however there is an alternative way to write functions
known as function expressions. It works quite differently under the hood, but is similar in terms of
use.

A function expression reads like this:


var whatDoYouDo = function(job, firstName) {}

We define a variable and assign our function to the variable. Alternatively, as a function statement,
this reads like:
function whatDoYouDo(job, firstName) {}

We have to assign this to a variable at a later stage (when using a function statement).

Here is an example of function expression:

var whatDoYouDo = function(job, firstName) {
    switch(job) {
        case "teacher":
            return firstName + " teaches kids how to code.";
        case "driver":
            return firstName + " drives a cab in Lisbon."
        case "designer":
            return firstName + " designs beautiful websites."
        default:
            return firstName + " does something else."
    }
}

console.log(whatDoYouDo("teacher", "John"));
N.B. We do not have to use a “break;” statement after each case in this function because the “return”
statement ends the function when it’s executed.

We are using a switch statement over the job argument and returning a string involving our firstName
argument based on our job argument. Since our input is just a string and we are not logging anything,
we need to log the result to console to read it in this case - it’s not printed anywhere by the function
itself.

Statements and expressions are actually a global concept in JavaScript.


An expression is a piece of code that always results in a single value, therefore when JS expects a
value we have to write an expression. Examples include logical expressions, mathematical
expressions, functions, etc.
A statement is a piece of code which performs an action, but does not necessarily produce an
immediate result. Examples include if/else statements, why loops, etc.

N.B. We can use functions defined in our JS code in our console log.

22. Arrays.

Arrays are another fundamental concept in JS. We can use arrays to bundle multiple variables into
one single variable. An array is a collection of variables which can even have multiple different data
types.

We can create arrays in these two formats:


var names = ["John", "Mark", "Jane"];
var years = new Array(1990, 1969, 1948);

The first is more commonly used, and tends to be the standard. Arrays are zero-based, so the first
element is 0, the second element is 1, etc.

Here we have some basic functions on arrays:


console.log(names[0])
console.log(names)
console.log(names.length)

The first prints “element 0” of the array “names”.


The second prints the whole array.
And the third tells us how many entries are in the array - aka the length of the array.

We can also mutate our array data with some simple commands, such as:

names[1] = "Ben";
names[names.length] = "Mary";
The first command changes the “1 element”, the second command sets an extra value at the end of
our array.

Arrays can contain different data types.

var john = ["John", "Smith", 1990, "teacher", false];

john.push("blue");

This push command adds a value to the end of our array.


john.unshift("Mr");

This “unshift” command adds an element to the start of our array.

john.pop();

The “pop” command removes the last element from our array.

john.shift();

The “shift” command removes the first element from our array.

console.log(john.indexOf(1990));

This command - “indexOf” - tells us which element of the array our chosen value appears in.
If the element is not present within our array, indexOf will return a value of -1.

var isDesigner = john.indexOf("designer") === -1 ? "John is no
t a designer" : "John is a designer";
console.log(isDesigner);

Here we see an example of using an array in conjunction with our ternary operator. If the string
“designer” is not found in the array “john”, then we return “John is not a designer”, otherwise we
return that “John is a designer”.

23/24. CODING CHALLENGE 3

The purpose of this challenge was to take the prices of 3 meals and calculate the relevant tips and
final costs assuming that the tip was different for different amounts. My solution was:
var bills = [124, 48, 268];

function TipCalculator(bill) {
   if (bill < 50) {
       return bill * 0.2
   } else if (bill > 50 && bill < 200) {
       return bill * 0.15
   } else {
       return bill * 0.1
   }
}

var tips = [TipCalculator(bills[0]), TipCalculator(bills[1]), 
TipCalculator(bills[2])]

var final = [bills[0] + tips[0], bills[1] + tips[1], bills[2] 
+ tips[2]]

console.log(bills)
console.log(tips)
console.log(final) 

This yielded correct results. I also tried a switch function like so:

function TipCalculator(bill) {
   switch(bill) {
       case (bill < 50):
           return bill * 0.2;
        case (bill > 50 && bill < 200):
            return bill * 0.15;
        case (bill > 200):
            return bill * 0.1
   }
}

But this attempt always returned undefined values for the tips, regardless of whether or not I put
them straight into an array or just calculated them. I’d forgotten a default clause, but adding this
revealed that all of the input values returned the default clause - perhaps the function wasn’t reading
the argument as a number since it was an array element? This is not the case - running a number
through the calculator returns the default too.

25. Objects and properties.

Objects are the single most important feature of the JS language.

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

Hence we can use objects to group different variables that belong together but have no particular
order.

In an array, the order matters a lot, whereas in an object, the order does not matter at all.

Here is an example of an object:

var john = {
    firstName: "John",
    lastName: "Smith",
    birthYear: 1990,
    family: ["Jane", "Mark", "Bob", "Emily"],
    job: "teacher",
    isMarried: false
};

Our object is ‘john’ - and “firstName”, “lastName”, etc. are ‘properties’ of our object ‘john’. Each of
these lines, separated by a comma, is a key value pair. We can even have arrays and objects as values
of our object. We can also have arrays as elements of arrays, which we failed to mention earlier. The
curly brackets like this are called the “object literal” and this is a way of defining an object.

Note that objects can hold various types of data.


Here are some ways that we can read specific data from our objects:
console.log(john.firstName);
console.log(john["lastName"]);
var x = "birthYear";
console.log(john[x]);

We can use the “dot notation” to print a specific value associated with a key name. We can also use
array notation with a key name to read that piece of data from the object. Similarly, we can define a
variable associated with a key name and use that to print data from the object.

We can mutate our object data in a similar way to how we mutate array data, like so:

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

We can also define an object using the “new object syntax”, similarly to arrays, like so:

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

26. Objects and methods.

We can also attach functions to objects - these functions are then called methods.

var john = {
    firstName: "John",
    lastName: "Smith",
    birthYear: 1990,
    family: ["Jane", "Mark", "Bob", "Emily"],
    job: "teacher",
    isMarried: false,
    calcAge: function(birthYear) {
        return 2018 - birthYear;
    }
};

In this array, we have added a new property - “calcAge” - and this function is now a method of our
object ‘john’.

Arrays are actually also objects, because arrays have functions that act on them too.
We can streamlike this like so:
calcAge: function() {
        return 2018 - this.birthYear;

The “this” keyword here allows us to take something from the current object.

Further refinement yields the following solution:


calcAge: function() {
        this.age = 2018 - this.birthYear;

N.B. We need to call the function by using john.calcAge() before printing to the console with
console.log(john) or the function itself won’t work and we don’t get the age listed in the object.

27/28. CODING CHALLENGE 4

This was a challenge to re-do the earlier BMI calculation and comparison using objects and methods
rather than basic variables and operators. My working solution was as such:

var john = {
    name: "John Smith",
    height: 1.76,
    mass: 83,
    calcBMI: function() {
        this.BMI = this.mass / (this.height * this.height)
    }
};

var mark = {
    name: "Mark Williams",
    height: 1.68,
    mass: 75,
    calcBMI: function() {
        this.BMI = this.mass / (this.height * this.height)
    }
};

john.calcBMI()
mark.calcBMI()

console.log(john.BMI, mark.BMI)

if (john.BMI > mark.BMI) {
    console.log(john.name + " has a higher BMI than " + mark.n
ame)
} else if (mark.BMI > john.BMI) {
    console.log(mark.name + " has a higher BMI than " + john.n
ame)
} else {
    console.log(mark.name + " and " + john.name + " have the s
ame BMI!")
}

One way of cleaning this up is to have our methods written like

calcBMI: function() {
this.BMI = this.mass / (this.height * this.height);
return this.BMI;
}

and then we can call our functions in our if/else statements since they return the values, i.e.

if (john.calcBMI() > mark.calcBMI()) {


console.log(john.fullName + “ has a higher BMI of “ + john.BMI)
}
and so on.

29. Loops and iteration.

Loops are a form of “control structure”, similar to if/else statements. We can use loops to automate
repetitive tasks. There are various loops in JS, we will start with the basic for loop.

Here is our most simple example:

for (var i = 0; i < 10; i++) {
    console.log(i);

We start with a “counter” - our variable i which is equal to 0. We then evaluate the condition
following - so we check if i is less than 10. This is true, so we execute the code in the for loop and log i
to the console. Finally, we perform the third part of the for loop, in this case, we increment i by 1
(using our ++ command which increments variables). Once i reaches 10, then i < 10 is FALSE, so we
only print 0, 1, 2, …, 9 to the console.

We tend to use i as the notation for our “counter variable” in JavaScript.

Imagine we have an array and we wish to print the individual elements to the console. We can
intuitively do this using a for loop as follows:

var john = ["John", "Smith", 1990, "designer", false];

for (var i = 0; i < john.length; i++) {
    console.log(john[i])
}
This for loop runs through a counter from 0 to the length of our array and increments accordingly
while printing each element. Note that since we’re using the properties of the array to define our
loop, our script will not break if we extend our array.

Looping through arrays is one of the biggest use cases of loops.

An alternative loop we can use to achieve a similar result is the WHILE LOOP, like so:

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

We also have continue and break statements. We can use the break statement to break out of a loop
and the continue statement to quit the current iteration of a loop and continue with the next one.

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

This is an example of the “continue statement”. We use the “strict difference operator”, !==, to tell
our loop to skip its iterations when the type of the data in the array is not a string. The output here is
“John; Smith; designer; blue”.

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

In contrast, this is the “break statement”. Here we stop our loop from running once we encounter an
element in the array which does not have the string data type, so our output here is just “John;
Smith”. Once we reach the first non-string element the loop terminates.

30/31/32. CODING CHALLENGE 5

My solution to part 1:

var john = {
    name: "John Smith",
    bills: [124, 48, 268, 180, 42],
    tips: [],
    final: [],
    calcTip: function(i) {
        for (var i = 0; i < john.bills.length; i++) {
            if (john.bills[i] < 50) {
                john.tips[i] = (john.bills[i] * 0.2)
            } else if (john.bills[i] > 50 && john.bills[i] < 2
00) {
                john.tips[i] = (john.bills[i] * 0.15)
            } else {
                john.tips[i] = (john.bills[i] * 0.1)
            }
        }
    },
    calcFinal: function(j) {
        for (var j = 0; j < john.bills.length; j++) {
            john.final[j] = john.bills[j] + john.tips[j]
        }
    }
}

I have successfully verified that calling the calcTip and calcFinal methods in this script populates the
“tips” and “final” arrays in the “john” object with the correct values.

Here is my copy of the code for the “mark” object.

var mark = {
    name: "Mark Williams",
    bills: [77, 375, 110, 45],
    tips: [],
    final: [],
    calcTip: function(i) {
        for (var i = 0; i < mark.bills.length; i++) {
            if (mark.bills[i] < 100) {
                mark.tips[i] = (mark.bills[i] * 0.2)
            } else if (mark.bills[i] >= 100 && mark.bills[i] < 
300) {
                mark.tips[i] = (mark.bills[i] * 0.1)
            } else {
                mark.tips[i] = (mark.bills[i] * 0.25)
            }
        }
    },
    calcFinal: function(j) {
        for (var j = 0; j < mark.bills.length; j++) {
            mark.final[j] = mark.bills[j] + mark.tips[j]
        }
    }
}
Here is my code for the final task of calculating the averages and printing the comparative result to
the console log.

function averageTip(tips) {
    x = 0;
    for (var i = 0; i < tips.length; i++) {
        x = x + tips[i]
    }
    return x / tips.length
}

var johnAvg = averageTip(john.tips)
var markAvg = averageTip(mark.tips)

console.log(johnAvg, markAvg)

if (johnAvg > markAvg) {
    console.log(john.name + " and his family tipped more than 
" + mark.name + " with an average tip of " + johnAvg)
} else if (markAvg > johnAvg) {
    console.log(mark.name + " and his family tipped more than 
" + john.name + " with an average tip of " + markAvg)
} else {
    console.log(mark.name + " and " + john.name + " both had t
he same average tip.")
}

FEEDBACK

- Failed to utilise the “this” function, could’ve used this to streamline code and create arrays without
explicitly defining them, like so:

calcTips: function() {
    this.tips = [];
    this.final = [];

    for (var i = 0; i < this.bills.length, i++)
}

Following this, we can perform our operations on this.tips and this.final, which makes copy/pasting
more simplistic also.

- We could create one method which fills both arrays by writing something like this:

for (var i = 0; i < this.bills.length, i++) {
        var percentage;
        var bill = this.bills[i];

        if (bill < 50) {percentage = 0.2};
        else if (bill >= 50 && bill < 200) {percentage = 0.15}
;
        else {percentage = 0.1}

        this.tips[i] = bill * percentage;
        this.final[i] = bill + bill * percentage
    }

We can see that this is clearly a more elegant solution.

- In my average, I should, as a matter of best practice, set var x = 0, as some software will be less
lenient with this variable assignment.

- I could also have stored the averages in the objects themselves, with a statement such as
john.average = calcAvg(john.tips), allowing me to do my final comparison using just object properties.

33. JavaScript Versions: ES5, ES6 / ES2015 and ES6+

A brief discussion of JavaScript versions.

A (very) short history of JavaScript:


1996 - JavaScript was released as LiveScript and name then changed to JavaScript to attract Java
developers. (Java is a completely different language which has nothing to do with JS.)

1997 - ES1 (ECMAScript 1) became the first version of the JS language standard.
We use ECMAScript to talk about the language standard and JavaScript to talk about the language in
practice.

2009 - ES5 was released with lots of news features.

2015 - ES6/ES2015 was released: the biggest update to the language ever!
2015 - JS changed to an annual release cycle.

2016…. present - Release of ES2016/ES2017/ES2018/….

ES5 is fully supported in all browsers today and safe to use.

ES6/ES7/ES8 are well supported in all modern browsers, but lack support in some older browsers. The
solution to this problem is to convert these JS versions back to ES5 using a process called transpiling
and polyfiling, which allows us to use most features. To check which features of modern JS versions
are supported in which browsers, there are compatibility tables available such as the ones found
here:
https://github.com/kangax/compat-table

Future versions are generally referred to together as “ESNext”. Some future features are already
supported in modern browsers, and we can already use some features in production with transpiling
and polyfiling.
In this course, we’ll start by using ES5 in the first part of the course and then ES6+ (ES6, ES7 ES8) in
the later part of the course.

The course will use the languages as follows:

ES5: - JS fundamentals
- How the language works
- DOM manipulation project
- Advanced language features
- Large real project

ES6+: - ES6/ES2015 introduction


- Asynchronous JS
- AJAX and API calls
- Modern dev setups (Webpack and Babel)
- Large real project

Course author believes that we will always have to understand ES5 in the future as much of the
learning material is written in ES5 and we will occasionally have to do professional work on older
codebases which are likely to be written in ES5.

You might also like