JavaScript Basics & Programming with JavaScript Notes - Cour$era

 Assessing Skills in HTML & CSS


1 Assessing Your Skills in HTML & CSS

A body element

A line containing html version information

A head element

2 Choose the correct HTML element for the most important heading.

<h1>

3 Identify all the structural tags that create new blocks on a web page. Select all that apply.

<nav>
<section>

4 Identify all the phrasing elements that the browser displays inline by default. Select all that apply.

<img>
<strong>
<a>
<span>

5 Identify elements that have no semantic value and should only be used if they are needed for styling purposes. Select all that apply.

<div>
<span>

6 Identify the reasons why semantic markup is important. Select all that apply.
It makes web pages more easily indexed by search engines.

7 Identify the tag with syntax errors.
<section id=important></section>

8 Which CSS rule has the most specificity?
#main { color: red; }
The # targets rules with ID attributes, and since an ID can be used only once on a web page, they are very specific.

9 Which rule will change the font size for this element?
<p class="intro">Here is an intro paragraph</p> .intro { font-size: 150%; }

11 How much horizontal screen space will the section with this CSS take up using the box-sizing model?
section { width: 200px; padding 20px; border: 5px solid black; margin: 20px }
290px

12 Which CSS display value would be best to use to make a short, unordered list of links display horizontally for navigation across a webpage?
ul { display: flex; }

13 Identify important considerations and best practices when building interactive web projects. Select all appropriate answers.
Make sure your HTML and CSS are properly formatted, following indentation standards.
Optimize images in an image editor to get file sizes as low as possible
Use the inspector in your browser to track down and identify problems, when troubleshooting your code.
Build for smaller screens first, then add layout for larger screens through CSS techniques, such as media queries.

It is important to follow standards and keep your projects as lean as possible.Use semantic HTML so that the structural meaning of the content is clear to machines.
Separate your HTML and CSS by using a linked stylesheet for all styling rules.


What is the padding box width of the following CSS rule?
div {
width: 10px;
padding: 20px;
margin: 40px;
}Ans: 50 pixels
The padding box width is the sum of the content width and the padding width. In this rule, it is 10 (content width) + 20 (padding left) + 20 (padding right) = 50.

Q:Based on the following CSS, what will be the margin-box width for div elements? div { width: 10px; padding-left: 5px; padding-right: 5px; margin-left: 5px; margin-right: 5px; }
A: 30
The margin-box width = content width + padding width + border width + margin width. In this scenario, the margin-box width is 30 pixels.
Border box width is the content width + padding width + border width

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$


Introduction to functional programming

In functional programming, data and functions that operate on it are clearly separated, not combined inside objects.

Many functions, by default, return the value of undefined.
We can say that the Functional Programming paradigm works by keeping the data and functionality separate. It's counterpart, OOP, works by keeping the data and functionality grouped in meaningful objects.

OOP helps us model real-life objects. It works best when the grouping of properties and data in an object makes logical sense - meaning, the properties and methods "belong together".

There are many more concepts and ideas in functional programming.
Here are some of the most important ones:
  • First-class functions
  • Higher-order function
  • Pure functions and side-effects
First-class functions: It is often said that functions in JavaScript are “first-class citizens”.
It means that a function in JavaScript is just another value that we can:
  • pass to other functions
  • save in a variable
  • return from other functions
Higher-order functions: A higher-order function is a function that has either one or both of the following characteristics:
  • It accepts other functions as arguments
  • It returns functions when invoked
There's no "special way" of defining higher-order functions in JavaScript.

Pure functions and side-effects: A pure function returns the exact same result as long as it's given the same values.

Another rule for a function to be considered pure is that it should not have side-effects. A side-effect is any instance where a function makes a change outside of itself.

This includes: 
-changing variable values outside of the function itself, or even relying on outside variables 
-calling a Browser API (even the console itself!) 
-calling Math.random() - since the value cannot be reliably repeated


When you use let and const to declare a variable, it is scoped to the block - even within if statements and loops, like the for or while loops. Therefore, the quantity variable you create will only exist within the for loop.  

Variables declared with const must be assigned during declaration.


print out when the following code runs?

var globalVar = 77;
function scopeTest() {
     var localVar = 88;
}
console.log(localVar);

ReferenceError: localVar is not defined --> localVar is scoped to the function so therefore it is undefined in the global scope.


Introduction to Object-Oriented Programming

The four fundamental OOP principles are inheritance, encapsulation, abstraction and polymorphism.

The Benefits of OOP:
  • Allows you to write modular code
  • Makes your code more flexible and
  • Makes your code reusable.
  • OOP Principles: Inheritance --> To setup the inheritance relation between classes in JavaScript, We can use the extends keyword, as in class B extends A.

    class Animal { /* ... class code here ... */ }
    class Bird extends Animal { /* ... class code here ... */ }
    class Eagle extends Bird { /* ... class code here ... */ }
  • OOP Principles: Encapsulation --> In the simplest terms, encapsulation has to do with making a code implementation "hidden" from other users, in the sense that they don't have to know how my code works in order to "consume" the code.
    Example: "abc".toUpperCase();

  • OOP Principles: Abstraction --> It is all about writing code in a way that will make it more generalized.
  • OOP Principles: Polymorphism --> Polymorphism is a word derived from the Greek language meaning "multiple forms". An alternative translation might be: "something that can take on many shapes".
The concat() method is exhibiting polymorphic behavior since it behaves differently based on the context - in this case, based on what data types I give it.


//concat strings
console.log("abc".concat("def")); // 'abcdef'
//concat arrarys
console.log(["abc"].concat(["def"])); // ['abc', 'def']
//using the + operator on two arrays
console.log(["abc"] + ["def"]); // ["abcdef"]


Constructors:
JavaScript has a number of built-in object types, such as: Math, Date, Object, Function, Boolean, Symbol, Array, Map, Set, Promise, JSON, etc.

These objects are sometimes referred to as "native objects".

Constructor functions, commonly referred to as just "constructors", are special functions that allow us to build instances of these built-in native objects. All the constructors are capitalized.

To use a constructor function, I must prepend it with the operator new.
For example, to create a new instance of the Date object, I can run: new Date().
However, not all the built-in objects come with a constructor function. An example of such an object type is the built-in Math object.
Running new Math() throws an Uncaught TypeError, informing us that Math is not a constructor.

Besides being more performant, due to the fact that each object in JavaScript is unique, you can't compare a String object with another String object, even when their values are identical.

In other words, if you compare new String('plum') === new String('plum'), you'll get back false, while "plum" === "plum" returns true. You're getting the false when comparing objects because it is not the values that you pass to the constructor that are being compared, but rather the memory location where objects are saved.

Instead of using Array, Function, and RegExp constructors, you should use their array literal, function literal, and pattern literal varieties: [], () {}, and /()/.

However, when building objects of other built-in types, we can use the constructor.
new Date();
new Error();
new Map();
new Promise();
new Set();
new WeakSet();
new WeakMap();

To inherit from one class to a new sub-class, JavaScript provides the extends keyword, which works as follows:
class Train {
    /*First of all, notice that there is no function keyword. Also, notice that the keyword constructor is used to define this function. You give your constructor function parameters inside an opening and closing parenthesis, just like in regular functions.
    The names of parameters are color and lightsOn. */
    constructor(color,lightsOn) {
        this.color = color;
        this.lightsOn = lightsOn;
    }
    toggleLights() {
        this.lightsOn = !this.lightsOn;
    }
    lightsStatus() {
        console.log('Lights on?', this.lightsOn);
    }
    getSelf() {
        console.log(this);
    }
    getPrototype() {
        var proto = Object.getPrototypeOf(this);
        console.log(proto);
    }
}

To inherit from one class to a new sub-class, JavaScript provides the extends keyword. In JavaScript classes, super is used to specify what property gets inherited from the super-class in the sub-class.

Notice that in addition to the inherited properties, you also automatically inherit all the methods that exist on the Train prototype, namely, the toggleLights(), lightsStatus(), getSelf(), and getPrototype() methods.

class HighSpeedTrain extends Train {
    constructor(passengers, highSpeedOn, color, lightsOn) {
        //inherited from the super-class
        super(color, lightsOn);
        this.passengers = passengers;
        this.highSpeedOn = highSpeedOn;
    }
}

Additionally, imagine you realized that you don't like how the toggleLights() method from the super-class works, and you want to implement it a bit differently in the sub-class. You can add it inside the HighSpeedTrain class. 
You realized that the HighSpeedTrain method should reuse the existing behavior of the original toggleLights() method, and so you used the super.toggleLights() syntax to inherit the entire super-class' method.
Next, you also inherit the behavior of the super-class' lightsStatus() method - because you realize that you want to have the updated status of the lightsOn property logged to the console, whenever you invoke the toggleLights() method in the sub-class.

You've added this third line to show that I can combine the "borrowed" method code from the super-class with your own custom code(i.e. console.log) in the sub-class.
class HighSpeedTrain extends Train {
    constructor(passengers, highSpeedOn, color, lightsOn) {
        //inherited from the super-class in the sub-class.
        super(color, lightsOn);
        this.passengers = passengers;
        this.highSpeedOn = highSpeedOn;
    }
    toggleHighSpeed() {
        this.highSpeedOn = !this.highSpeedOn;
        console.log('High speed status:', this.highSpeedOn);
    }
    toggleLights() {
        super.toggleLigths();
        super.lightsStatus();
        console.log('Lights are 100% operational.');
    }
}

Note: If I didn't use the super keyword in our sub-classes, the following error will be triggered: Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor.

Advanced JavaScript Features:

It's important to know that a for of loop cannot work on an object directly, since an object is not iterableContrary to objects, arrays are iterable. 

Built-in methods:

  • Object.keys() : receives an object as its parameter
  • Object.values() : 
  • Object.entries().

For- of loops and objects:

When you run on objects in JavaScript "for in" loops, iterate over the properties of the object and its prototype. While "for of" loops do this only for the objects' properties.

The for-of loop will iterate over the object's own properties only when using the Object.keys() method to return an array to loop over.The for-of loop will not iterate over the object and its prototype properties.

const mycar = {
    engine: true,
    steering: true,
    speed: "slow"
}
const sportsCar = Object.create(mycar);
sportsCar.speed = "fast";
console.log("The sportsCar object: ", sportsCar);

console.log('--------for-in is unreliable -------');
//for-in iterate over objects and ITS PROTOTYPE
for(prop in sportsCar) {
    console.log(prop);
}
console.log('*', "Iterating over object and its prototype");

console.log('------for-of is reliable------');
//for-of iterate over object's own properties only
for (prop of Object.keys(sportsCar)) {
    console.log(prop + ": " + sportsCar[prop]);
}
console.log('#', "Iterating over object's own properties only!");


What are template literals?

Template literals are an alternative way of working with strings.
Example of a template string: (backtick characters)
`Hello, World!`

With template literals, an expression can be embedded in a placeholder. A placeholder is represented by ${}, with anything within the curly brackets treated as JavaScript and anything outside the brackets treated as a string:  

Maps are made up of iterable key value pairs.

  • The spread operator allows you to pass all array elements into a function without having to type them all individually.
  • The rest operator allows you to take items from an array and use them to create a separate sub-array..The rest operator can be used to destructure existing array items, rather than typing them out again.
Set objects are collections of values. A value in the set may only occur once; it is unique in the set's collection. 

Template literals (Template strings): Template literals are literals delimited with backtick (`) characters.
Using normal strings
console.log("string text line 1\n" + "string text line 2");
// "string text line 1
// string text line 2"

Using template literals
console.log(`string text line 
string text line 2`);
// "string text line 1
// string text line 2"
Arrow function expressions (Syntax: () => expression)
An arrow function expression is a compact alternative to a traditional function expression, with some semantic differences and deliberate limitations.
  • Arrow functions don't have their own bindings to this, arguments, or super, and should not be used as methods.
  • Arrow functions cannot be used as constructors. Calling them with new throws a TypeError. They also don't have access to the new.target keyword.
  • Arrow functions cannot use yield within their body and cannot be created as generator functions.
param => expression

(param) => expression

(param1, paramN) => expression

() => {
  statements
}

param => {
  statements
}

(param1, paramN) => {
  statements
}

Following are JavaScript DOM selectors:
  • querySelector() method returns the first element in the document that matches the selector.
  • querySelectorAll() method returns all elements in the document that match the selector. 
  • getElementById() method returns a specific element whose id matches the selector.
  • getElementsByClassName() method returns all elements in the document that has the class specified in the selector.

  • What does the document variable return in JavaScript?
    console.log(document);
    The document object holds the entire structure of the active webpage in the browser's memory.
Other JavaScript environments:
Node.js can run in multiple settings, for example, on the command line, in a desktop application, or on the back-end of a web app (on a server). And it's a completely separate, standalone environment without ties to the JavaScript in the browser.


DISCLAIMER

The purpose of sharing the content on this website is to Educate. The author/owner of the content does not warrant that the information provided on this website is fully complete and shall not be responsible for any errors or omissions. The author/owner shall have neither liability nor responsibility to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the contents of this website. So, use the content of this website at your own risk.

This content has been shared under Educational And Non-Profit Purposes Only. No Copyright Infringement Intended, All Rights Reserved to the Actual Owner.

For Copyright Content Removal Please Contact us by Email at besttechreads[at]gmail.com

Post a Comment

Previous Post Next Post