javascript1
javascript1
null is "a value that represents no value". null is value that has been explicitly defined to a
variable. In this example we get a value of null when the fs.readFile method does not throw an error.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document Object Model</title>
</head>
<body>
<div>
<p>
<span></span>
</p>
<label></label>
<input>
</div>
</body>
The document object in JavaScript represents the DOM. It provides us many methods that we can use
to selecting elements to update element contents and many more.
🛠️ Modifying Elements
Method Description
element.setAttribute('name', 'value') Sets an attribute on an element.
element.getAttribute('name') Gets the value of an attribute.
element.removeAttribute('name') Removes an attribute.
element.classList.add('class') Adds a class to the element.
element.classList.remove('class') Removes a class.
element.classList.toggle('class') Toggles a class on/off.
element.classList.contains('class') Checks if a class exists.
element.style.property = 'value' Changes inline styles (e.g., style.color = 'blue' ).
🧹 Removing Elements
Method Description
element.remove() Removes the element from the DOM.
parent.removeChild(child) Removes a specified child from its parent.
🎯 Event Handling
Method Description
element.addEventListener('event', callback) Adds an event listener (e.g., click, input, etc.).
✅ Example
const button = document.createElement('button');
button.textContent = "Click Me";
button.classList.add('my-btn');
document.body.appendChild(button);
button.addEventListener('click', () => {
alert('Button Clicked!');
});
1. Capturing Phase – the event starts from window then goes down to every element until it reaches
the target element.
3. Bubbling Phase – the event bubbles up from the target element then goes up every element until it
reaches the window .
xproperty in the someprop property which have an undefined value. Remember properties in an object
which does not exist in itself and its prototype has a default value of undefined and undefined has no
property x .
6.What is event.target ?
In simplest terms, the event.target is the element on which the event occurred or the element
that triggered the event.
Sample JavaScript.
function clickFunc(event) {
console.log(event.target);
}
If you click the button it will log the button markup even though we attach the event on the
outermost div it will always log the button so we can conclude that the event.target is the element
that triggered the event.
1. If x and y have same type. Then compare them with the === operator.
8. If x is either string , symbol or number and y is type object Then return x == toPrimitive(y) .
Note: toPrimitive uses first the valueOf method then the toString method in objects to get the primitive
value of that object.
Let's have examples.
x y x == y
5 5 true
1 '1' true
0 false true
x y x === y
5 5 true
0 false false
If we use the === operator all the comparisons except for the first example will return false because
they don't have the same type while the first example will return true because the two have the same
type and value.
8. What is Hoisting?
Hoisting is the term used to describe the moving of variables and functions to the top of their (global
or function) scope on where we define that variable or function.
Ok to understand Hoisting, I have to explain the execution context.
The Execution Context is the "environment of code" that is currently executing. The Execution
Context has two phases compilation and execution.
Compilation - in this phase it gets all the function declarations and hoists them up to the top of their
scope so we can reference them later and gets all variables declaration (declare with the var
keyword) and also hoists them up and give them a default value of undefined.
Execution - in this phase it assigns values to the variables hoisted earlier and
it executes or invokes functions (methods in objects).
Note: only function declarations and variables declared with the var keyword
are hoisted not function expressions or arrow functions, let and const keywords.
Ok, suppose we have an example code in the global scope below.
console.log(y);
y = 1;
console.log(y);
console.log(greet("Mark"));
function greet(name){
return 'Hello ' + name + '!';
}
var y;
for example purposes, I commented on the assignment of variable and function call.
After the compilation phase finishes it starts the execution phase invoking methods and assigns
values to variables.
function greet(name) {
return 'Hello ' + name + '!';
}
var y;
console.log(y);
y = 1;
console.log(y);
console.log(greet("Mark"));
//Global's Scope
var globalVar = "abc";
function a(){
//testClosures's Scope
console.log(globalVar);
}
In this example, when we declare the a function the Global Scope is part of a's closure.
The reason for the variable globalVar which does not have a value in the image because of the reason
that the value of that variable can change based on where and when we invoke the a function.
But in our example above the globalVar variable will have the value of abc.
Ok, let's have a complex example.
function outerFunc(outerParam) {
function innerFunc(innerParam) {
const x = outerFunc(outerVar);
outerVar = "outer-2";
globalVar = "guess"
x("inner");
the reassignment happened after the invocation of the outer function and in that time when we invoke
the outerFunc function it's look up the value of outerVar in the Scope Chain, the outerVar will have a value
of "outer". Now, when we invoke the x variable which have a reference to the innerFunc , the
innerParamwill have a value of inner because thats the value we pass in the invocation and
the globalVar variable will have a value of guess because before the invocation of the x variable we
assign a new value to the globalVar and at the time of invocation x the value of globalVar in the Scope
Chain is guess.
we return the global variable i . So when we call one of those functions in that array after the loop it
logs 5 because we get
the current value of i which is 5 and we can access it because it's a global variable.
Because Closures keeps the references of that variable not its values at the time of it's creation. We
can solve this using IIFES or changing the var keyword to let for block-scoping.
const carDetails = {
name: "Ford Mustang",
This is what we would normally expect because in the getName method we return this.name , this in this
context refers to the object which is the carDetails object that is currently the "owner" object of the
function executing.
Ok, Let's some add some code to make it weird. Below the console.log statement add this three lines of
code
The second console.log statement prints the word Ford Ranger which is weird because in our
first console.log statement it printed Ford Mustang. The reason to this is that the getCarName method has
a different "owner" object that is the window object. Declaring variables with the var keyword in the
global scope attaches properties in the window object with the same name as the variables.
Remember this in the global scope refers to the window object when "use strict" is not used.
One way of solving this problem is by using the apply and call methods in functions.
The apply and call methods expects the first parameter to be an object which would be value
of this inside that function.
IIFE or Immediately Invoked Function Expression, Functions that are declared in the global
scope, Anonymous Functions and Inner functions in methods inside an object has a default
of this which points to the window object.
(function (){
console.log(this);
function iHateThis(){
console.log(this);
}
const myFavoriteObj = {
guessThis(){
function getThis(){
console.log(this);
}
getThis();
},
name: 'Marko Polo',
thisIsAnnoying(callback){
callback();
}
};
If we want to get the value of the name property which is Marko Polo in the myFavoriteObj object there
are two ways to solve this.
First, we save the value of this in a variable.
const myFavoriteObj = {
guessThis(){
const self = this; //saves the this value to the "self" variable
function getName(){
console.log(self.name);
}
getName();
},
name: 'Marko Polo',
thisIsAnnoying(callback){
callback();
In this image we save the value of this which would be the myFavoriteObj object. So we can access it
inside the getName inner function.
Second, we use ES6 Arrow Functions.
const myFavoriteObj = {
guessThis(){
const getName = () => {
//copies the value of "this" outside of this arrow function
console.log(this.name);
}
getName();
},
name: 'Marko Polo',
thisIsAnnoying(callback){
callback();
}
};
Arrow Functions does not have its own this . It copies the value of this of the enclosing lexical scope or
in this example the value of this outside the getName inner function which would be
the myFavoriteObj object. We can also determine the value of this on how the function is invoked.
function higherOrderFunction(param,callback){
return callback(param);
}
The map() method creates a new array with the results of calling a provided function on every
element in the calling array.
other way
Array.prototype.myMap = function(callback) {
// Ensure 'this' is an array
if (!Array.isArray(this)) {
throw new TypeError('Called on non-array');
}
return result;
};
console.log(doubled); // [2, 4, 6, 8]
The filter() method creates a new array with all elements that pass the test implemented by the
provided function.
//ES5 Version
function Person(firstName, lastName, age, address){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
Person.self = function(){
return this;
}
Person.prototype.toString = function(){
return "[object Person]";
}
//ES6 Version
class Person {
constructor(firstName, lastName, age, address){
this.lastName = lastName;
this.firstName = firstName;
this.age = age;
this.address = address;
}
static self() {
return this;
}
toString(){
getFullName(){
return `${this.firstName} ${this.lastName}`;
}
}
//ES5 Version
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.describe = function () {
return `I am ${this.getFullName()} and I have a position of ${this.jobTitle} and I started at ${this.y
earStarted}`;
}
Employee.prototype.toString = function () {
return "[object Employee]";
}
//ES6 Version
class Employee extends Person { //Inherits from "Person" class
constructor(firstName, lastName, age, address, jobTitle, yearStarted) {
super(firstName, lastName, age, address);
this.jobTitle = jobTitle;
this.yearStarted = yearStarted;
}
describe() {
return `I am ${this.getFullName()} and I have a position of ${this.jobTitle} and I started at ${this.
yearStarted}`;
}
class Something {
function AnotherSomething(){
}
const as = new AnotherSomething();
const s = new Something();
In this example, we wait for the click event in the element with an id of btnAdd, if it is clicked ,
the clickCallback function is executed. A Callback function adds some functionality to some data or
event. The reduce , filter and map methods in Array expects a callback as a parameter. A good analogy
for a callback is when you call someone and if they don't answer you leave a message and you expect
them to callback. The act of calling someone or leaving a message is the event or data and
the callback is the action that you expect to occur later.
function higherOrderFunction(param,callback){
return callback(param);
}`
In this example, we wait for the click event in the element with an id of btnAdd, if it is clicked ,
the clickCallback function is executed. A Callback function adds some functionality to some data or
event. The reduce , filter and map methods in Array expects a callback as a parameter. A good analogy
for a callback is when you call someone and if they don't answer you leave a message and you expect
them to callback. The act of calling someone or leaving a message is the event or data and
the callback is the action that you expect to occur later.
1. Callbacks
A callback is a function passed into another function to be called once an operation is complete.
javascript
CopyEdit
function fetchData(callback) {
setTimeout(() => {
fetchData((data) => {
console.log(data); // Logs after 1 second
});
2. Promises
A Promise represents a value that will be available now, later, or never.
javascript
CopyEdit
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received');
}, 1000);
});
};
3. Async/Await
Introduced in ES2017, async/await makes asynchronous code look synchronous.
javascript
CopyEdit
const fetchData = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data received');
}, 1000);
getData();
javascript
CopyEdit
Promise.all([fetchData1(), fetchData2()])
.then(([res1, res2]) => {
console.log(res1, res2);
});
5. Observable (Advanced)
Used in RxJS (Reactive Programming) for handling complex async data streams (e.g., Angular apps).
javascript
CopyEdit
import { of } from 'rxjs';
of('Hello').subscribe((data) => {
console.log(data);
});