Register to get access to free programming courses with interactive exercises

Properties and methods JavaScript fundamentals

The data we use in our programs can have important properties, such as strings having length. As you will see later, this property is required to implement string conversion algorithms (e.g., string reversal). So how do you find out the length of a string? In many languages, string length is calculated with a special function, and it looks a bit like this:

import { length } from 'hexlet-basics/string';

const name = 'Robb';
console.log(length(name)); // => 4

In JavaScript, properties are built into the language. They are written with a dot right after a variable (or a constant):

const name = 'Robb';
const len = name.length;
console.log(len); // => 4

Properties are linked with the data they are taken from. For primitive types, e.g. strings, all property descriptions are described in the documentation. However, numbers have no properties at all.

JavaScript allows you to call properties that do not exist (e.g. in the case of typos). In this case their value is undefined:

const name = 'Robb';
console.log(name.whatIsThat); // => undefined

Self-check. What will console.log(name[name.length]) print for the variable name above? Why is the result like that?

Methods

In addition to properties, data has methods - functions within properties. Basically, it means that methods work and are called like functions, but do it like a property using a dot notation.

const name = 'Robb';
const upperName = name.toUpperCase();
console.log(upperName); // => 'ROBB'

Inline methods always apply to the data they are linked with. The .toUpperCase() method returns the same string but converts all characters to uppercase. Data usually has many more methods than properties, for example, strings have several dozens of them. In the documentation they may seem to be described weirdly at first glance: String.prototype.toLowerCase(). This description reveals some internal implementation details which are not important right now, moreover, we haven't studied all the necessary basics to talk about prototypes.

Numbers have methods as well:

const temperature = 22.93;
// Rounding to one decimal place
const roundedTemperature = temperature.toFixed(1);
// This method returns a string containing the rounded number
console.log(roundedTemperature); // => '22.9'

// They can be called directly like this
// The brackets are necessary, or else it won't work
(22.93).toFixed(1); // '22.9'

FYI. Technically, it's a bit more complicated. It's not the numbers themselves that have methods, but the data (objects) of the Number type. Numbers written in variables or constants are automatically converted to this type when called, this process is called boxing.

Why do we need methods? Why not just use functions? The situation with numbers is even more complicated. Some operations are implemented as methods of numbers, such as .toFixed(), and most of them are implemented as methods accessible via Math.

There are two reasons why it's done that way:

  1. It's just always been like that. JavaScript was developed a little too quickly, so not everything was well thought out
  2. Not all functions are linked to a specific value. For example, Math.min(). This function finds the minimum of all numbers passed to it. It doesn't make sense to make this function a method of a particular number, like (1).min(). It has no connection to any particular number

On the other hand, functions that work with a particular number should be implemented as methods for the sake of consistency. Such functions include calculating the modulus of a number. I.e., instead of Math.abs(-10), it's more reasonable to have (-10).abs().

As for methods in general, things are not so straightforward. Some languages have no methods and have no issues. Other languages use methods as the main tool for building functions, and even here regular functions are always used along with methods. JavaScript is a language that uses both approaches and actively uses both normal functions and methods.

Immutability

What will the last call print?

const name = 'Tirion';
console.log(name.toUpperCase()); // => TIRION
console.log(name); // => ?

The answer to this question depends on how well you understood the lesson about the immutability of primitive data types. Calling the .toUpperCase() method returns a new value with all letters converted to uppercase but doesn't (and can't) change the original string. So the constant (or variable, it doesn't matter here) will contain the original 'Tirion' value. This logic holds true for methods of all primitive types. Moreover, attempting to change the value of a property of this data will lead to nothing:

const name = 'Tirion';
console.log(name.length); // => 6
name.length = 100;
console.log(name.length); // => 6

You can replace the value with a new one instead of changing it. This requires variables:

let name = 'Tirion';
name = name.toUpperCase();
console.log(name); // => TIRION

Properties and methods as expressions

Properties and methods are expressions just like variables, constants, or function calls, which means they can be combined in many different ways.

In operations:

const name = 'Shaya';
name.length + 5; // 10
`hi, ${name.toUpperCase()}!`; // hi, SHAYA!

In function parameters:

const name1 = 'Robb';
const name2 = 'Shaya';
console.log(name2.length); // => 5
console.log(name2.toLowerCase()); // => shaya
console.log(Math.min(name1.length, name2.length)); // => 4

https://replit.com/@hexlet/js-basics-properties-method


Hexlet Experts

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions