JavaScript Functions and Events (2023)

Notes taken from various websites including:

https://www.w3schools.com/js/js_whereto.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

JavaScript Functions

A JavaScript function is a block of JavaScript code, that can be executed when “called” for.

For example, a function can be called when an event occurs, like when the user clicks a button.

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.

Source

Function declarations
A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:

The name of the function.
A list of parameters to the function, enclosed in parentheses and separated by commas.
The JavaScript statements that define the function, enclosed in curly brackets, { /* … */ }.
For example, the following code defines a simple function named square:

function square(number) {
return number * number;
}

The function square takes one parameter, called number. The function consists of one statement that says to return the parameter of the function (that is, number) multiplied by itself. The statement return specifies the value returned by the function:

return number * number;

Parameters are essentially passed to functions by value — so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or in the code which called that function.

When you pass an object as a parameter, if the function changes the object’s properties, that change is visible outside the function, as shown in the following example:

function myFunc(theObject) {
theObject.make = “Toyota”;
}

const mycar = {
make: “Honda”,
model: “Accord”,
year: 1998,
};

console.log(mycar.make); // “Honda”
myFunc(mycar);
console.log(mycar.make); // “Toyota”

Differences between functions and methods (taken from Geeks for Geeks)

FunctionMethod
A JavaScript function is a block of code designed to perform a particular task.The javascript method is an object property that has a function value.
Syntax of Function is -:function functionName(parameters) {
   // Content
}
Syntax of Method is -:object = {
   methodName: function() {
       // Content
   }
};object.methodName()
A function can pass the data that is operated and may return the data. The method operates the data contained in a Class.
Data passed to a function is explicit.A method implicitly passes the object on which it was called.
A function lives on its own.A method is a function associated with an object property.
A function can be called directly by its name A method consists of a code that can be called by the name of its object and its method name using dot notation or square bracket notation.
Functions are helpful because it increases the reusability of the code.Javascript includes some in-built methods also for example -: parseInt() Method
The () Operator is used to Invoke the FunctionWe can access object method by the following the syntax -:objectName.methodName()

External JavaScript Advantages

Javascript can also be placed in the <body> of a HTML document and in external sheets with the file extension .js (not sure why I thought this was relevant, but there you go!)
Placing scripts in external files has some advantages:

It separates HTML and code
It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads

JavaScript Output

ref

JavaScript can interact with the DOM/webpage and display different data in several ways:

  • Wrting into an HTML element using innerHTML
  • Wirting into the HTML output using document.write()
  • Writing into an alert box, using window.alert()
  • Wiring into the browser console, using console.log()

Using InnerHTML

use the document.getElementByID(id) method.

JavaScript Events

HTML events are “things” that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can “react” on these events.

more info at w3schools

JavaScript’s interaction with HTML is handled through events that occur when the user or the browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.

Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.

Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code.

Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see a few examples to understand a relation between Event and JavaScript −

onclick Event Type

This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.

Example

Try the following example.

 Live Demo

<html>
   <head>   
      <script type = "text/javascript">
         <!--
            function sayHello() {
               alert("Hello World")
            }
         //-->
      </script>      
   </head>
   
   <body>
      <p>Click the following button and see result</p>      
      <form>
         <input type = "button" onclick = "sayHello()" value = "Say Hello" />
      </form>      
   </body>
</html>

More info at Tutorialspoint (includes a massive list of event types)

The This Keyword in JavaScript (2023)

This – references the object that is executing the current function

  • If the function is part of an object, we call that function a method.

“This” will reference that object

  • if the function is a regular function

“This” will reference the global / window object

in case, like me, you’ve forgotten what an object is, Mozilla describes it as

“In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.”

Example of an Object – with a function/method:

const person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

In the example above, this refers to the person object. Because the function is in an object

Some more notes about the This Keyword, robbed from around the web:

In general, the this references the object of which the function is a property. In other words, the this references the object that is currently calling the function.

Javascript Tutorial

Suppose you have an object called counter that has a method next(). When you call the next() method, you can access the this object.

let counter = {
  count: 0,
  next: function () {
    return ++this.count;
  },
};

counter.next();

Inside the next() function, the this references the counter object. See the following method call:

counter.next();

Global context

In the global context, the this references the global object, which is the window object on the web browser or global object on Node.js.

This behavior is consistent in both strict and non-strict modes. Here’s the output on the web browser:

console.log(this === window); // trueCode language: JavaScript (javascript)

If you assign a property to this object in the global context, JavaScript will add the property to the global object as shown in the following example:

this.color= 'Red';
console.log(window.color); // 'Red'

The this keyword is a source of confusion.

If you just type and run “this”, you’ll get the window object (the top of the DOM hierarchy)

If you type “this” inside a function, the value of this is contextual and dynamic. It can change.

Mozilla JS website

In most cases, the value of this is determined by how a function is called (runtime binding). It can’t be set by assignment during execution, and it may be different each time the function is called. The bind() method can set the value of a function’s this regardless of how it’s called, and arrow functions don’t provide their own this binding (it retains the this value of the enclosing lexical context).

In non–strict mode, this is always a reference to an object. In strict mode, it can be any value. For more information on how the value is determined, see the description below.

Description

The value of this depends on in which context it appears: function, class, or global.

Function context

Inside a function, the value of this depends on how the function is called. Think about this as a hidden parameter of a function — just like the parameters declared in the function definition, this is a binding that the language creates for you when the function body is evaluated.

For a typical function, the value of this is the object that the function is accessed on. In other words, if the function call is in the form obj.f(), then this refers to obj. For example:

function getThis() {
  return this;
}

const obj1 = { name: "obj1" };
const obj2 = { name: "obj2" };

obj1.getThis = getThis;
obj2.getThis = getThis;

console.log(obj1.getThis()); // { name: 'obj1', getThis: [Function: getThis] }
console.log(obj2.getThis()); // { name: 'obj2', getThis: [Function: getThis] }

More info and better description of this keyword on the Mozilla website here

Arrow Functions vs Regular Functions in JavaScript (2023)

JavaScript has 2 types of functions.

Normal/regular functions

Arrow functions

Arrow functions are simpler and shorter.

A normal JS function, with arguments (stuff in brackets), which returns something:

function multiply(num1, num2) {
  const result = num1 * num2
  return result
}

The same function, as an arrow function is:

const multiply = (num1, num2) => {
  const result = num1 * num2
  return result
}

If the only statement, is the return statement, then the arrow function can be even shorter:

const multiply = (num1, num2) => num1 * num2

Reference

Freecodecamp


You can define functions in JavaScript by using the “function” keyword.

// Function declaration
function greet(who) {
  return `Hello, ${who}!`;
}

The second way to define a function, is to use the arrow function syntax:

const greet = (who) => {
return Hello, ${who}!;
}


Reference

dmitripavlutin.com


  1. you can omit the return statement and curly braces in arrow function, when its a one line function

2. When the function has only 1 argument, the round bracket is optional.

JavaScript – Primitives Vs Objects

Notes about primitives and objects data types in JavaScript

I’ve got a bit fed up of the Udemy course I’m doing on JavaScript and the videos, so I’m taking notes from different websites and I’ll do a summary at the end.

edureka.co

Primitive Data Types

Primitive data types are number, string, boolean, NULL, Infinity and symbol. Non-primitive data types is the object. The JavaScript arrays and functions are also objects. For more check out this web developer course online.

flaviocopes

Follow Flavio on Twitter

What is the main difference between primitive types and objects in JavaScript?

First, let’s define what are primitive types.

Primitive types in JavaScript are

  • strings
  • numbers (Number and BigInt)
  • booleans (true or false)
  • undefined
  • Symbol values

null is a special primitive type. If you run typeof null you’ll get 'object' back, but it’s actually a primitive type.

Everything that is not a primitive type is an object.

Functions are objects, too. We can set properties and method on functions. typeof will return 'function' but the Function constructor derives from the Object constructor.

The big differences between primitive types and objects are

  • primitive types are immutable, objects only have an immutable reference, but their value can change over time
  • primitive types are passed by value. Objects are passed by reference
  • primitive types are copied by value. Objects are copied by reference
  • primitive types are compared by value. Objects are compared by reference

dev.to

Javascript Types

There are eight data types in Javascript:

  1. string
  2. number
  3. bigint
  4. boolean
  5. undefined
  6. null
  7. symbol
  8. Object

The first 7 of them are commonly called Primitive Types and everything else are Object Types.

Primitive Types

They can only store a single data, have no methods and are immutable. (An immutable value is one whose content cannot be changed without creating an entirely new value. In JavaScript, primitive values are immutable — once a primitive value is created, it cannot be changed, although the variable that holds it may be reassigned another value).

That’s another interesting point! Primitive Types have no methods but, except for null and undefined, they all have object equivalents that wrap the primitive values then we’re able to use methods.

For string primitive there is String object, for number primitive there is Number, and so there are BooleanBigInt and Symbol.

Javascript automatically converts the primitives to their corresponding objects when a method is to be invoked. Javascript wraps the primitive and call the method.

Object Types

Differently from the primitives, Objects can store collections of data, their properties, and are mutable.

Differences between types

1. Assigning to a variable and copying value

The difference in the way the values are stored in variables is what makes people usually call Object Types as Reference Types.

Primitive Types

When we assign a primitive type to a variable, we can think of that variable as containing that primitive value.

let car = "tesla"
let year = 2021

// Variable - Value
// car      - "tesla"
// year     - 2021

So when we assign this variable to another variable, we are copying that value to the new variable. Thus, primitive types are “copied by value”.

let car = "tesla"
let newCar = car

// Variable - Value
// car      - "tesla"
// newCar   - "tesla"

Since we copied the primitive values directly, both variables are separate and if we change one we don’t affect the other.

let car = "tesla"
let newCar = car

car = "audi"

// Variable - Value
// car      - "audi"
// newCar   - "tesla"

Object Types

With Object Types things are different. When we assign an object to a variable, the variable is given a reference to that value. This reference stores the address to the location of that value in memory(techically more than that but let’s simplify). So the variable doesn’t has the value itself.

Let’s imagine the variable, the value it stores, the address in memory and the object in the coming snippets:

let cars = ["tesla"]

// Variable - Value                 - Address - Object
// cars      - <#001> (The reference) - #001    - ["tesla"]

This way, when we assign this variable to another one we are giving it the reference for the object and not copying the object itself like it happens with the primitive value. Thus, objects types are “copied by reference”.

let cars = ["tesla"]
let newCars = cars

// Variable  - Value                 - Address - Object
// cars      - <#001> (The reference) - #001    - ["tesla"]
// newCars   - <#001> (The reference stores the same address)

cars = ["tesla", "audi"]

// Variable  - Value                 - Address - Object
// cars      - <#001> (The reference) - #001    - ["tesla", "audi"]
// newCars   - <#001> (The reference stores the same address)

console.log(cars) // ["tesla", "audi"]
console.log(newCars) // ["tesla", "audi"]

Both of them have references to the same array object. So when we modify the object from one of the variables the other will also have this change.

  • Primitives are ummutable
  • You can’t alter the original primitive, instead it will return a new primitive value
  • Primitives, also have an object counterpart
  • When used with some methods, primitive values get wrapped into an object – once it’s finished, it turns back to a primitive value
  • It does this, because objects can have properties

  • The new keyword creates a blank object, it links the blank object to the parent

Using Get Stat to Monitor Rankings

Home – click on a website to view their rankings

Dashboard Tab

Graph at the bottom is arguably the most helpful.

  • Ranking Averages vs. Distribution Graph
  • If you use the date-picker to a date range of less than 2 weeks, you see daily fluctuations
  • It can be easier to click the # on the bottom left and view the number of KWs in the top 3

Keywords Tab

Click “show/Hide” on top right

Click “google base rank” and “ranking change” and “ranking URL”

Click on the “change” column. Those keywords with a positive change number, have gone down in rankings

Click on each Keyword to see ranking changes over a set date-range (use date-picker on top right)

Competitive Landscape

Compare latest column, to what the share of voice was 7 days ago, 30 days ago, up to 180 days ago.

Click the “site” menu on the top left column of the whole GUI – and pick a category of keywords to see specific changes

Scope and the Scope Chain in JavaScript

Scoping – where do variables live? – Where can we access a certain variable?

Notes from JS Udemy Course

JS is a high level, object oriented multi paradigm programming language

Lexical scoping – scoping is controlled by placement of functions and blocks in the code

Scope is the space or environment in which a certain variable is declared.

There are 3 main types of scope for variables:

Global scope

Function scope

Block scope

The Scope of a variable, is the region of our code where a certain variable can be accessed.

Scope Chain in JavaScript

I asked Chat GPT “what is scope chain in JavaScript?”

A scope chain in JavaScript refers to the hierarchical order of scopes, with each scope having access to its own variables and those of its parent scopes.

This hierarchy is established based on where functions and blocks are physically located within the code (lexical scoping).

When a variable is referenced in JavaScript, the engine looks for the variable in the current scope.

If it doesn’t find it there, it moves up the chain to the parent scope. This process continues all the way up to the global scope if necessary. If the variable isn’t found in the global scope, a ReferenceError is thrown.

Here’s a simple example to demonstrate the concept:

let globalVar = "global"; // global scope

function outer() {
    let outerVar = "outer"; // outer function scope

    function inner() {
        let innerVar = "inner"; // inner function scope

        console.log(innerVar); // "inner", found in inner scope
        console.log(outerVar); // "outer", not found in inner scope but found in outer scope
        console.log(globalVar); // "global", not found in inner or outer scopes but found in global scope
    }

    inner();
}

outer();


In the above example, the inner function’s scope chain includes the inner scope, the outer scope, and the global scope. The outer function’s scope chain includes the outer scope and the global scope. The global scope is at the top of every scope chain.

The scope chain is fundamental to understanding variable lookup and closure behavior in JavaScript.

Hoisting in JavaScript

I asked chatgpt to explain hoisting to me:

In JavaScript, hoisting is a behavior in which variable and function declarations are moved to the top of their containing scope during the compile phase, before the code has been executed. This means you can use a variable or function before it’s been declared in the code.

However, it’s crucial to note that while the declarations (not initializations) are hoisted, the assignments are not. This is why a variable declared and initialized after it’s used will return undefined.

Here’s an example of hoisting with variables:

javascriptCopy codeconsole.log(myVar); // Output: undefined

var myVar = 5;

console.log(myVar); // Output: 5

In this example, the declaration (var myVar) is hoisted to the top of the scope, but the assignment (myVar = 5) is not. That’s why the first console.log outputs undefined, and the second outputs 5.

Now, let’s see an example with functions:

console.log(myFunction()); // Output: This is hoisted!

function myFunction() {
  return "This is hoisted!";
}

Here, the entire function declaration (including the body) is hoisted, so you can call the function before it's declared in the code.

However, if we use function expressions and try to call it before it's defined, it will return undefined because only declarations are hoisted, not initializations:


console.log(myFunction); // Output: undefined

var myFunction = function() {
  return "This is not hoisted!";
}

In JavaScript ES6, let and const were introduced, which have different scoping rules from var. While var is function-scoped, let and const are block-scoped. However, they too are hoisted, but due to a mechanism known as the Temporal Dead Zone (TDZ), you cannot access them before declaration.


console.log(myVar); // Output: undefined
console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization

var myVar = 5;
let myLet = 10;

In this code, trying to log myLet before it's declared results in a ReferenceError, while myVar is undefined due to the hoisting and the difference in behavior between var and let/const.

Then I asked Bard:

JavaScript hoisting is a concept that refers to the fact that variable declarations are moved to the top of their scope before the code is executed. This means that you can access a variable even if it is declared after the line of code where you first try to use it.

For example, the following code will print “Hello World!” even though the message variable is declared after the line where it is first used:

JavaScript

console.log("Hello World!");
var message = "Hello World!";

This is because the JavaScript engine will hoist the variable declaration to the top of the scope, before the code is executed. This means that the variable will be defined and accessible even though it is declared after the line where it is first used.

It is important to note that hoisting does not affect the value of the variable. In the example above, the value of the message variable will still be “Hello World!” even though it is declared after the line where it is first used.

Hoisting can be a useful concept to understand, but it can also lead to errors if you are not careful. For example, the following code will throw an error because the message variable is not defined when it is first used:

JavaScript

var message = "Hello World!";
console.log(message);

This is because the message variable is not defined until after the line where it is first used. To avoid this error, you should always declare variables before you use them.

Here are some tips for avoiding errors when using hoisting:

  • Always declare variables before you use them.
  • Use the const keyword to declare constant variables.
  • Use the let keyword to declare local variables.
  • Use the strict mode to prevent errors from being thrown when variables are not declared.

I hope this explanation of JavaScript hoisting was helpful. Please let me know if you have any other questions.

Source HTML vs Rendered HTML

Summary

For an SEO Audit

You want to check that href links and H1s etc are in the source and the rendered HTML

Rendered HTML, is basically HTML after all the JS has run.

You also want to check that the rendered HTML is not too different to the source HTML.

View the site with JS turned off. Ideally images should still be there and href links should definitely still work with JS turned off.


Rendering process – start with the source HTML and CSS.

The browser parses the source html and CSS which creates the DOM and CSSOM.

The DOM is more important for SEO

The browser creates a DOM tree to identify elements on the website and where everything belongs and relates

The browsers takes the DOM and CSSOM and creates a render tree to lay everything out.

The tree is then used to create the actual pixels and layout of what you see.

JS may then be added to manipulate the DOM

You can turn the final DOM Tree, back into HTML – this is Rendered HTML

When you click View Source in your browser

