В JavaScript ключевое слово const
используется для объявления постоянной переменной, которую нельзя переназначить после ее инициализации.
Вот несколько методов, которые можно использовать с ключевым словом const
в JavaScript:
-
Объявление постоянной переменной:
const PI = 3.14159; console.log(PI); // Output: 3.14159
-
Объявление объекта как константы:
const person = { name: "John", age: 30 }; person.name = "Jane"; // You can modify the properties of a constant object console.log(person.name); // Output: Jane
-
Объявление массива как константы:
const numbers = [1, 2, 3, 4, 5]; numbers.push(6); // You can modify the content of a constant array console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]
-
Использование
const
с функцией:const add = function(a, b) { return a + b; }; console.log(add(2, 3)); // Output: 5
-
Использование
const
в цикле:const arr = [1, 2, 3, 4, 5]; for (const num of arr) { console.log(num); }