Objects:
In JavaScript, an object is a collection of key-value pairs used to store multiple values in a single variable. It can contain data (properties) and functions (methods).
*Syntax of an Object:
*
const person = {
name: "John",
age: 30,
isStudent: false,
greet: function() {
console.log("Hello!");
}
};
**
Explanation:**
- name, age, and isStudent are properties.
- greet is a method (a function inside the object).
- Keys are always strings (even if you don’t write quotes).
- Values can be any data type: string, number, boolean, array, another object, or function. ** Why Use Objects?** To represent real-world entities (like a user, product, etc.). To group related data and behavior together.
Hoisting:
Hoisting is JavaScript's behavior of moving declarations to the top of their scope (before code execution).
This applies to:
- var variable declarations
- Function declarations
- NOT let and const (they are not hoisted in the same way)
In simple terms:
You can use variables and functions before you declare them.
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 and const 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 (as undefined), not the function.
this:
In JavaScript, the this keyword refers to an object.
The this keyword refers to different objects depending on how it is used:
Example:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
_this is not a variable. It is a keyword. You cannot change the value of this.
Top comments (0)