This shows the SOURCE HTML

Developer Tools – Sources – SOURCE HTML

Network Tab in developer tools – SOURCE HTML

In the elements tab in Chrome in Dev Tools – you get the current DOM Content

https://support.google.com/webmasters/answer/11626894?hl=en

Overview

When you visit a page, the website sends HTML code to your browser. Often this source code includes additional resources such as scripts, which must be loaded, and which may alter the page code.

How to view Source HTML

Right-clicking “show source” typically shows only the original page code returned to the browser, before scripts and other resources have been loaded and run. But there are many instances, particularly when troubleshooting your page, when you need to see the code of the final, rendered page on the browser, after all resources have been loaded, and any scripts run. For example:

  • To search for Google Analytics or Google Tag Manager tags used in verification.
  • To debug page loading and display (that is, to check that all libraries and other resources that you want to be loaded are).
  • To look at structured data on the served page.

How to view the rendered source

Here are a few methods to view the rendered source code for a web page:

  • In the Chrome browser: Right-click any part of the page and select Inspect to see all the HTML from the rendered page. Search for items in the rendered HTML with Control + F (Windows) or Command + F (Mac).
  • For a page on your own site:
    1. Inspect the URL, either by entering the URL directly in the URL Inspection tool, or by clicking an inspection link next to a URL shown in most Search Console reports.
    2. Click Test live URL > View tested page.
    3. The HTML tab shows the rendered HTML for the page.
  • For a page on any site, not just a site that you own:
    1. Open the Mobile-friendly Test.
    2. Enter the URL of the page. The page must be available to Google without a login, and not blocked by robots.txt.
    3. Click View tested page.
    4. The HTML tab shows the rendered HTML for the page.

Creating an Actionable 404 Report from Screaming Frog

Follow this protocol, to produce a sheet you can send to devs etc, to remove 404s

  • This will get rid of the site-wide 404s and some individual 404s

Run a crawl with Screaming Frog

Export the report –> Screaming Frog – Bulk Export  – Response Codes – Internal – Internal Client Error (4xxs)  (check 500s too)

In Excel – Copy and paste the “destination” URLs into a new sheet – into column A

Remove duplicates from the destination URLs that you’ve just copied into a new sheet

rename the colum – 404s Destination

Copy and paste the Source URLs and the Anchor Text into a new sheet.

Paste Source URLs in column A, and Anchor Text into column C

In cell B1 type – ” | “

In cell D1 – give the column the heading “Source | Anchor”

In cell D2 concatenate – =CONCATENATE(A2,$B$1,C2)

Drag the formula down.

You’ll now have the anchor text and the source URL together, so you can vlookup the destination (404) URL

Copy and paste all of the source URLs | Anchor Text and Destination URLs from the original sheet into columns B and C in the new sheet you just made.


You need “destination” in column B and “Source | Anchor Text” in column C, as vlookup has to go left to right

  • So you’ll have – Destination – Destination – Source | Anchor Text

