Skip to content

Dot operator in JavaScript | Example code

  • by

The JavaScript dot (.) operator is simply an operator that sits between its operands, just like + and -. The variables stored in an object we access via the dot operator are called properties.

objectName.propertyName
objectName.methodName()

Here, objectName represents the name of the object, propertyName is the name of the property you want to access, and methodName is the name of the method you want to call.

For example, let’s say you have an object person with properties name and age, and a method sayHello():

const person = {
  name: 'John',
  age: 30,
  sayHello: function() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
};

You can access the properties of the person object using the dot operator:

console.log(person.name); // Output: John
console.log(person.age); // Output: 30

You can call the sayHello method using the dot operator as well:

person.sayHello(); // Output: Hello, my name is John and I am 30 years old.

JavaScript’s object support is the notion of chaining dots together to dive down into complex structures.

Dot operator in JavaScript

Simple example code access the object property using dot notation.

<!DOCTYPE html>
<html>
<body>

  <script>

    function Student(name, age, standard) {
      this.name = name;
      this.age = age;
      this.standard = standard;
    }
    let student = new Student("Rohan", 18, 12);

    console.log(student.name,student.age)
  </script>

</body>
</html> 

Output:

Dot operator in JavaScript

Using dot operator with functions

Functions are objects that can have properties just like any other object.

var t = function() {
    console.log('foo');
};

t.bar = function() {
    console.log('bar');
};

t.bar();

t.favColor = 'red';
t.shoeSize = 12;

Output: bar

Comment if you have any doubts or suggestions on this JS operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading