מילת ההצהרה const משמשת להכזרה על משתנה קבוע שאין אפשרות לשנות את הערך שלו.
 

תחביר

const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
nameN
שם המשתנה.
valueN
הערך של המשתנה.

תיאור

בשפת ג'אווה סקריפט אנו משתמשים במשתנים על מנת להחזיק ערכים שונים.
הצהרה על משתנה באמצעות const הופכת אותו לקבוע ולא ניתן לשנות את הערך שלו.
הקצאת ערך למשתנה ללא הצהרה מראש הופכת אותו למשתנה גלובלי, אך בשונה מהצהרה באמצעות var הוא אינו כפוף לאובייקט האב window.
חשוב לציין שהצהרה באמצעות const לא מבצעת Hoisting.

דוגמאות

הדוגמה הבאה ממחישה כיצד מתנהגים משתנים קבועים.

// NOTE: Constants can be declared with uppercase or lowercase, but a common
// convention is to use all-uppercase letters.

// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;

// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;

// MY_FAV is 7
console.log('my favorite number is: ' + MY_FAV);

// trying to redeclare a constant throws an error -  Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared
const MY_FAV = 20;

// the name MY_FAV is reserved for constant above, so this will fail too
var MY_FAV = 20;

// this throws an error too
let MY_FAV = 20;

// it's important to note the nature of block scoping
if (MY_FAV === 7) { 
    // this is fine and creates a block scoped MY_FAV variable 
    // (works equally well with let to declare a block scoped non const variable)
    let MY_FAV = 20;

    // MY_FAV is now 20
    console.log('my favorite number is ' + MY_FAV);

    // this gets hoisted into the global context and throws an error
    var MY_FAV = 20;
}

// MY_FAV is still 7
console.log('my favorite number is ' + MY_FAV);

// throws an error - Uncaught SyntaxError: Missing initializer in const declaration
const FOO; 

// const also works on objects
const MY_OBJECT = {'key': 'value'};

// Attempting to overwrite the object throws an error - Uncaught TypeError: Assignment to constant variable.
MY_OBJECT = {'OTHER_KEY': 'value'};

// However, object keys are not protected,
// so the following statement is executed without problem
MY_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable

// The same applies to arrays
const MY_ARRAY = [];
// It's possible to push items into the array
MY_ARRAY.push('A'); // ["A"]
// However, assigning a new array to the variable throws an error - Uncaught TypeError: Assignment to constant variable.
MY_ARRAY = ['B'];

מפרט

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Let and Const Declarations' in that specification.
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Let and Const Declarations' in that specification.
Draft No changes.

תאימות דפדפן

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
Basic supportChrome Full support 21Edge Full support YesFirefox Full support 36
Notes
Full support 36
Notes
Notes Prior to Firefox 13, const is implemented, but re-assignment is not failing.
Notes Prior to Firefox 46, a TypeError was thrown on redeclaration instead of a SyntaxError.
IE Full support 11Opera Full support YesSafari Full support 5.1WebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 36
Notes
Full support 36
Notes
Notes Prior to Firefox 13, const is implemented, but re-assignment is not failing.
Notes Prior to Firefox 46, a TypeError was thrown on redeclaration instead of a SyntaxError.
Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes

Legend

Full support  
Full support
See implementation notes.
See implementation notes.

ראה גם

Document Tags and Contributors

Contributors to this page: fabio.rahamim
Last updated by: fabio.rahamim,