Object in JavaScript:
An object in JavaScript is a way to store related data and functions together in a single container, using key-value pairs.
Basic Example:
const car = {
brand: "Toyota",
model: "Corolla",
year: 2020
};
-
brand
,model
, andyear
are keys (also called properties). -
"Toyota"
,"Corolla"
, and2020
are values.
Accessing Values:
console.log(car.brand); // Output: "Toyota"
console.log(car["year"]); // Output: 2020
Adding or Changing Properties:
car.color = "red"; // add a new property
car.year = 2021; // change a property
Looping Through an Object:
for (let key in car) {
console.log(key + ": " + car[key]);
}
Object with a Function (Method):
const person = {
name: "Alice",
greet: function() {
console.log("Hello, I'm " + this.name);
}
};
person.greet(); // Output: Hello, I'm Alice
this
in JavaScript:
The this
keyword refers to the object that is currently executing the code.
Its value depends on where and how the function is called.
Common Cases of this
:
1. Inside an Object Method
const person = {
name: "Alice",
greet: function() {
console.log("Hi, I'm " + this.name);
}
};
person.greet(); // Output: Hi, I'm Alice
Here,
this
refers to theperson
object.
2. In a Regular Function (not in an object)
function show() {
console.log(this);
}
show(); // In browsers: `this` is the `window` object
3. In an Event Listener (Browser)
<button onclick="alert(this.innerText)">Click me</button>
this
refers to the button that was clicked.
4. Arrow Functions
const obj = {
name: "Bob",
greet: () => {
console.log("Hello, " + this.name);
}
};
obj.greet(); // Output: Hello, undefined
Arrow functions do not have their own
this
— they inherit it from the outer scope.
---# Hoisting in JavaScript:
Hoisting means that JavaScript moves variable and function declarations to the top of their scope (before the code is executed).
But only the declarations are hoisted, not the initializations.
Example: Variable Hoisting
console.log(x); // undefined
var x = 5;
Behind the scenes, JavaScript treats it like:
var x;
console.log(x); // undefined
x = 5;
var
is hoisted — declared at the top, but not assigned.
let
and const
Hoisting
console.log(y); // ReferenceError
let y = 10;
-
let
andconst
are hoisted, but they are not initialized. - They stay in a "temporal dead zone" until the line where they are defined.
Function Hoisting
greet(); // Hello!
function greet() {
console.log("Hello!");
}
Function declarations are fully hoisted — both the name and the body.
Function Expressions (NOT Hoisted)
sayHi(); // TypeError: sayHi is not a function
var sayHi = function() {
console.log("Hi!");
};
- Only the variable
sayHi
is hoisted (asundefined
), not the function.
Summary Table:
Type | Hoisted? | Usable before definition? |
---|---|---|
var |
Yes (declared) | Yes, but value is undefined
|
let / const
|
Yes (declared) | No (ReferenceError) |
Function declaration | Yes | Yes |
Function expression | Partially | No (TypeError) |
Top comments (0)