How can you extract the id attribute of all the elements in the document with JavaScript?

We can do it in three steps.

  1. Pull all the elements in the document irrespective of their Tag.
  2. Loop through all the Elements and see if the element has an attribute id
  3. If exists collect the attribute value into the output array
<!DOCTYPE html>
<html>
<body id="myBody">
    <div id="mainContainer" class="container-fluid">
        <div id="firstRow" class="row">
            <div id="fullCol" class="col-md-12">
                <h1 id="headingText">Hello World!</h1>
                <p id="subHeadingText">
                This is some sample text you're viewing on the Page.</p>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        (function () {
            let elements = document.getElementsByTagName("*");
            let ids = [];
            for (let i = 0; i < elements.length; i++) {
                let element = elements[i];
                if (element.id) {
                    ids.push(element.id);
                }
            }
            console.log(JSON.stringify(ids));
        })();
    </script>
</body>
</html>

output:
["myBody","mainContainer","firstRow","fullCol","headingText","subHeadingText"]

What is closure in Javascript?

  • In Javascript, a closure can be imagined as a concept of a function scope within a function.
  • The global execution context can be treated as a whole function in which all the script contents are present, and when we run the script the global function is called.
(function () {
    let k = 1;
    function kd() {
        console.log(`value of k is ${k}`);
    }
    kd();
})();

output:
value of k is 1
  • the inner functions present in this function can access all the variables that are defined in the outer scope and can modify them.
  • interestingly, these variables are still available even after the outer function has been executed and removed from memory.
function outer() {
    let counter = 0;
    function inner() {
        counter++;
        return counter;
    }
    return inner;
}

let instance = outer();
console.log(instance());
console.log(instance());
console.log(instance());

output:
1
2
3
  • In the above code block, the outer function is called only once, while when we call the inner function multiple times the variable counter which is native to the outer function is modified by the inner function and value persists.
  • This is conceptually similar to the context of methods and properties in a class where the methods can access and modify the variables of the class in an Object Oriented Language.

What is hoisting in JavaScript?

  • In Javascript, Hoisting is a concept in which Javascript brings all the variables declarations to the top of the script during execution.
  • This means that if a variable is initialized at some part of the script while being accessed before its definition is valid and doesn't throw an error.
  • But the assignment of variables happen at their original places which means that although variables are available before their actual place of declaration, their value is undefined.
console.log(`The value of x before is ${x}`);
var x = 10;
console.log(`The value of x after is ${x}`);

output:
The value of x before is undefined
The value of x after is 10
  • variables declared using var keyword in the global execution context are "hoisted", which is why the above code works without issue.
  • let keyword on the other hand by its design doesn't allow this to happen
console.log(`The value of x before is ${x}`);
let x = 10;
console.log(`The value of x after is ${x}`);

output:
console.log(`The value of x before is ${x}`);
                                        ^
ReferenceError: Cannot access 'x' before initialization

What are the different lifecycle hooks available to Components in Angular?

The below are the lifecycle hooks available in Angular. These are added by implementing the respective interface on the component.

  1. ngOnChange - before OnInit and whenever Input property changes in value
  2. ngOnInit - called once the Input properties are set, used to fetch initial data
  3. ngDoCheck - detect and act upon any changes that are by default on detected
  4. ngAfterContentInit - after loading any external entity into the component, such as a directive
  5. ngAfterContentChecked - after the content loaded is checked
  6. ngAfterViewInit - after the view is initialized
  7. ngAfterViewChecked - after the view is checked
  8. ngOnDestroy - just before the component is destroyed

How can you work with cookies in Angular?

To work with Cookies, we can make use of the CookieService which is a part of the ngx-cookie-service module.

  • Install: npm install --save ngx-cookie-service
  • Include:
import { CookieService } from 'ngx-cookie-service';
@NgModule({
  providers: [ CookieService ],
})
export class AppModule { }
  • Use:
constructor( private cookieService: CookieService ) { 
  this.cookieService.set( 'MyCookieKey', 'Hello There!' );
  this.cookieValue = this.cookieService.get('Test');
}

What is the difference between double equals (==) and triple equals (===) ?

In JavaScript, double equal operator (==) stands for value compare. The operands on either sides are converted into a common type and are compared for their values.

// JS converts the right type to equivalent left type
// 5 == '5'
// 5 == number('5') == 5
// result is true
5 == '5' 

the triple operator (===) stands for both value and type compare. The operands are not type converted and instead are looked for their type match as well.

5 === '5' // result is false since we're comparing a number and a string