DEV Community

Chithra Priya
Chithra Priya

Posted on

JS >>> Objects, Hosting, this keyword

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!");
  }
};
Enter fullscreen mode Exit fullscreen mode

**
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:

  1. var variable declarations
  2. Function declarations
  3. 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;
Enter fullscreen mode Exit fullscreen mode

Behind the scenes, JavaScript treats it like:

var x;
console.log(x); // undefined
x = 5;
Enter fullscreen mode Exit fullscreen mode
_var is hoisted — declared at the top, but not assigned._
Enter fullscreen mode Exit fullscreen mode

let and const Hoisting:

console.log(y); // ReferenceError
let y = 10;
Enter fullscreen mode Exit fullscreen mode
  • 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!");
}
Enter fullscreen mode Exit fullscreen mode
Function declarations are fully hoisted — both the name and the body.
Enter fullscreen mode Exit fullscreen mode

Function Expressions (NOT Hoisted):

sayHi(); // TypeError: sayHi is not a function

var sayHi = function() {
  console.log("Hi!");
};
Enter fullscreen mode Exit fullscreen mode
Only the variable sayHi is hoisted (as undefined), not the function.
Enter fullscreen mode Exit fullscreen mode

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;
  }
};
Enter fullscreen mode Exit fullscreen mode

_this is not a variable. It is a keyword. You cannot change the value of this.

Top comments (0)