Name column D in the new sheet “Example Source URL & Anchor Text” and in cell D2 enter the lookup – VLOOKUP(A2,B:C,2,0) (put “equals sign” before the V. Drag the formula down

Copy column A and paste into a new sheet. Name the sheet “Final”.

Copy column D with the vlookup and paste values into column B in the “Final Spreadsheet”

In “final”, you should now have all the unique 404s and an example of a page that links to those 404s with the anchor text.

  • If you’re sending the spreadsheet onto a dev or someone to fix the 404s, you are probably best sending the full sheet with all the inlinks to the 404s, plus the one you’ve just made. It depends how they go about fixing the 404s.

    Once 404s have been fixed, rerun a crawl and recheck them.

look out for 404s that are classed as  HTTP Redirects in the “type” column – these don’t seem to have a unique source URL. You may have to search for the URL in the search box in Screaming Frog and click the “inlinks” tab to see original link to the non-secure http page

If you like, before you send off the report to someone, you can double check the “destination” URLs definitely are 404s, by pasting them into screaming frog in “list” mode

Deleting a webpage – 404s and that

Had to do this today, would have helped to have a bit of a process written down…

  • Check if page ranks for anything
  • if it does, then consider redirecting (301ing) to most relevant/related page (in regards to what it ranks for)
  • 410 is better than 404 according to Yoast – for a deleted page
  • Remove internal links from page copy etc and menus (crawl site if poss)

https://yoast.com/deleting-pages-from-your-site/

JavaScript – What is the DOM & DOM Manipulation? [2023]

The Document Object Model – is a structured representation of an HTML document.

You can use the DOM to “connect” HTML to CSS and JS.

The DOM is often said to have a tree structure or a hierarchy like a family with children and parents

Image source

Selecting & Manipulating Elements with JavaScript

You can use “document” to ‘enter’ the document – as in the top level of the HTML document as shown in the tree diagram above.

  • use “querySelector” to select a specific element in the DOM.

For example document.querySelector(‘.message’).textContent

Will select the text content of the element with the class of “message”

Once you have selected the content, use the equals sign = to update it.

document.querySelector(‘.message’).textContent = ‘Correct Number!’

The ‘code’ on the line above, will change the text-content found in the element .message to “Correct Number!”

“textContent” will only work if the element is something like a paragraph, that holds content.

If you have a value input field, like on a form or something similar, you may have to use .value instead of .textContent

document.querySelector(‘.guess’).value = 23;

The code on the left, adds “23” as the input value to the form/input field on the right^

Screenshot from The Complete JavaScript Course

Handling Click Events

In this example, the button has a class of “check”

document.querySelector(‘.check’) – will select the button with the class of “check”

Then we need to use the addEventListener() method. The addEventListener method, basically looks out for events such as button clicks.

Image Source

Event Listener ^looks out for events such as button clicks.

We can add the event we want to look out for, in this example a click:

addEventListener(‘click’)

  • Now we need to tell the event listener what to do what it observers a click

addEventListener(‘click’ function () {
console.log(document.querySelector(‘.guess’).value);});

The code in bold, will take the value from the element called “guess” and print it to the “console.log”.

Screenshot from The Complete JavaScript Course

The code above prints 9 to the console.log

the element with the class of “guess” is the form input field containing the number 9:

Adding “Game Logic”

The aim of game in the screenshot above – guess the secret number

We need to randomly create a number and then tell the user when the number they guess is too high, too low or correct.

  • Producing the secret number

const number = (Math.truncMath.random()*20)

Math.random gives a number between 0 and 1

Match.trunc rounds up or down the number to the nearest whole number.

Multiplting the random number by 20 makes the number, well, larger

  • Checking the User Input Vs the Secret Number

if (!guess) {

document.querySelector(‘.message’).textContent = ‘No Number’;}

else if (guess === secretNumber) {

document.querySelector(‘.message‘).textContent = ‘Correct Number!’;

}

The code above will print “No number” if a number isn’t entered into the relevant form field.

if the number entered (the guess), is equal to the secretNumber – then the code will print “Correct Number!” – to the element with the class of “message“.

What if the guess is greater than the Secret Number?

else if (guess > secretNumber) {

document.querSelector(‘.message’).textContent=’Too high!’

and if it’s too low:

else if (guess < secretNumber) {

document.querSelector(‘.message’).textContent=’Too low!’

So all the code together will look like:

Adding a Score to The Game

The score will start at 20 and decrease for every wrong guess.

So, if the user guesses too low, reduce the score by 1

We also need to add a variable for the original/starting score, after the secretNumber is declared (or the code to create the secretNumber anyway)

Declare the score with:

let score = 20;

The score is part of the “application state”. The score is available in the code and not just in the DOM

Game Over

To tell the player when they’ve lost the game, we need to add a condition related to the score variable:

if (score > 1) {

https://www.udemy.com/course/the-complete-javascript-course/learn/lecture/22648419#learning-tools

Manipulating CSS When Player Wins- Change Background Colour

First select the whole <body> element

document.querySelector(‘body’).style.backgroundColor = ‘#60347’;

Implementing a High Score ‘Box’

Just like the regular, current score, we need to store the high-score in a variable.

use the code

let highscore = 0;

We need to check if the current score is greater than the existing game’s score

if (score > highscore) {

highscore = score;

}

Assuming the “HighScore” Box has already been made – we need to check what the class is.

In the this case, the class = “highscore”

Now we need a way to update the highscore, when the current score is greater.

document.querySelector(‘.highscore’).

textContent = highscore;

https://www.udemy.com/course/the-complete-javascript-course/learn/lecture/22648427#learning-tools

Getting Rid of Duplicate Code (DRY Principle)

The code if the guess is too high, or if the guess is too low code is pretty much duplicate code

Remember

Dont Repeat Yourself DRY

There’s no problem starting out with repeated code, and then refactor the code once it’s all working

  • ID duplicate or close-duplicate code
  • Refactor the facker

Change the code above, to a “when guess is wrong” code block.

Use a ternary operator