JavaScript Questions

HTML DOM

1. What are nodes in the DOM?

icon

The DOM (Document Object Model) is a tree like representation of the HTML elements. The nodes in the DOM are the tags, texts, attributes. Eg:
If we have the following HTML code:

                                
<body>
    <p>This is a paragraph.</p>
    <div>This is a div element.</div>
    <h1>This is a heading.</h1>
</body>
                                
                            
Then the dom nodes are the body, p, div and h1. Also the texts are the text nodes in the DOM

2. Extract the text label of a button.

icon
                            
const btn = document.querySelector('button')
document.write(btn.textContent)
                            
                        

3. Create an element in DOM.

icon
                            const ul = document.createElement('ul')
                        

4. Create a new child element in DOM.

icon
                            
for(let i = 1; i <= 10; i++){
    let list = document.createElement('li')
    let text = document.createTextNode(`This is a list item ${i}`)
    list.appendChild(text)
    ul.appendChild(list)
}
                            
                        

5. Replace the child element with new child element.

icon
                            
let list = document.createElement('li')
let text = document.createTextNode(`This is a list item 100`)
list.appendChild(text)
const replace = ul.lastElementChild
// This replaces the last item in the list
ul.replaceChild(list, replace)
                            
                        

6. Select an element by element ID.

icon
                            const p = document.getElementById('content')
                        

7. Select an element by element Name.

icon
                            const inputBar = document.getElementsByName('name')
                        

8. Select an elements with tag name using query selector function

icon
                            const paragraphs = document.querySelectorAll('p')
                        

ES6 Functions

1. What does "ES" mean in JS?

icon

In JavaScript ES means ECMAScript which is the standard on which JavaScript is based. It is a scripting language specification developed and maintained by Ecma International, a standards organization. It defines the syntax, semantics, and behavior of the JavaScript programming language. Some of the versions of ECMAScript are ES5, ES6 etc.

2. Difference between Regular function and arrow functions

icon

The differences between regular functions and ES6 functions are as follows:

S.N Regular Functions ES6 Functions
1. The regular function can be invoked with the new keyword. The arrow function i.e. the ES6 function cannot be invoked using the new keyword.
2. They have this keyword, i.e. the this keyword points towards its own attributes in case of regular functions. They have not this keyword binded, if we use this keyword in arrow functions, it returns closest non arrow function.
3. The regular function has arguments object, i.e. if we don't know the number of arguments we can find it by using argument object. The arrow function does not have argumnet object binded to it.
4. Syntax:
                                        
function regularSum(a, b){
    return a + b;
}
console.log(regularSum(9,6));
                                        
                                    
Syntax:
                                        
const esSum = (a, b) => a + b
console.log(esSum(9,6));
                                        
                                    

3. Examples of Regular function and ES6 functions?

icon

ES6 Function (Arrow Function)

                            
const esSum = (a, b) => a + b
console.log(esSum(9,6));
                            
                        

Regular Function

                            
function regularSum(a, b){
    return a + b;
}
console.log(regularSum(9,6));
                            
                        

Promise Example

icon
                            
/**
* This function returns a promise.
* A promise is basically like a realy life promise,
* either it gets fulfilled (resolved) or 
* the promise is not fullfilled(rejected).
* This function takes name as a parameter and checks if the
* argument passed is 'ram', if the argument is ram the promise gets resolved
* else it gets rejected.
* 
* I have put a settimeout to simulate that the time delays.
* 
* For example: when fetching the data form api we may or may not get the data.
* so if we get the data in return the promise is resolved and we get the data or
* else we do not get the data and the promise is rejected.
*/
const displayRam = (name) => {
    return new Promise((resolve, reject) => {
        if(name.toLowerCase() === 'ram'){
            setTimeout(() => {
                resolve({username: "Ram", age: 20, email: 'ram@gmail.com'})
            }, 2000)
        }else{
            reject({message: "The name passed is invalid"})
        }
    })
}

/***
* In this function call the .then method is used to tell what to do after
* the promise is resolved. If the argument passed is 'ram' then the promise
* is resolved and the data is logged to the console, if the argument is
* something else the promise is rejected and it goes to the .catch block 
* and prints out the error.
*/
displayRam('ram')
    .then(data => console.log(data))
    .catch(err => console.log(err))
                            
                        

Async and Await Example

icon
                            
/**
* This is an asynchronous function.
* A async function always returns a promise.
* 
* So, in this function we use the promise we created
* in the promiseExample, since the promise can resolve or get rejected,
* we do not know when we will get the data so we add async to tell javascript
* that do something only after you have got the data till then do something else.
* 
* Async and await came into existence to avoid much promise chaining and callback hell.
* 
* In this function the function is called then the promise displayRam is called,
* It waits till it gets the return and then logs the data.
* 
* If the argument is different then it logs an error in the console.
*/
const callingFunction = async () => {
    const data = await displayRam('ram')
    console.log("Data: ", data);
}

callingFunction()